]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/sqlite/lib/contrib/sqlite3.c
update: sync
[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.16.1.  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 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
310 # define _BSD_SOURCE
311 #endif
312
313 /*
314 ** Include standard header files as necessary
315 */
316 #ifdef HAVE_STDINT_H
317 #include <stdint.h>
318 #endif
319 #ifdef HAVE_INTTYPES_H
320 #include <inttypes.h>
321 #endif
322
323 /*
324 ** The following macros are used to cast pointers to integers and
325 ** integers to pointers.  The way you do this varies from one compiler
326 ** to the next, so we have developed the following set of #if statements
327 ** to generate appropriate macros for a wide range of compilers.
328 **
329 ** The correct "ANSI" way to do this is to use the intptr_t type. 
330 ** Unfortunately, that typedef is not available on all compilers, or
331 ** if it is available, it requires an #include of specific headers
332 ** that vary from one machine to the next.
333 **
334 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
335 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
336 ** So we have to define the macros in different ways depending on the
337 ** compiler.
338 */
339 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
340 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
341 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
342 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
343 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
344 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
345 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
346 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
347 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
348 #else                          /* Generates a warning - but it always works */
349 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
350 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
351 #endif
352
353 /*
354 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
355 ** 0 means mutexes are permanently disable and the library is never
356 ** threadsafe.  1 means the library is serialized which is the highest
357 ** level of threadsafety.  2 means the libary is multithreaded - multiple
358 ** threads can use SQLite as long as no two threads try to use the same
359 ** database connection at the same time.
360 **
361 ** Older versions of SQLite used an optional THREADSAFE macro.
362 ** We support that for legacy.
363 */
364 #if !defined(SQLITE_THREADSAFE)
365 #if defined(THREADSAFE)
366 # define SQLITE_THREADSAFE THREADSAFE
367 #else
368 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
369 #endif
370 #endif
371
372 /*
373 ** Powersafe overwrite is on by default.  But can be turned off using
374 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
375 */
376 #ifndef SQLITE_POWERSAFE_OVERWRITE
377 # define SQLITE_POWERSAFE_OVERWRITE 1
378 #endif
379
380 /*
381 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
382 ** It determines whether or not the features related to 
383 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
384 ** be overridden at runtime using the sqlite3_config() API.
385 */
386 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
387 # define SQLITE_DEFAULT_MEMSTATUS 1
388 #endif
389
390 /*
391 ** Exactly one of the following macros must be defined in order to
392 ** specify which memory allocation subsystem to use.
393 **
394 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
395 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
396 **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
397 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
398 **
399 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
400 ** assert() macro is enabled, each call into the Win32 native heap subsystem
401 ** will cause HeapValidate to be called.  If heap validation should fail, an
402 ** assertion will be triggered.
403 **
404 ** (Historical note:  There used to be several other options, but we've
405 ** pared it down to just these three.)
406 **
407 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
408 ** the default.
409 */
410 #if defined(SQLITE_SYSTEM_MALLOC) \
411   + defined(SQLITE_WIN32_MALLOC) \
412   + defined(SQLITE_ZERO_MALLOC) \
413   + defined(SQLITE_MEMDEBUG)>1
414 # error "Two or more of the following compile-time configuration options\
415  are defined but at most one is allowed:\
416  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
417  SQLITE_ZERO_MALLOC"
418 #endif
419 #if defined(SQLITE_SYSTEM_MALLOC) \
420   + defined(SQLITE_WIN32_MALLOC) \
421   + defined(SQLITE_ZERO_MALLOC) \
422   + defined(SQLITE_MEMDEBUG)==0
423 # define SQLITE_SYSTEM_MALLOC 1
424 #endif
425
426 /*
427 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
428 ** sizes of memory allocations below this value where possible.
429 */
430 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
431 # define SQLITE_MALLOC_SOFT_LIMIT 1024
432 #endif
433
434 /*
435 ** We need to define _XOPEN_SOURCE as follows in order to enable
436 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
437 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
438 ** so it is omitted there.  See ticket #2673.
439 **
440 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
441 ** implemented on some systems.  So we avoid defining it at all
442 ** if it is already defined or if it is unneeded because we are
443 ** not doing a threadsafe build.  Ticket #2681.
444 **
445 ** See also ticket #2741.
446 */
447 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) \
448  && !defined(__APPLE__) && SQLITE_THREADSAFE
449 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
450 #endif
451
452 /*
453 ** The TCL headers are only needed when compiling the TCL bindings.
454 */
455 #if defined(SQLITE_TCL) || defined(TCLSH)
456 # include <tcl.h>
457 #endif
458
459 /*
460 ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
461 ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
462 ** make it true by defining or undefining NDEBUG.
463 **
464 ** Setting NDEBUG makes the code smaller and run faster by disabling the
465 ** number assert() statements in the code.  So we want the default action
466 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
467 ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
468 ** feature.
469 */
470 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
471 # define NDEBUG 1
472 #endif
473 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
474 # undef NDEBUG
475 #endif
476
477 /*
478 ** The testcase() macro is used to aid in coverage testing.  When 
479 ** doing coverage testing, the condition inside the argument to
480 ** testcase() must be evaluated both true and false in order to
481 ** get full branch coverage.  The testcase() macro is inserted
482 ** to help ensure adequate test coverage in places where simple
483 ** condition/decision coverage is inadequate.  For example, testcase()
484 ** can be used to make sure boundary values are tested.  For
485 ** bitmask tests, testcase() can be used to make sure each bit
486 ** is significant and used at least once.  On switch statements
487 ** where multiple cases go to the same block of code, testcase()
488 ** can insure that all cases are evaluated.
489 **
490 */
491 #ifdef SQLITE_COVERAGE_TEST
492 SQLITE_PRIVATE   void sqlite3Coverage(int);
493 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
494 #else
495 # define testcase(X)
496 #endif
497
498 /*
499 ** The TESTONLY macro is used to enclose variable declarations or
500 ** other bits of code that are needed to support the arguments
501 ** within testcase() and assert() macros.
502 */
503 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
504 # define TESTONLY(X)  X
505 #else
506 # define TESTONLY(X)
507 #endif
508
509 /*
510 ** Sometimes we need a small amount of code such as a variable initialization
511 ** to setup for a later assert() statement.  We do not want this code to
512 ** appear when assert() is disabled.  The following macro is therefore
513 ** used to contain that setup code.  The "VVA" acronym stands for
514 ** "Verification, Validation, and Accreditation".  In other words, the
515 ** code within VVA_ONLY() will only run during verification processes.
516 */
517 #ifndef NDEBUG
518 # define VVA_ONLY(X)  X
519 #else
520 # define VVA_ONLY(X)
521 #endif
522
523 /*
524 ** The ALWAYS and NEVER macros surround boolean expressions which 
525 ** are intended to always be true or false, respectively.  Such
526 ** expressions could be omitted from the code completely.  But they
527 ** are included in a few cases in order to enhance the resilience
528 ** of SQLite to unexpected behavior - to make the code "self-healing"
529 ** or "ductile" rather than being "brittle" and crashing at the first
530 ** hint of unplanned behavior.
531 **
532 ** In other words, ALWAYS and NEVER are added for defensive code.
533 **
534 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
535 ** be true and false so that the unreachable code then specify will
536 ** not be counted as untested code.
537 */
538 #if defined(SQLITE_COVERAGE_TEST)
539 # define ALWAYS(X)      (1)
540 # define NEVER(X)       (0)
541 #elif !defined(NDEBUG)
542 # define ALWAYS(X)      ((X)?1:(assert(0),0))
543 # define NEVER(X)       ((X)?(assert(0),1):0)
544 #else
545 # define ALWAYS(X)      (X)
546 # define NEVER(X)       (X)
547 #endif
548
549 /*
550 ** Return true (non-zero) if the input is a integer that is too large
551 ** to fit in 32-bits.  This macro is used inside of various testcase()
552 ** macros to verify that we have tested SQLite for large-file support.
553 */
554 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
555
556 /*
557 ** The macro unlikely() is a hint that surrounds a boolean
558 ** expression that is usually false.  Macro likely() surrounds
559 ** a boolean expression that is usually true.  GCC is able to
560 ** use these hints to generate better code, sometimes.
561 */
562 #if defined(__GNUC__) && 0
563 # define likely(X)    __builtin_expect((X),1)
564 # define unlikely(X)  __builtin_expect((X),0)
565 #else
566 # define likely(X)    !!(X)
567 # define unlikely(X)  !!(X)
568 #endif
569
570 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
571 /************** Begin file sqlite3.h *****************************************/
572 /*
573 ** 2001 September 15
574 **
575 ** The author disclaims copyright to this source code.  In place of
576 ** a legal notice, here is a blessing:
577 **
578 **    May you do good and not evil.
579 **    May you find forgiveness for yourself and forgive others.
580 **    May you share freely, never taking more than you give.
581 **
582 *************************************************************************
583 ** This header file defines the interface that the SQLite library
584 ** presents to client programs.  If a C-function, structure, datatype,
585 ** or constant definition does not appear in this file, then it is
586 ** not a published API of SQLite, is subject to change without
587 ** notice, and should not be referenced by programs that use SQLite.
588 **
589 ** Some of the definitions that are in this file are marked as
590 ** "experimental".  Experimental interfaces are normally new
591 ** features recently added to SQLite.  We do not anticipate changes
592 ** to experimental interfaces but reserve the right to make minor changes
593 ** if experience from use "in the wild" suggest such changes are prudent.
594 **
595 ** The official C-language API documentation for SQLite is derived
596 ** from comments in this file.  This file is the authoritative source
597 ** on how SQLite interfaces are suppose to operate.
598 **
599 ** The name of this file under configuration management is "sqlite.h.in".
600 ** The makefile makes some minor changes to this file (such as inserting
601 ** the version number) and changes its name to "sqlite3.h" as
602 ** part of the build process.
603 */
604 #ifndef _SQLITE3_H_
605 #define _SQLITE3_H_
606 #include <stdarg.h>     /* Needed for the definition of va_list */
607
608 /*
609 ** Make sure we can call this stuff from C++.
610 */
611 #if 0
612 extern "C" {
613 #endif
614
615
616 /*
617 ** Add the ability to override 'extern'
618 */
619 #ifndef SQLITE_EXTERN
620 # define SQLITE_EXTERN extern
621 #endif
622
623 #ifndef SQLITE_API
624 # define SQLITE_API
625 #endif
626
627
628 /*
629 ** These no-op macros are used in front of interfaces to mark those
630 ** interfaces as either deprecated or experimental.  New applications
631 ** should not use deprecated interfaces - they are support for backwards
632 ** compatibility only.  Application writers should be aware that
633 ** experimental interfaces are subject to change in point releases.
634 **
635 ** These macros used to resolve to various kinds of compiler magic that
636 ** would generate warning messages when they were used.  But that
637 ** compiler magic ended up generating such a flurry of bug reports
638 ** that we have taken it all out and gone back to using simple
639 ** noop macros.
640 */
641 #define SQLITE_DEPRECATED
642 #define SQLITE_EXPERIMENTAL
643
644 /*
645 ** Ensure these symbols were not defined by some previous header file.
646 */
647 #ifdef SQLITE_VERSION
648 # undef SQLITE_VERSION
649 #endif
650 #ifdef SQLITE_VERSION_NUMBER
651 # undef SQLITE_VERSION_NUMBER
652 #endif
653
654 /*
655 ** CAPI3REF: Compile-Time Library Version Numbers
656 **
657 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
658 ** evaluates to a string literal that is the SQLite version in the
659 ** format "X.Y.Z" where X is the major version number (always 3 for
660 ** SQLite3) and Y is the minor version number and Z is the release number.)^
661 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
662 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
663 ** numbers used in [SQLITE_VERSION].)^
664 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
665 ** be larger than the release from which it is derived.  Either Y will
666 ** be held constant and Z will be incremented or else Y will be incremented
667 ** and Z will be reset to zero.
668 **
669 ** Since version 3.6.18, SQLite source code has been stored in the
670 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
671 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
672 ** a string which identifies a particular check-in of SQLite
673 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
674 ** string contains the date and time of the check-in (UTC) and an SHA1
675 ** hash of the entire source tree.
676 **
677 ** See also: [sqlite3_libversion()],
678 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
679 ** [sqlite_version()] and [sqlite_source_id()].
680 */
681 #define SQLITE_VERSION        "3.7.16.1"
682 #define SQLITE_VERSION_NUMBER 3007016
683 #define SQLITE_SOURCE_ID      "2013-03-29 13:44:34 527231bc67285f01fb18d4451b28f61da3c4e39d"
684
685 /*
686 ** CAPI3REF: Run-Time Library Version Numbers
687 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
688 **
689 ** These interfaces provide the same information as the [SQLITE_VERSION],
690 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
691 ** but are associated with the library instead of the header file.  ^(Cautious
692 ** programmers might include assert() statements in their application to
693 ** verify that values returned by these interfaces match the macros in
694 ** the header, and thus insure that the application is
695 ** compiled with matching library and header files.
696 **
697 ** <blockquote><pre>
698 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
699 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
700 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
701 ** </pre></blockquote>)^
702 **
703 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
704 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
705 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
706 ** function is provided for use in DLLs since DLL users usually do not have
707 ** direct access to string constants within the DLL.  ^The
708 ** sqlite3_libversion_number() function returns an integer equal to
709 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
710 ** a pointer to a string constant whose value is the same as the 
711 ** [SQLITE_SOURCE_ID] C preprocessor macro.
712 **
713 ** See also: [sqlite_version()] and [sqlite_source_id()].
714 */
715 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
716 SQLITE_API const char *sqlite3_libversion(void);
717 SQLITE_API const char *sqlite3_sourceid(void);
718 SQLITE_API int sqlite3_libversion_number(void);
719
720 /*
721 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
722 **
723 ** ^The sqlite3_compileoption_used() function returns 0 or 1 
724 ** indicating whether the specified option was defined at 
725 ** compile time.  ^The SQLITE_ prefix may be omitted from the 
726 ** option name passed to sqlite3_compileoption_used().  
727 **
728 ** ^The sqlite3_compileoption_get() function allows iterating
729 ** over the list of options that were defined at compile time by
730 ** returning the N-th compile time option string.  ^If N is out of range,
731 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
732 ** prefix is omitted from any strings returned by 
733 ** sqlite3_compileoption_get().
734 **
735 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
736 ** and sqlite3_compileoption_get() may be omitted by specifying the 
737 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
738 **
739 ** See also: SQL functions [sqlite_compileoption_used()] and
740 ** [sqlite_compileoption_get()] and the [compile_options pragma].
741 */
742 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
743 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
744 SQLITE_API const char *sqlite3_compileoption_get(int N);
745 #endif
746
747 /*
748 ** CAPI3REF: Test To See If The Library Is Threadsafe
749 **
750 ** ^The sqlite3_threadsafe() function returns zero if and only if
751 ** SQLite was compiled with mutexing code omitted due to the
752 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
753 **
754 ** SQLite can be compiled with or without mutexes.  When
755 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
756 ** are enabled and SQLite is threadsafe.  When the
757 ** [SQLITE_THREADSAFE] macro is 0, 
758 ** the mutexes are omitted.  Without the mutexes, it is not safe
759 ** to use SQLite concurrently from more than one thread.
760 **
761 ** Enabling mutexes incurs a measurable performance penalty.
762 ** So if speed is of utmost importance, it makes sense to disable
763 ** the mutexes.  But for maximum safety, mutexes should be enabled.
764 ** ^The default behavior is for mutexes to be enabled.
765 **
766 ** This interface can be used by an application to make sure that the
767 ** version of SQLite that it is linking against was compiled with
768 ** the desired setting of the [SQLITE_THREADSAFE] macro.
769 **
770 ** This interface only reports on the compile-time mutex setting
771 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
772 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
773 ** can be fully or partially disabled using a call to [sqlite3_config()]
774 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
775 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
776 ** sqlite3_threadsafe() function shows only the compile-time setting of
777 ** thread safety, not any run-time changes to that setting made by
778 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
779 ** is unchanged by calls to sqlite3_config().)^
780 **
781 ** See the [threading mode] documentation for additional information.
782 */
783 SQLITE_API int sqlite3_threadsafe(void);
784
785 /*
786 ** CAPI3REF: Database Connection Handle
787 ** KEYWORDS: {database connection} {database connections}
788 **
789 ** Each open SQLite database is represented by a pointer to an instance of
790 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
791 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
792 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
793 ** and [sqlite3_close_v2()] are its destructors.  There are many other
794 ** interfaces (such as
795 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
796 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
797 ** sqlite3 object.
798 */
799 typedef struct sqlite3 sqlite3;
800
801 /*
802 ** CAPI3REF: 64-Bit Integer Types
803 ** KEYWORDS: sqlite_int64 sqlite_uint64
804 **
805 ** Because there is no cross-platform way to specify 64-bit integer types
806 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
807 **
808 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
809 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
810 ** compatibility only.
811 **
812 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
813 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
814 ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
815 ** between 0 and +18446744073709551615 inclusive.
816 */
817 #ifdef SQLITE_INT64_TYPE
818   typedef SQLITE_INT64_TYPE sqlite_int64;
819   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
820 #elif defined(_MSC_VER) || defined(__BORLANDC__)
821   typedef __int64 sqlite_int64;
822   typedef unsigned __int64 sqlite_uint64;
823 #else
824   typedef long long int sqlite_int64;
825   typedef unsigned long long int sqlite_uint64;
826 #endif
827 typedef sqlite_int64 sqlite3_int64;
828 typedef sqlite_uint64 sqlite3_uint64;
829
830 /*
831 ** If compiling for a processor that lacks floating point support,
832 ** substitute integer for floating-point.
833 */
834 #ifdef SQLITE_OMIT_FLOATING_POINT
835 # define double sqlite3_int64
836 #endif
837
838 /*
839 ** CAPI3REF: Closing A Database Connection
840 **
841 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
842 ** for the [sqlite3] object.
843 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
844 ** the [sqlite3] object is successfully destroyed and all associated
845 ** resources are deallocated.
846 **
847 ** ^If the database connection is associated with unfinalized prepared
848 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
849 ** will leave the database connection open and return [SQLITE_BUSY].
850 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
851 ** and unfinished sqlite3_backups, then the database connection becomes
852 ** an unusable "zombie" which will automatically be deallocated when the
853 ** last prepared statement is finalized or the last sqlite3_backup is
854 ** finished.  The sqlite3_close_v2() interface is intended for use with
855 ** host languages that are garbage collected, and where the order in which
856 ** destructors are called is arbitrary.
857 **
858 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
859 ** [sqlite3_blob_close | close] all [BLOB handles], and 
860 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
861 ** with the [sqlite3] object prior to attempting to close the object.  ^If
862 ** sqlite3_close_v2() is called on a [database connection] that still has
863 ** outstanding [prepared statements], [BLOB handles], and/or
864 ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
865 ** of resources is deferred until all [prepared statements], [BLOB handles],
866 ** and [sqlite3_backup] objects are also destroyed.
867 **
868 ** ^If an [sqlite3] object is destroyed while a transaction is open,
869 ** the transaction is automatically rolled back.
870 **
871 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
872 ** must be either a NULL
873 ** pointer or an [sqlite3] object pointer obtained
874 ** from [sqlite3_open()], [sqlite3_open16()], or
875 ** [sqlite3_open_v2()], and not previously closed.
876 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
877 ** argument is a harmless no-op.
878 */
879 SQLITE_API int sqlite3_close(sqlite3*);
880 SQLITE_API int sqlite3_close_v2(sqlite3*);
881
882 /*
883 ** The type for a callback function.
884 ** This is legacy and deprecated.  It is included for historical
885 ** compatibility and is not documented.
886 */
887 typedef int (*sqlite3_callback)(void*,int,char**, char**);
888
889 /*
890 ** CAPI3REF: One-Step Query Execution Interface
891 **
892 ** The sqlite3_exec() interface is a convenience wrapper around
893 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
894 ** that allows an application to run multiple statements of SQL
895 ** without having to use a lot of C code. 
896 **
897 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
898 ** semicolon-separate SQL statements passed into its 2nd argument,
899 ** in the context of the [database connection] passed in as its 1st
900 ** argument.  ^If the callback function of the 3rd argument to
901 ** sqlite3_exec() is not NULL, then it is invoked for each result row
902 ** coming out of the evaluated SQL statements.  ^The 4th argument to
903 ** sqlite3_exec() is relayed through to the 1st argument of each
904 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
905 ** is NULL, then no callback is ever invoked and result rows are
906 ** ignored.
907 **
908 ** ^If an error occurs while evaluating the SQL statements passed into
909 ** sqlite3_exec(), then execution of the current statement stops and
910 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
911 ** is not NULL then any error message is written into memory obtained
912 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
913 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
914 ** on error message strings returned through the 5th parameter of
915 ** of sqlite3_exec() after the error message string is no longer needed.
916 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
917 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
918 ** NULL before returning.
919 **
920 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
921 ** routine returns SQLITE_ABORT without invoking the callback again and
922 ** without running any subsequent SQL statements.
923 **
924 ** ^The 2nd argument to the sqlite3_exec() callback function is the
925 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
926 ** callback is an array of pointers to strings obtained as if from
927 ** [sqlite3_column_text()], one for each column.  ^If an element of a
928 ** result row is NULL then the corresponding string pointer for the
929 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
930 ** sqlite3_exec() callback is an array of pointers to strings where each
931 ** entry represents the name of corresponding result column as obtained
932 ** from [sqlite3_column_name()].
933 **
934 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
935 ** to an empty string, or a pointer that contains only whitespace and/or 
936 ** SQL comments, then no SQL statements are evaluated and the database
937 ** is not changed.
938 **
939 ** Restrictions:
940 **
941 ** <ul>
942 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
943 **      is a valid and open [database connection].
944 ** <li> The application must not close [database connection] specified by
945 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
946 ** <li> The application must not modify the SQL statement text passed into
947 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
948 ** </ul>
949 */
950 SQLITE_API int sqlite3_exec(
951   sqlite3*,                                  /* An open database */
952   const char *sql,                           /* SQL to be evaluated */
953   int (*callback)(void*,int,char**,char**),  /* Callback function */
954   void *,                                    /* 1st argument to callback */
955   char **errmsg                              /* Error msg written here */
956 );
957
958 /*
959 ** CAPI3REF: Result Codes
960 ** KEYWORDS: SQLITE_OK {error code} {error codes}
961 ** KEYWORDS: {result code} {result codes}
962 **
963 ** Many SQLite functions return an integer result code from the set shown
964 ** here in order to indicate success or failure.
965 **
966 ** New error codes may be added in future versions of SQLite.
967 **
968 ** See also: [SQLITE_IOERR_READ | extended result codes],
969 ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
970 */
971 #define SQLITE_OK           0   /* Successful result */
972 /* beginning-of-error-codes */
973 #define SQLITE_ERROR        1   /* SQL error or missing database */
974 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
975 #define SQLITE_PERM         3   /* Access permission denied */
976 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
977 #define SQLITE_BUSY         5   /* The database file is locked */
978 #define SQLITE_LOCKED       6   /* A table in the database is locked */
979 #define SQLITE_NOMEM        7   /* A malloc() failed */
980 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
981 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
982 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
983 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
984 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
985 #define SQLITE_FULL        13   /* Insertion failed because database is full */
986 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
987 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
988 #define SQLITE_EMPTY       16   /* Database is empty */
989 #define SQLITE_SCHEMA      17   /* The database schema changed */
990 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
991 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
992 #define SQLITE_MISMATCH    20   /* Data type mismatch */
993 #define SQLITE_MISUSE      21   /* Library used incorrectly */
994 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
995 #define SQLITE_AUTH        23   /* Authorization denied */
996 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
997 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
998 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
999 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
1000 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
1001 /* end-of-error-codes */
1002
1003 /*
1004 ** CAPI3REF: Extended Result Codes
1005 ** KEYWORDS: {extended error code} {extended error codes}
1006 ** KEYWORDS: {extended result code} {extended result codes}
1007 **
1008 ** In its default configuration, SQLite API routines return one of 26 integer
1009 ** [SQLITE_OK | result codes].  However, experience has shown that many of
1010 ** these result codes are too coarse-grained.  They do not provide as
1011 ** much information about problems as programmers might like.  In an effort to
1012 ** address this, newer versions of SQLite (version 3.3.8 and later) include
1013 ** support for additional result codes that provide more detailed information
1014 ** about errors. The extended result codes are enabled or disabled
1015 ** on a per database connection basis using the
1016 ** [sqlite3_extended_result_codes()] API.
1017 **
1018 ** Some of the available extended result codes are listed here.
1019 ** One may expect the number of extended result codes will be expand
1020 ** over time.  Software that uses extended result codes should expect
1021 ** to see new result codes in future releases of SQLite.
1022 **
1023 ** The SQLITE_OK result code will never be extended.  It will always
1024 ** be exactly zero.
1025 */
1026 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
1027 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
1028 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
1029 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
1030 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
1031 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
1032 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
1033 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
1034 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
1035 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
1036 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
1037 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
1038 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
1039 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1040 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
1041 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
1042 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
1043 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
1044 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
1045 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
1046 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
1047 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
1048 #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
1049 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
1050 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1051 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1052 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
1053 #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
1054 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
1055 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
1056 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
1057 #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
1058 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
1059 #define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
1060 #define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
1061 #define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
1062 #define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
1063 #define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
1064 #define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
1065 #define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
1066 #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
1067 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
1068
1069 /*
1070 ** CAPI3REF: Flags For File Open Operations
1071 **
1072 ** These bit values are intended for use in the
1073 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1074 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1075 */
1076 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1077 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1078 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1079 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1080 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1081 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1082 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
1083 #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
1084 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1085 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1086 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1087 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1088 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1089 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1090 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1091 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1092 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1093 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1094 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1095 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1096
1097 /* Reserved:                         0x00F00000 */
1098
1099 /*
1100 ** CAPI3REF: Device Characteristics
1101 **
1102 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1103 ** object returns an integer which is a vector of these
1104 ** bit values expressing I/O characteristics of the mass storage
1105 ** device that holds the file that the [sqlite3_io_methods]
1106 ** refers to.
1107 **
1108 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1109 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1110 ** mean that writes of blocks that are nnn bytes in size and
1111 ** are aligned to an address which is an integer multiple of
1112 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1113 ** that when data is appended to a file, the data is appended
1114 ** first then the size of the file is extended, never the other
1115 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1116 ** information is written to disk in the same order as calls
1117 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
1118 ** after reboot following a crash or power loss, the only bytes in a
1119 ** file that were written at the application level might have changed
1120 ** and that adjacent bytes, even bytes within the same sector are
1121 ** guaranteed to be unchanged.
1122 */
1123 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1124 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1125 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1126 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1127 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1128 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1129 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1130 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1131 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1132 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1133 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1134 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1135 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
1136
1137 /*
1138 ** CAPI3REF: File Locking Levels
1139 **
1140 ** SQLite uses one of these integer values as the second
1141 ** argument to calls it makes to the xLock() and xUnlock() methods
1142 ** of an [sqlite3_io_methods] object.
1143 */
1144 #define SQLITE_LOCK_NONE          0
1145 #define SQLITE_LOCK_SHARED        1
1146 #define SQLITE_LOCK_RESERVED      2
1147 #define SQLITE_LOCK_PENDING       3
1148 #define SQLITE_LOCK_EXCLUSIVE     4
1149
1150 /*
1151 ** CAPI3REF: Synchronization Type Flags
1152 **
1153 ** When SQLite invokes the xSync() method of an
1154 ** [sqlite3_io_methods] object it uses a combination of
1155 ** these integer values as the second argument.
1156 **
1157 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1158 ** sync operation only needs to flush data to mass storage.  Inode
1159 ** information need not be flushed. If the lower four bits of the flag
1160 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1161 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1162 ** to use Mac OS X style fullsync instead of fsync().
1163 **
1164 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1165 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1166 ** settings.  The [synchronous pragma] determines when calls to the
1167 ** xSync VFS method occur and applies uniformly across all platforms.
1168 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1169 ** energetic or rigorous or forceful the sync operations are and
1170 ** only make a difference on Mac OSX for the default SQLite code.
1171 ** (Third-party VFS implementations might also make the distinction
1172 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1173 ** operating systems natively supported by SQLite, only Mac OSX
1174 ** cares about the difference.)
1175 */
1176 #define SQLITE_SYNC_NORMAL        0x00002
1177 #define SQLITE_SYNC_FULL          0x00003
1178 #define SQLITE_SYNC_DATAONLY      0x00010
1179
1180 /*
1181 ** CAPI3REF: OS Interface Open File Handle
1182 **
1183 ** An [sqlite3_file] object represents an open file in the 
1184 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1185 ** implementations will
1186 ** want to subclass this object by appending additional fields
1187 ** for their own use.  The pMethods entry is a pointer to an
1188 ** [sqlite3_io_methods] object that defines methods for performing
1189 ** I/O operations on the open file.
1190 */
1191 typedef struct sqlite3_file sqlite3_file;
1192 struct sqlite3_file {
1193   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1194 };
1195
1196 /*
1197 ** CAPI3REF: OS Interface File Virtual Methods Object
1198 **
1199 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1200 ** [sqlite3_file] object (or, more commonly, a subclass of the
1201 ** [sqlite3_file] object) with a pointer to an instance of this object.
1202 ** This object defines the methods used to perform various operations
1203 ** against the open file represented by the [sqlite3_file] object.
1204 **
1205 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
1206 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1207 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1208 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1209 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1210 ** to NULL.
1211 **
1212 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1213 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1214 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1215 ** flag may be ORed in to indicate that only the data of the file
1216 ** and not its inode needs to be synced.
1217 **
1218 ** The integer values to xLock() and xUnlock() are one of
1219 ** <ul>
1220 ** <li> [SQLITE_LOCK_NONE],
1221 ** <li> [SQLITE_LOCK_SHARED],
1222 ** <li> [SQLITE_LOCK_RESERVED],
1223 ** <li> [SQLITE_LOCK_PENDING], or
1224 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1225 ** </ul>
1226 ** xLock() increases the lock. xUnlock() decreases the lock.
1227 ** The xCheckReservedLock() method checks whether any database connection,
1228 ** either in this process or in some other process, is holding a RESERVED,
1229 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1230 ** if such a lock exists and false otherwise.
1231 **
1232 ** The xFileControl() method is a generic interface that allows custom
1233 ** VFS implementations to directly control an open file using the
1234 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1235 ** integer opcode.  The third argument is a generic pointer intended to
1236 ** point to a structure that may contain arguments or space in which to
1237 ** write return values.  Potential uses for xFileControl() might be
1238 ** functions to enable blocking locks with timeouts, to change the
1239 ** locking strategy (for example to use dot-file locks), to inquire
1240 ** about the status of a lock, or to break stale locks.  The SQLite
1241 ** core reserves all opcodes less than 100 for its own use.
1242 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1243 ** Applications that define a custom xFileControl method should use opcodes
1244 ** greater than 100 to avoid conflicts.  VFS implementations should
1245 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1246 ** recognize.
1247 **
1248 ** The xSectorSize() method returns the sector size of the
1249 ** device that underlies the file.  The sector size is the
1250 ** minimum write that can be performed without disturbing
1251 ** other bytes in the file.  The xDeviceCharacteristics()
1252 ** method returns a bit vector describing behaviors of the
1253 ** underlying device:
1254 **
1255 ** <ul>
1256 ** <li> [SQLITE_IOCAP_ATOMIC]
1257 ** <li> [SQLITE_IOCAP_ATOMIC512]
1258 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1259 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1260 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1261 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1262 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1263 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1264 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1265 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1266 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1267 ** </ul>
1268 **
1269 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1270 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1271 ** mean that writes of blocks that are nnn bytes in size and
1272 ** are aligned to an address which is an integer multiple of
1273 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1274 ** that when data is appended to a file, the data is appended
1275 ** first then the size of the file is extended, never the other
1276 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1277 ** information is written to disk in the same order as calls
1278 ** to xWrite().
1279 **
1280 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1281 ** in the unread portions of the buffer with zeros.  A VFS that
1282 ** fails to zero-fill short reads might seem to work.  However,
1283 ** failure to zero-fill short reads will eventually lead to
1284 ** database corruption.
1285 */
1286 typedef struct sqlite3_io_methods sqlite3_io_methods;
1287 struct sqlite3_io_methods {
1288   int iVersion;
1289   int (*xClose)(sqlite3_file*);
1290   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1291   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1292   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1293   int (*xSync)(sqlite3_file*, int flags);
1294   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1295   int (*xLock)(sqlite3_file*, int);
1296   int (*xUnlock)(sqlite3_file*, int);
1297   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1298   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1299   int (*xSectorSize)(sqlite3_file*);
1300   int (*xDeviceCharacteristics)(sqlite3_file*);
1301   /* Methods above are valid for version 1 */
1302   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1303   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1304   void (*xShmBarrier)(sqlite3_file*);
1305   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1306   /* Methods above are valid for version 2 */
1307   /* Additional methods may be added in future releases */
1308 };
1309
1310 /*
1311 ** CAPI3REF: Standard File Control Opcodes
1312 **
1313 ** These integer constants are opcodes for the xFileControl method
1314 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1315 ** interface.
1316 **
1317 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1318 ** opcode causes the xFileControl method to write the current state of
1319 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1320 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1321 ** into an integer that the pArg argument points to. This capability
1322 ** is used during testing and only needs to be supported when SQLITE_TEST
1323 ** is defined.
1324 ** <ul>
1325 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1326 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1327 ** layer a hint of how large the database file will grow to be during the
1328 ** current transaction.  This hint is not guaranteed to be accurate but it
1329 ** is often close.  The underlying VFS might choose to preallocate database
1330 ** file space based on this hint in order to help writes to the database
1331 ** file run faster.
1332 **
1333 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1334 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1335 ** extends and truncates the database file in chunks of a size specified
1336 ** by the user. The fourth argument to [sqlite3_file_control()] should 
1337 ** point to an integer (type int) containing the new chunk-size to use
1338 ** for the nominated database. Allocating database file space in large
1339 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1340 ** improve performance on some systems.
1341 **
1342 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1343 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1344 ** to the [sqlite3_file] object associated with a particular database
1345 ** connection.  See the [sqlite3_file_control()] documentation for
1346 ** additional information.
1347 **
1348 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1349 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1350 ** SQLite and sent to all VFSes in place of a call to the xSync method
1351 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1352 ** Some specialized VFSes need this signal in order to operate correctly
1353 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most 
1354 ** VFSes do not need this signal and should silently ignore this opcode.
1355 ** Applications should not call [sqlite3_file_control()] with this
1356 ** opcode as doing so may disrupt the operation of the specialized VFSes
1357 ** that do require it.  
1358 **
1359 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1360 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1361 ** retry counts and intervals for certain disk I/O operations for the
1362 ** windows [VFS] in order to provide robustness in the presence of
1363 ** anti-virus programs.  By default, the windows VFS will retry file read,
1364 ** file write, and file delete operations up to 10 times, with a delay
1365 ** of 25 milliseconds before the first retry and with the delay increasing
1366 ** by an additional 25 milliseconds with each subsequent retry.  This
1367 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1368 ** to be adjusted.  The values are changed for all database connections
1369 ** within the same process.  The argument is a pointer to an array of two
1370 ** integers where the first integer i the new retry count and the second
1371 ** integer is the delay.  If either integer is negative, then the setting
1372 ** is not changed but instead the prior value of that setting is written
1373 ** into the array entry, allowing the current retry settings to be
1374 ** interrogated.  The zDbName parameter is ignored.
1375 **
1376 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1377 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1378 ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1379 ** write ahead log and shared memory files used for transaction control
1380 ** are automatically deleted when the latest connection to the database
1381 ** closes.  Setting persistent WAL mode causes those files to persist after
1382 ** close.  Persisting the files is useful when other processes that do not
1383 ** have write permission on the directory containing the database file want
1384 ** to read the database file, as the WAL and shared memory files must exist
1385 ** in order for the database to be readable.  The fourth parameter to
1386 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1387 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1388 ** WAL mode.  If the integer is -1, then it is overwritten with the current
1389 ** WAL persistence setting.
1390 **
1391 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1392 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1393 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1394 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1395 ** xDeviceCharacteristics methods. The fourth parameter to
1396 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1397 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1398 ** mode.  If the integer is -1, then it is overwritten with the current
1399 ** zero-damage mode setting.
1400 **
1401 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1402 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1403 ** a write transaction to indicate that, unless it is rolled back for some
1404 ** reason, the entire database file will be overwritten by the current 
1405 ** transaction. This is used by VACUUM operations.
1406 **
1407 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1408 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1409 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1410 ** final bottom-level VFS are written into memory obtained from 
1411 ** [sqlite3_malloc()] and the result is stored in the char* variable
1412 ** that the fourth parameter of [sqlite3_file_control()] points to.
1413 ** The caller is responsible for freeing the memory when done.  As with
1414 ** all file-control actions, there is no guarantee that this will actually
1415 ** do anything.  Callers should initialize the char* variable to a NULL
1416 ** pointer in case this file-control is not implemented.  This file-control
1417 ** is intended for diagnostic use only.
1418 **
1419 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1420 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
1421 ** file control is sent to the open [sqlite3_file] object corresponding
1422 ** to the database file to which the pragma statement refers. ^The argument
1423 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1424 ** pointers to strings (char**) in which the second element of the array
1425 ** is the name of the pragma and the third element is the argument to the
1426 ** pragma or NULL if the pragma has no argument.  ^The handler for an
1427 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1428 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1429 ** or the equivalent and that string will become the result of the pragma or
1430 ** the error message if the pragma fails. ^If the
1431 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
1432 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1433 ** file control returns [SQLITE_OK], then the parser assumes that the
1434 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1435 ** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1436 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1437 ** that the VFS encountered an error while handling the [PRAGMA] and the
1438 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1439 ** file control occurs at the beginning of pragma statement analysis and so
1440 ** it is able to override built-in [PRAGMA] statements.
1441 **
1442 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1443 ** ^This file-control may be invoked by SQLite on the database file handle
1444 ** shortly after it is opened in order to provide a custom VFS with access
1445 ** to the connections busy-handler callback. The argument is of type (void **)
1446 ** - an array of two (void *) values. The first (void *) actually points
1447 ** to a function of type (int (*)(void *)). In order to invoke the connections
1448 ** busy-handler, this function should be invoked with the second (void *) in
1449 ** the array as the only argument. If it returns non-zero, then the operation
1450 ** should be retried. If it returns zero, the custom VFS should abandon the
1451 ** current operation.
1452 **
1453 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1454 ** ^Application can invoke this file-control to have SQLite generate a
1455 ** temporary filename using the same algorithm that is followed to generate
1456 ** temporary filenames for TEMP tables and other internal uses.  The
1457 ** argument should be a char** which will be filled with the filename
1458 ** written into memory obtained from [sqlite3_malloc()].  The caller should
1459 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1460 **
1461 ** </ul>
1462 */
1463 #define SQLITE_FCNTL_LOCKSTATE               1
1464 #define SQLITE_GET_LOCKPROXYFILE             2
1465 #define SQLITE_SET_LOCKPROXYFILE             3
1466 #define SQLITE_LAST_ERRNO                    4
1467 #define SQLITE_FCNTL_SIZE_HINT               5
1468 #define SQLITE_FCNTL_CHUNK_SIZE              6
1469 #define SQLITE_FCNTL_FILE_POINTER            7
1470 #define SQLITE_FCNTL_SYNC_OMITTED            8
1471 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
1472 #define SQLITE_FCNTL_PERSIST_WAL            10
1473 #define SQLITE_FCNTL_OVERWRITE              11
1474 #define SQLITE_FCNTL_VFSNAME                12
1475 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1476 #define SQLITE_FCNTL_PRAGMA                 14
1477 #define SQLITE_FCNTL_BUSYHANDLER            15
1478 #define SQLITE_FCNTL_TEMPFILENAME           16
1479
1480 /*
1481 ** CAPI3REF: Mutex Handle
1482 **
1483 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1484 ** abstract type for a mutex object.  The SQLite core never looks
1485 ** at the internal representation of an [sqlite3_mutex].  It only
1486 ** deals with pointers to the [sqlite3_mutex] object.
1487 **
1488 ** Mutexes are created using [sqlite3_mutex_alloc()].
1489 */
1490 typedef struct sqlite3_mutex sqlite3_mutex;
1491
1492 /*
1493 ** CAPI3REF: OS Interface Object
1494 **
1495 ** An instance of the sqlite3_vfs object defines the interface between
1496 ** the SQLite core and the underlying operating system.  The "vfs"
1497 ** in the name of the object stands for "virtual file system".  See
1498 ** the [VFS | VFS documentation] for further information.
1499 **
1500 ** The value of the iVersion field is initially 1 but may be larger in
1501 ** future versions of SQLite.  Additional fields may be appended to this
1502 ** object when the iVersion value is increased.  Note that the structure
1503 ** of the sqlite3_vfs object changes in the transaction between
1504 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1505 ** modified.
1506 **
1507 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1508 ** structure used by this VFS.  mxPathname is the maximum length of
1509 ** a pathname in this VFS.
1510 **
1511 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1512 ** the pNext pointer.  The [sqlite3_vfs_register()]
1513 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1514 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1515 ** searches the list.  Neither the application code nor the VFS
1516 ** implementation should use the pNext pointer.
1517 **
1518 ** The pNext field is the only field in the sqlite3_vfs
1519 ** structure that SQLite will ever modify.  SQLite will only access
1520 ** or modify this field while holding a particular static mutex.
1521 ** The application should never modify anything within the sqlite3_vfs
1522 ** object once the object has been registered.
1523 **
1524 ** The zName field holds the name of the VFS module.  The name must
1525 ** be unique across all VFS modules.
1526 **
1527 ** [[sqlite3_vfs.xOpen]]
1528 ** ^SQLite guarantees that the zFilename parameter to xOpen
1529 ** is either a NULL pointer or string obtained
1530 ** from xFullPathname() with an optional suffix added.
1531 ** ^If a suffix is added to the zFilename parameter, it will
1532 ** consist of a single "-" character followed by no more than
1533 ** 11 alphanumeric and/or "-" characters.
1534 ** ^SQLite further guarantees that
1535 ** the string will be valid and unchanged until xClose() is
1536 ** called. Because of the previous sentence,
1537 ** the [sqlite3_file] can safely store a pointer to the
1538 ** filename if it needs to remember the filename for some reason.
1539 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1540 ** must invent its own temporary name for the file.  ^Whenever the 
1541 ** xFilename parameter is NULL it will also be the case that the
1542 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1543 **
1544 ** The flags argument to xOpen() includes all bits set in
1545 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1546 ** or [sqlite3_open16()] is used, then flags includes at least
1547 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1548 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1549 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1550 **
1551 ** ^(SQLite will also add one of the following flags to the xOpen()
1552 ** call, depending on the object being opened:
1553 **
1554 ** <ul>
1555 ** <li>  [SQLITE_OPEN_MAIN_DB]
1556 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1557 ** <li>  [SQLITE_OPEN_TEMP_DB]
1558 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1559 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1560 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1561 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1562 ** <li>  [SQLITE_OPEN_WAL]
1563 ** </ul>)^
1564 **
1565 ** The file I/O implementation can use the object type flags to
1566 ** change the way it deals with files.  For example, an application
1567 ** that does not care about crash recovery or rollback might make
1568 ** the open of a journal file a no-op.  Writes to this journal would
1569 ** also be no-ops, and any attempt to read the journal would return
1570 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1571 ** file will be doing page-aligned sector reads and writes in a random
1572 ** order and set up its I/O subsystem accordingly.
1573 **
1574 ** SQLite might also add one of the following flags to the xOpen method:
1575 **
1576 ** <ul>
1577 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1578 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1579 ** </ul>
1580 **
1581 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1582 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1583 ** will be set for TEMP databases and their journals, transient
1584 ** databases, and subjournals.
1585 **
1586 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1587 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1588 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1589 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1590 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1591 ** be created, and that it is an error if it already exists.
1592 ** It is <i>not</i> used to indicate the file should be opened 
1593 ** for exclusive access.
1594 **
1595 ** ^At least szOsFile bytes of memory are allocated by SQLite
1596 ** to hold the  [sqlite3_file] structure passed as the third
1597 ** argument to xOpen.  The xOpen method does not have to
1598 ** allocate the structure; it should just fill it in.  Note that
1599 ** the xOpen method must set the sqlite3_file.pMethods to either
1600 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1601 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1602 ** element will be valid after xOpen returns regardless of the success
1603 ** or failure of the xOpen call.
1604 **
1605 ** [[sqlite3_vfs.xAccess]]
1606 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1607 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1608 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1609 ** to test whether a file is at least readable.   The file can be a
1610 ** directory.
1611 **
1612 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1613 ** output buffer xFullPathname.  The exact size of the output buffer
1614 ** is also passed as a parameter to both  methods. If the output buffer
1615 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1616 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1617 ** to prevent this by setting mxPathname to a sufficiently large value.
1618 **
1619 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1620 ** interfaces are not strictly a part of the filesystem, but they are
1621 ** included in the VFS structure for completeness.
1622 ** The xRandomness() function attempts to return nBytes bytes
1623 ** of good-quality randomness into zOut.  The return value is
1624 ** the actual number of bytes of randomness obtained.
1625 ** The xSleep() method causes the calling thread to sleep for at
1626 ** least the number of microseconds given.  ^The xCurrentTime()
1627 ** method returns a Julian Day Number for the current date and time as
1628 ** a floating point value.
1629 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1630 ** Day Number multiplied by 86400000 (the number of milliseconds in 
1631 ** a 24-hour day).  
1632 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1633 ** date and time if that method is available (if iVersion is 2 or 
1634 ** greater and the function pointer is not NULL) and will fall back
1635 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1636 **
1637 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1638 ** are not used by the SQLite core.  These optional interfaces are provided
1639 ** by some VFSes to facilitate testing of the VFS code. By overriding 
1640 ** system calls with functions under its control, a test program can
1641 ** simulate faults and error conditions that would otherwise be difficult
1642 ** or impossible to induce.  The set of system calls that can be overridden
1643 ** varies from one VFS to another, and from one version of the same VFS to the
1644 ** next.  Applications that use these interfaces must be prepared for any
1645 ** or all of these interfaces to be NULL or for their behavior to change
1646 ** from one release to the next.  Applications must not attempt to access
1647 ** any of these methods if the iVersion of the VFS is less than 3.
1648 */
1649 typedef struct sqlite3_vfs sqlite3_vfs;
1650 typedef void (*sqlite3_syscall_ptr)(void);
1651 struct sqlite3_vfs {
1652   int iVersion;            /* Structure version number (currently 3) */
1653   int szOsFile;            /* Size of subclassed sqlite3_file */
1654   int mxPathname;          /* Maximum file pathname length */
1655   sqlite3_vfs *pNext;      /* Next registered VFS */
1656   const char *zName;       /* Name of this virtual file system */
1657   void *pAppData;          /* Pointer to application-specific data */
1658   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1659                int flags, int *pOutFlags);
1660   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1661   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1662   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1663   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1664   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1665   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1666   void (*xDlClose)(sqlite3_vfs*, void*);
1667   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1668   int (*xSleep)(sqlite3_vfs*, int microseconds);
1669   int (*xCurrentTime)(sqlite3_vfs*, double*);
1670   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1671   /*
1672   ** The methods above are in version 1 of the sqlite_vfs object
1673   ** definition.  Those that follow are added in version 2 or later
1674   */
1675   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1676   /*
1677   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1678   ** Those below are for version 3 and greater.
1679   */
1680   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1681   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1682   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1683   /*
1684   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1685   ** New fields may be appended in figure versions.  The iVersion
1686   ** value will increment whenever this happens. 
1687   */
1688 };
1689
1690 /*
1691 ** CAPI3REF: Flags for the xAccess VFS method
1692 **
1693 ** These integer constants can be used as the third parameter to
1694 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1695 ** what kind of permissions the xAccess method is looking for.
1696 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1697 ** simply checks whether the file exists.
1698 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1699 ** checks whether the named directory is both readable and writable
1700 ** (in other words, if files can be added, removed, and renamed within
1701 ** the directory).
1702 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1703 ** [temp_store_directory pragma], though this could change in a future
1704 ** release of SQLite.
1705 ** With SQLITE_ACCESS_READ, the xAccess method
1706 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1707 ** currently unused, though it might be used in a future release of
1708 ** SQLite.
1709 */
1710 #define SQLITE_ACCESS_EXISTS    0
1711 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1712 #define SQLITE_ACCESS_READ      2   /* Unused */
1713
1714 /*
1715 ** CAPI3REF: Flags for the xShmLock VFS method
1716 **
1717 ** These integer constants define the various locking operations
1718 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1719 ** following are the only legal combinations of flags to the
1720 ** xShmLock method:
1721 **
1722 ** <ul>
1723 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1724 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1725 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1726 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1727 ** </ul>
1728 **
1729 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1730 ** was given no the corresponding lock.  
1731 **
1732 ** The xShmLock method can transition between unlocked and SHARED or
1733 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1734 ** and EXCLUSIVE.
1735 */
1736 #define SQLITE_SHM_UNLOCK       1
1737 #define SQLITE_SHM_LOCK         2
1738 #define SQLITE_SHM_SHARED       4
1739 #define SQLITE_SHM_EXCLUSIVE    8
1740
1741 /*
1742 ** CAPI3REF: Maximum xShmLock index
1743 **
1744 ** The xShmLock method on [sqlite3_io_methods] may use values
1745 ** between 0 and this upper bound as its "offset" argument.
1746 ** The SQLite core will never attempt to acquire or release a
1747 ** lock outside of this range
1748 */
1749 #define SQLITE_SHM_NLOCK        8
1750
1751
1752 /*
1753 ** CAPI3REF: Initialize The SQLite Library
1754 **
1755 ** ^The sqlite3_initialize() routine initializes the
1756 ** SQLite library.  ^The sqlite3_shutdown() routine
1757 ** deallocates any resources that were allocated by sqlite3_initialize().
1758 ** These routines are designed to aid in process initialization and
1759 ** shutdown on embedded systems.  Workstation applications using
1760 ** SQLite normally do not need to invoke either of these routines.
1761 **
1762 ** A call to sqlite3_initialize() is an "effective" call if it is
1763 ** the first time sqlite3_initialize() is invoked during the lifetime of
1764 ** the process, or if it is the first time sqlite3_initialize() is invoked
1765 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1766 ** of sqlite3_initialize() does any initialization.  All other calls
1767 ** are harmless no-ops.)^
1768 **
1769 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1770 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1771 ** an effective call to sqlite3_shutdown() does any deinitialization.
1772 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1773 **
1774 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1775 ** is not.  The sqlite3_shutdown() interface must only be called from a
1776 ** single thread.  All open [database connections] must be closed and all
1777 ** other SQLite resources must be deallocated prior to invoking
1778 ** sqlite3_shutdown().
1779 **
1780 ** Among other things, ^sqlite3_initialize() will invoke
1781 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1782 ** will invoke sqlite3_os_end().
1783 **
1784 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1785 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1786 ** the library (perhaps it is unable to allocate a needed resource such
1787 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1788 **
1789 ** ^The sqlite3_initialize() routine is called internally by many other
1790 ** SQLite interfaces so that an application usually does not need to
1791 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1792 ** calls sqlite3_initialize() so the SQLite library will be automatically
1793 ** initialized when [sqlite3_open()] is called if it has not be initialized
1794 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1795 ** compile-time option, then the automatic calls to sqlite3_initialize()
1796 ** are omitted and the application must call sqlite3_initialize() directly
1797 ** prior to using any other SQLite interface.  For maximum portability,
1798 ** it is recommended that applications always invoke sqlite3_initialize()
1799 ** directly prior to using any other SQLite interface.  Future releases
1800 ** of SQLite may require this.  In other words, the behavior exhibited
1801 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1802 ** default behavior in some future release of SQLite.
1803 **
1804 ** The sqlite3_os_init() routine does operating-system specific
1805 ** initialization of the SQLite library.  The sqlite3_os_end()
1806 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1807 ** performed by these routines include allocation or deallocation
1808 ** of static resources, initialization of global variables,
1809 ** setting up a default [sqlite3_vfs] module, or setting up
1810 ** a default configuration using [sqlite3_config()].
1811 **
1812 ** The application should never invoke either sqlite3_os_init()
1813 ** or sqlite3_os_end() directly.  The application should only invoke
1814 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1815 ** interface is called automatically by sqlite3_initialize() and
1816 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1817 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1818 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1819 ** When [custom builds | built for other platforms]
1820 ** (using the [SQLITE_OS_OTHER=1] compile-time
1821 ** option) the application must supply a suitable implementation for
1822 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1823 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1824 ** must return [SQLITE_OK] on success and some other [error code] upon
1825 ** failure.
1826 */
1827 SQLITE_API int sqlite3_initialize(void);
1828 SQLITE_API int sqlite3_shutdown(void);
1829 SQLITE_API int sqlite3_os_init(void);
1830 SQLITE_API int sqlite3_os_end(void);
1831
1832 /*
1833 ** CAPI3REF: Configuring The SQLite Library
1834 **
1835 ** The sqlite3_config() interface is used to make global configuration
1836 ** changes to SQLite in order to tune SQLite to the specific needs of
1837 ** the application.  The default configuration is recommended for most
1838 ** applications and so this routine is usually not necessary.  It is
1839 ** provided to support rare applications with unusual needs.
1840 **
1841 ** The sqlite3_config() interface is not threadsafe.  The application
1842 ** must insure that no other SQLite interfaces are invoked by other
1843 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1844 ** may only be invoked prior to library initialization using
1845 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1846 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1847 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1848 ** Note, however, that ^sqlite3_config() can be called as part of the
1849 ** implementation of an application-defined [sqlite3_os_init()].
1850 **
1851 ** The first argument to sqlite3_config() is an integer
1852 ** [configuration option] that determines
1853 ** what property of SQLite is to be configured.  Subsequent arguments
1854 ** vary depending on the [configuration option]
1855 ** in the first argument.
1856 **
1857 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1858 ** ^If the option is unknown or SQLite is unable to set the option
1859 ** then this routine returns a non-zero [error code].
1860 */
1861 SQLITE_API int sqlite3_config(int, ...);
1862
1863 /*
1864 ** CAPI3REF: Configure database connections
1865 **
1866 ** The sqlite3_db_config() interface is used to make configuration
1867 ** changes to a [database connection].  The interface is similar to
1868 ** [sqlite3_config()] except that the changes apply to a single
1869 ** [database connection] (specified in the first argument).
1870 **
1871 ** The second argument to sqlite3_db_config(D,V,...)  is the
1872 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
1873 ** that indicates what aspect of the [database connection] is being configured.
1874 ** Subsequent arguments vary depending on the configuration verb.
1875 **
1876 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1877 ** the call is considered successful.
1878 */
1879 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1880
1881 /*
1882 ** CAPI3REF: Memory Allocation Routines
1883 **
1884 ** An instance of this object defines the interface between SQLite
1885 ** and low-level memory allocation routines.
1886 **
1887 ** This object is used in only one place in the SQLite interface.
1888 ** A pointer to an instance of this object is the argument to
1889 ** [sqlite3_config()] when the configuration option is
1890 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1891 ** By creating an instance of this object
1892 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1893 ** during configuration, an application can specify an alternative
1894 ** memory allocation subsystem for SQLite to use for all of its
1895 ** dynamic memory needs.
1896 **
1897 ** Note that SQLite comes with several [built-in memory allocators]
1898 ** that are perfectly adequate for the overwhelming majority of applications
1899 ** and that this object is only useful to a tiny minority of applications
1900 ** with specialized memory allocation requirements.  This object is
1901 ** also used during testing of SQLite in order to specify an alternative
1902 ** memory allocator that simulates memory out-of-memory conditions in
1903 ** order to verify that SQLite recovers gracefully from such
1904 ** conditions.
1905 **
1906 ** The xMalloc, xRealloc, and xFree methods must work like the
1907 ** malloc(), realloc() and free() functions from the standard C library.
1908 ** ^SQLite guarantees that the second argument to
1909 ** xRealloc is always a value returned by a prior call to xRoundup.
1910 **
1911 ** xSize should return the allocated size of a memory allocation
1912 ** previously obtained from xMalloc or xRealloc.  The allocated size
1913 ** is always at least as big as the requested size but may be larger.
1914 **
1915 ** The xRoundup method returns what would be the allocated size of
1916 ** a memory allocation given a particular requested size.  Most memory
1917 ** allocators round up memory allocations at least to the next multiple
1918 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1919 ** Every memory allocation request coming in through [sqlite3_malloc()]
1920 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1921 ** that causes the corresponding memory allocation to fail.
1922 **
1923 ** The xInit method initializes the memory allocator.  (For example,
1924 ** it might allocate any require mutexes or initialize internal data
1925 ** structures.  The xShutdown method is invoked (indirectly) by
1926 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1927 ** by xInit.  The pAppData pointer is used as the only parameter to
1928 ** xInit and xShutdown.
1929 **
1930 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1931 ** the xInit method, so the xInit method need not be threadsafe.  The
1932 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1933 ** not need to be threadsafe either.  For all other methods, SQLite
1934 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1935 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1936 ** it is by default) and so the methods are automatically serialized.
1937 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1938 ** methods must be threadsafe or else make their own arrangements for
1939 ** serialization.
1940 **
1941 ** SQLite will never invoke xInit() more than once without an intervening
1942 ** call to xShutdown().
1943 */
1944 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1945 struct sqlite3_mem_methods {
1946   void *(*xMalloc)(int);         /* Memory allocation function */
1947   void (*xFree)(void*);          /* Free a prior allocation */
1948   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1949   int (*xSize)(void*);           /* Return the size of an allocation */
1950   int (*xRoundup)(int);          /* Round up request size to allocation size */
1951   int (*xInit)(void*);           /* Initialize the memory allocator */
1952   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1953   void *pAppData;                /* Argument to xInit() and xShutdown() */
1954 };
1955
1956 /*
1957 ** CAPI3REF: Configuration Options
1958 ** KEYWORDS: {configuration option}
1959 **
1960 ** These constants are the available integer configuration options that
1961 ** can be passed as the first argument to the [sqlite3_config()] interface.
1962 **
1963 ** New configuration options may be added in future releases of SQLite.
1964 ** Existing configuration options might be discontinued.  Applications
1965 ** should check the return code from [sqlite3_config()] to make sure that
1966 ** the call worked.  The [sqlite3_config()] interface will return a
1967 ** non-zero [error code] if a discontinued or unsupported configuration option
1968 ** is invoked.
1969 **
1970 ** <dl>
1971 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1972 ** <dd>There are no arguments to this option.  ^This option sets the
1973 ** [threading mode] to Single-thread.  In other words, it disables
1974 ** all mutexing and puts SQLite into a mode where it can only be used
1975 ** by a single thread.   ^If SQLite is compiled with
1976 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1977 ** it is not possible to change the [threading mode] from its default
1978 ** value of Single-thread and so [sqlite3_config()] will return 
1979 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1980 ** configuration option.</dd>
1981 **
1982 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1983 ** <dd>There are no arguments to this option.  ^This option sets the
1984 ** [threading mode] to Multi-thread.  In other words, it disables
1985 ** mutexing on [database connection] and [prepared statement] objects.
1986 ** The application is responsible for serializing access to
1987 ** [database connections] and [prepared statements].  But other mutexes
1988 ** are enabled so that SQLite will be safe to use in a multi-threaded
1989 ** environment as long as no two threads attempt to use the same
1990 ** [database connection] at the same time.  ^If SQLite is compiled with
1991 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1992 ** it is not possible to set the Multi-thread [threading mode] and
1993 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1994 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1995 **
1996 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1997 ** <dd>There are no arguments to this option.  ^This option sets the
1998 ** [threading mode] to Serialized. In other words, this option enables
1999 ** all mutexes including the recursive
2000 ** mutexes on [database connection] and [prepared statement] objects.
2001 ** In this mode (which is the default when SQLite is compiled with
2002 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
2003 ** to [database connections] and [prepared statements] so that the
2004 ** application is free to use the same [database connection] or the
2005 ** same [prepared statement] in different threads at the same time.
2006 ** ^If SQLite is compiled with
2007 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2008 ** it is not possible to set the Serialized [threading mode] and
2009 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2010 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
2011 **
2012 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
2013 ** <dd> ^(This option takes a single argument which is a pointer to an
2014 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
2015 ** alternative low-level memory allocation routines to be used in place of
2016 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
2017 ** its own private copy of the content of the [sqlite3_mem_methods] structure
2018 ** before the [sqlite3_config()] call returns.</dd>
2019 **
2020 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
2021 ** <dd> ^(This option takes a single argument which is a pointer to an
2022 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
2023 ** structure is filled with the currently defined memory allocation routines.)^
2024 ** This option can be used to overload the default memory allocation
2025 ** routines with a wrapper that simulations memory allocation failure or
2026 ** tracks memory usage, for example. </dd>
2027 **
2028 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
2029 ** <dd> ^This option takes single argument of type int, interpreted as a 
2030 ** boolean, which enables or disables the collection of memory allocation 
2031 ** statistics. ^(When memory allocation statistics are disabled, the 
2032 ** following SQLite interfaces become non-operational:
2033 **   <ul>
2034 **   <li> [sqlite3_memory_used()]
2035 **   <li> [sqlite3_memory_highwater()]
2036 **   <li> [sqlite3_soft_heap_limit64()]
2037 **   <li> [sqlite3_status()]
2038 **   </ul>)^
2039 ** ^Memory allocation statistics are enabled by default unless SQLite is
2040 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
2041 ** allocation statistics are disabled by default.
2042 ** </dd>
2043 **
2044 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
2045 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
2046 ** scratch memory.  There are three arguments:  A pointer an 8-byte
2047 ** aligned memory buffer from which the scratch allocations will be
2048 ** drawn, the size of each scratch allocation (sz),
2049 ** and the maximum number of scratch allocations (N).  The sz
2050 ** argument must be a multiple of 16.
2051 ** The first argument must be a pointer to an 8-byte aligned buffer
2052 ** of at least sz*N bytes of memory.
2053 ** ^SQLite will use no more than two scratch buffers per thread.  So
2054 ** N should be set to twice the expected maximum number of threads.
2055 ** ^SQLite will never require a scratch buffer that is more than 6
2056 ** times the database page size. ^If SQLite needs needs additional
2057 ** scratch memory beyond what is provided by this configuration option, then 
2058 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
2059 **
2060 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
2061 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
2062 ** the database page cache with the default page cache implementation.  
2063 ** This configuration should not be used if an application-define page
2064 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
2065 ** There are three arguments to this option: A pointer to 8-byte aligned
2066 ** memory, the size of each page buffer (sz), and the number of pages (N).
2067 ** The sz argument should be the size of the largest database page
2068 ** (a power of two between 512 and 32768) plus a little extra for each
2069 ** page header.  ^The page header size is 20 to 40 bytes depending on
2070 ** the host architecture.  ^It is harmless, apart from the wasted memory,
2071 ** to make sz a little too large.  The first
2072 ** argument should point to an allocation of at least sz*N bytes of memory.
2073 ** ^SQLite will use the memory provided by the first argument to satisfy its
2074 ** memory needs for the first N pages that it adds to cache.  ^If additional
2075 ** page cache memory is needed beyond what is provided by this option, then
2076 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
2077 ** The pointer in the first argument must
2078 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
2079 ** will be undefined.</dd>
2080 **
2081 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2082 ** <dd> ^This option specifies a static memory buffer that SQLite will use
2083 ** for all of its dynamic memory allocation needs beyond those provided
2084 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
2085 ** There are three arguments: An 8-byte aligned pointer to the memory,
2086 ** the number of bytes in the memory buffer, and the minimum allocation size.
2087 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2088 ** to using its default memory allocator (the system malloc() implementation),
2089 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
2090 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
2091 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
2092 ** allocator is engaged to handle all of SQLites memory allocation needs.
2093 ** The first pointer (the memory pointer) must be aligned to an 8-byte
2094 ** boundary or subsequent behavior of SQLite will be undefined.
2095 ** The minimum allocation size is capped at 2**12. Reasonable values
2096 ** for the minimum allocation size are 2**5 through 2**8.</dd>
2097 **
2098 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2099 ** <dd> ^(This option takes a single argument which is a pointer to an
2100 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
2101 ** alternative low-level mutex routines to be used in place
2102 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
2103 ** content of the [sqlite3_mutex_methods] structure before the call to
2104 ** [sqlite3_config()] returns. ^If SQLite is compiled with
2105 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2106 ** the entire mutexing subsystem is omitted from the build and hence calls to
2107 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2108 ** return [SQLITE_ERROR].</dd>
2109 **
2110 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2111 ** <dd> ^(This option takes a single argument which is a pointer to an
2112 ** instance of the [sqlite3_mutex_methods] structure.  The
2113 ** [sqlite3_mutex_methods]
2114 ** structure is filled with the currently defined mutex routines.)^
2115 ** This option can be used to overload the default mutex allocation
2116 ** routines with a wrapper used to track mutex usage for performance
2117 ** profiling or testing, for example.   ^If SQLite is compiled with
2118 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2119 ** the entire mutexing subsystem is omitted from the build and hence calls to
2120 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2121 ** return [SQLITE_ERROR].</dd>
2122 **
2123 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2124 ** <dd> ^(This option takes two arguments that determine the default
2125 ** memory allocation for the lookaside memory allocator on each
2126 ** [database connection].  The first argument is the
2127 ** size of each lookaside buffer slot and the second is the number of
2128 ** slots allocated to each database connection.)^  ^(This option sets the
2129 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2130 ** verb to [sqlite3_db_config()] can be used to change the lookaside
2131 ** configuration on individual connections.)^ </dd>
2132 **
2133 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2134 ** <dd> ^(This option takes a single argument which is a pointer to
2135 ** an [sqlite3_pcache_methods2] object.  This object specifies the interface
2136 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
2137 ** object and uses it for page cache memory allocations.</dd>
2138 **
2139 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2140 ** <dd> ^(This option takes a single argument which is a pointer to an
2141 ** [sqlite3_pcache_methods2] object.  SQLite copies of the current
2142 ** page cache implementation into that object.)^ </dd>
2143 **
2144 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2145 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2146 ** function with a call signature of void(*)(void*,int,const char*), 
2147 ** and a pointer to void. ^If the function pointer is not NULL, it is
2148 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
2149 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2150 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2151 ** passed through as the first parameter to the application-defined logger
2152 ** function whenever that function is invoked.  ^The second parameter to
2153 ** the logger function is a copy of the first parameter to the corresponding
2154 ** [sqlite3_log()] call and is intended to be a [result code] or an
2155 ** [extended result code].  ^The third parameter passed to the logger is
2156 ** log message after formatting via [sqlite3_snprintf()].
2157 ** The SQLite logging interface is not reentrant; the logger function
2158 ** supplied by the application must not invoke any SQLite interface.
2159 ** In a multi-threaded application, the application-defined logger
2160 ** function must be threadsafe. </dd>
2161 **
2162 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2163 ** <dd> This option takes a single argument of type int. If non-zero, then
2164 ** URI handling is globally enabled. If the parameter is zero, then URI handling
2165 ** is globally disabled. If URI handling is globally enabled, all filenames
2166 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
2167 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2168 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2169 ** connection is opened. If it is globally disabled, filenames are
2170 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2171 ** database connection is opened. By default, URI handling is globally
2172 ** disabled. The default value may be changed by compiling with the
2173 ** [SQLITE_USE_URI] symbol defined.
2174 **
2175 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2176 ** <dd> This option takes a single integer argument which is interpreted as
2177 ** a boolean in order to enable or disable the use of covering indices for
2178 ** full table scans in the query optimizer.  The default setting is determined
2179 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2180 ** if that compile-time option is omitted.
2181 ** The ability to disable the use of covering indices for full table scans
2182 ** is because some incorrectly coded legacy applications might malfunction
2183 ** malfunction when the optimization is enabled.  Providing the ability to
2184 ** disable the optimization allows the older, buggy application code to work
2185 ** without change even with newer versions of SQLite.
2186 **
2187 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2188 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2189 ** <dd> These options are obsolete and should not be used by new code.
2190 ** They are retained for backwards compatibility but are now no-ops.
2191 ** </dl>
2192 **
2193 ** [[SQLITE_CONFIG_SQLLOG]]
2194 ** <dt>SQLITE_CONFIG_SQLLOG
2195 ** <dd>This option is only available if sqlite is compiled with the
2196 ** SQLITE_ENABLE_SQLLOG pre-processor macro defined. The first argument should
2197 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2198 ** The second should be of type (void*). The callback is invoked by the library
2199 ** in three separate circumstances, identified by the value passed as the
2200 ** fourth parameter. If the fourth parameter is 0, then the database connection
2201 ** passed as the second argument has just been opened. The third argument
2202 ** points to a buffer containing the name of the main database file. If the
2203 ** fourth parameter is 1, then the SQL statement that the third parameter
2204 ** points to has just been executed. Or, if the fourth parameter is 2, then
2205 ** the connection being passed as the second parameter is being closed. The
2206 ** third parameter is passed NULL In this case.
2207 ** </dl>
2208 */
2209 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2210 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2211 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2212 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2213 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2214 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2215 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2216 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2217 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2218 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2219 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2220 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
2221 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2222 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
2223 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2224 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2225 #define SQLITE_CONFIG_URI          17  /* int */
2226 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2227 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2228 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
2229 #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
2230
2231 /*
2232 ** CAPI3REF: Database Connection Configuration Options
2233 **
2234 ** These constants are the available integer configuration options that
2235 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2236 **
2237 ** New configuration options may be added in future releases of SQLite.
2238 ** Existing configuration options might be discontinued.  Applications
2239 ** should check the return code from [sqlite3_db_config()] to make sure that
2240 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
2241 ** non-zero [error code] if a discontinued or unsupported configuration option
2242 ** is invoked.
2243 **
2244 ** <dl>
2245 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2246 ** <dd> ^This option takes three additional arguments that determine the 
2247 ** [lookaside memory allocator] configuration for the [database connection].
2248 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2249 ** pointer to a memory buffer to use for lookaside memory.
2250 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2251 ** may be NULL in which case SQLite will allocate the
2252 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2253 ** size of each lookaside buffer slot.  ^The third argument is the number of
2254 ** slots.  The size of the buffer in the first argument must be greater than
2255 ** or equal to the product of the second and third arguments.  The buffer
2256 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2257 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2258 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2259 ** configuration for a database connection can only be changed when that
2260 ** connection is not currently using lookaside memory, or in other words
2261 ** when the "current value" returned by
2262 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2263 ** Any attempt to change the lookaside memory configuration when lookaside
2264 ** memory is in use leaves the configuration unchanged and returns 
2265 ** [SQLITE_BUSY].)^</dd>
2266 **
2267 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2268 ** <dd> ^This option is used to enable or disable the enforcement of
2269 ** [foreign key constraints].  There should be two additional arguments.
2270 ** The first argument is an integer which is 0 to disable FK enforcement,
2271 ** positive to enable FK enforcement or negative to leave FK enforcement
2272 ** unchanged.  The second parameter is a pointer to an integer into which
2273 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2274 ** following this call.  The second parameter may be a NULL pointer, in
2275 ** which case the FK enforcement setting is not reported back. </dd>
2276 **
2277 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2278 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2279 ** There should be two additional arguments.
2280 ** The first argument is an integer which is 0 to disable triggers,
2281 ** positive to enable triggers or negative to leave the setting unchanged.
2282 ** The second parameter is a pointer to an integer into which
2283 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2284 ** following this call.  The second parameter may be a NULL pointer, in
2285 ** which case the trigger setting is not reported back. </dd>
2286 **
2287 ** </dl>
2288 */
2289 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2290 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2291 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2292
2293
2294 /*
2295 ** CAPI3REF: Enable Or Disable Extended Result Codes
2296 **
2297 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2298 ** [extended result codes] feature of SQLite. ^The extended result
2299 ** codes are disabled by default for historical compatibility.
2300 */
2301 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2302
2303 /*
2304 ** CAPI3REF: Last Insert Rowid
2305 **
2306 ** ^Each entry in an SQLite table has a unique 64-bit signed
2307 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2308 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2309 ** names are not also used by explicitly declared columns. ^If
2310 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2311 ** is another alias for the rowid.
2312 **
2313 ** ^This routine returns the [rowid] of the most recent
2314 ** successful [INSERT] into the database from the [database connection]
2315 ** in the first argument.  ^As of SQLite version 3.7.7, this routines
2316 ** records the last insert rowid of both ordinary tables and [virtual tables].
2317 ** ^If no successful [INSERT]s
2318 ** have ever occurred on that database connection, zero is returned.
2319 **
2320 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2321 ** method, then this routine will return the [rowid] of the inserted
2322 ** row as long as the trigger or virtual table method is running.
2323 ** But once the trigger or virtual table method ends, the value returned 
2324 ** by this routine reverts to what it was before the trigger or virtual
2325 ** table method began.)^
2326 **
2327 ** ^An [INSERT] that fails due to a constraint violation is not a
2328 ** successful [INSERT] and does not change the value returned by this
2329 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2330 ** and INSERT OR ABORT make no changes to the return value of this
2331 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2332 ** encounters a constraint violation, it does not fail.  The
2333 ** INSERT continues to completion after deleting rows that caused
2334 ** the constraint problem so INSERT OR REPLACE will always change
2335 ** the return value of this interface.)^
2336 **
2337 ** ^For the purposes of this routine, an [INSERT] is considered to
2338 ** be successful even if it is subsequently rolled back.
2339 **
2340 ** This function is accessible to SQL statements via the
2341 ** [last_insert_rowid() SQL function].
2342 **
2343 ** If a separate thread performs a new [INSERT] on the same
2344 ** database connection while the [sqlite3_last_insert_rowid()]
2345 ** function is running and thus changes the last insert [rowid],
2346 ** then the value returned by [sqlite3_last_insert_rowid()] is
2347 ** unpredictable and might not equal either the old or the new
2348 ** last insert [rowid].
2349 */
2350 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2351
2352 /*
2353 ** CAPI3REF: Count The Number Of Rows Modified
2354 **
2355 ** ^This function returns the number of database rows that were changed
2356 ** or inserted or deleted by the most recently completed SQL statement
2357 ** on the [database connection] specified by the first parameter.
2358 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2359 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2360 ** triggers or [foreign key actions] are not counted.)^ Use the
2361 ** [sqlite3_total_changes()] function to find the total number of changes
2362 ** including changes caused by triggers and foreign key actions.
2363 **
2364 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2365 ** are not counted.  Only real table changes are counted.
2366 **
2367 ** ^(A "row change" is a change to a single row of a single table
2368 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2369 ** are changed as side effects of [REPLACE] constraint resolution,
2370 ** rollback, ABORT processing, [DROP TABLE], or by any other
2371 ** mechanisms do not count as direct row changes.)^
2372 **
2373 ** A "trigger context" is a scope of execution that begins and
2374 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2375 ** Most SQL statements are
2376 ** evaluated outside of any trigger.  This is the "top level"
2377 ** trigger context.  If a trigger fires from the top level, a
2378 ** new trigger context is entered for the duration of that one
2379 ** trigger.  Subtriggers create subcontexts for their duration.
2380 **
2381 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2382 ** not create a new trigger context.
2383 **
2384 ** ^This function returns the number of direct row changes in the
2385 ** most recent INSERT, UPDATE, or DELETE statement within the same
2386 ** trigger context.
2387 **
2388 ** ^Thus, when called from the top level, this function returns the
2389 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2390 ** that also occurred at the top level.  ^(Within the body of a trigger,
2391 ** the sqlite3_changes() interface can be called to find the number of
2392 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2393 ** statement within the body of the same trigger.
2394 ** However, the number returned does not include changes
2395 ** caused by subtriggers since those have their own context.)^
2396 **
2397 ** See also the [sqlite3_total_changes()] interface, the
2398 ** [count_changes pragma], and the [changes() SQL function].
2399 **
2400 ** If a separate thread makes changes on the same database connection
2401 ** while [sqlite3_changes()] is running then the value returned
2402 ** is unpredictable and not meaningful.
2403 */
2404 SQLITE_API int sqlite3_changes(sqlite3*);
2405
2406 /*
2407 ** CAPI3REF: Total Number Of Rows Modified
2408 **
2409 ** ^This function returns the number of row changes caused by [INSERT],
2410 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2411 ** ^(The count returned by sqlite3_total_changes() includes all changes
2412 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2413 ** [foreign key actions]. However,
2414 ** the count does not include changes used to implement [REPLACE] constraints,
2415 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2416 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2417 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2418 ** are counted.)^
2419 ** ^The sqlite3_total_changes() function counts the changes as soon as
2420 ** the statement that makes them is completed (when the statement handle
2421 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2422 **
2423 ** See also the [sqlite3_changes()] interface, the
2424 ** [count_changes pragma], and the [total_changes() SQL function].
2425 **
2426 ** If a separate thread makes changes on the same database connection
2427 ** while [sqlite3_total_changes()] is running then the value
2428 ** returned is unpredictable and not meaningful.
2429 */
2430 SQLITE_API int sqlite3_total_changes(sqlite3*);
2431
2432 /*
2433 ** CAPI3REF: Interrupt A Long-Running Query
2434 **
2435 ** ^This function causes any pending database operation to abort and
2436 ** return at its earliest opportunity. This routine is typically
2437 ** called in response to a user action such as pressing "Cancel"
2438 ** or Ctrl-C where the user wants a long query operation to halt
2439 ** immediately.
2440 **
2441 ** ^It is safe to call this routine from a thread different from the
2442 ** thread that is currently running the database operation.  But it
2443 ** is not safe to call this routine with a [database connection] that
2444 ** is closed or might close before sqlite3_interrupt() returns.
2445 **
2446 ** ^If an SQL operation is very nearly finished at the time when
2447 ** sqlite3_interrupt() is called, then it might not have an opportunity
2448 ** to be interrupted and might continue to completion.
2449 **
2450 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2451 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2452 ** that is inside an explicit transaction, then the entire transaction
2453 ** will be rolled back automatically.
2454 **
2455 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2456 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2457 ** that are started after the sqlite3_interrupt() call and before the 
2458 ** running statements reaches zero are interrupted as if they had been
2459 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2460 ** that are started after the running statement count reaches zero are
2461 ** not effected by the sqlite3_interrupt().
2462 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2463 ** SQL statements is a no-op and has no effect on SQL statements
2464 ** that are started after the sqlite3_interrupt() call returns.
2465 **
2466 ** If the database connection closes while [sqlite3_interrupt()]
2467 ** is running then bad things will likely happen.
2468 */
2469 SQLITE_API void sqlite3_interrupt(sqlite3*);
2470
2471 /*
2472 ** CAPI3REF: Determine If An SQL Statement Is Complete
2473 **
2474 ** These routines are useful during command-line input to determine if the
2475 ** currently entered text seems to form a complete SQL statement or
2476 ** if additional input is needed before sending the text into
2477 ** SQLite for parsing.  ^These routines return 1 if the input string
2478 ** appears to be a complete SQL statement.  ^A statement is judged to be
2479 ** complete if it ends with a semicolon token and is not a prefix of a
2480 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2481 ** string literals or quoted identifier names or comments are not
2482 ** independent tokens (they are part of the token in which they are
2483 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2484 ** and comments that follow the final semicolon are ignored.
2485 **
2486 ** ^These routines return 0 if the statement is incomplete.  ^If a
2487 ** memory allocation fails, then SQLITE_NOMEM is returned.
2488 **
2489 ** ^These routines do not parse the SQL statements thus
2490 ** will not detect syntactically incorrect SQL.
2491 **
2492 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2493 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2494 ** automatically by sqlite3_complete16().  If that initialization fails,
2495 ** then the return value from sqlite3_complete16() will be non-zero
2496 ** regardless of whether or not the input SQL is complete.)^
2497 **
2498 ** The input to [sqlite3_complete()] must be a zero-terminated
2499 ** UTF-8 string.
2500 **
2501 ** The input to [sqlite3_complete16()] must be a zero-terminated
2502 ** UTF-16 string in native byte order.
2503 */
2504 SQLITE_API int sqlite3_complete(const char *sql);
2505 SQLITE_API int sqlite3_complete16(const void *sql);
2506
2507 /*
2508 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2509 **
2510 ** ^This routine sets a callback function that might be invoked whenever
2511 ** an attempt is made to open a database table that another thread
2512 ** or process has locked.
2513 **
2514 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2515 ** is returned immediately upon encountering the lock.  ^If the busy callback
2516 ** is not NULL, then the callback might be invoked with two arguments.
2517 **
2518 ** ^The first argument to the busy handler is a copy of the void* pointer which
2519 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2520 ** the busy handler callback is the number of times that the busy handler has
2521 ** been invoked for this locking event.  ^If the
2522 ** busy callback returns 0, then no additional attempts are made to
2523 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2524 ** ^If the callback returns non-zero, then another attempt
2525 ** is made to open the database for reading and the cycle repeats.
2526 **
2527 ** The presence of a busy handler does not guarantee that it will be invoked
2528 ** when there is lock contention. ^If SQLite determines that invoking the busy
2529 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2530 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2531 ** Consider a scenario where one process is holding a read lock that
2532 ** it is trying to promote to a reserved lock and
2533 ** a second process is holding a reserved lock that it is trying
2534 ** to promote to an exclusive lock.  The first process cannot proceed
2535 ** because it is blocked by the second and the second process cannot
2536 ** proceed because it is blocked by the first.  If both processes
2537 ** invoke the busy handlers, neither will make any progress.  Therefore,
2538 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2539 ** will induce the first process to release its read lock and allow
2540 ** the second process to proceed.
2541 **
2542 ** ^The default busy callback is NULL.
2543 **
2544 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2545 ** when SQLite is in the middle of a large transaction where all the
2546 ** changes will not fit into the in-memory cache.  SQLite will
2547 ** already hold a RESERVED lock on the database file, but it needs
2548 ** to promote this lock to EXCLUSIVE so that it can spill cache
2549 ** pages into the database file without harm to concurrent
2550 ** readers.  ^If it is unable to promote the lock, then the in-memory
2551 ** cache will be left in an inconsistent state and so the error
2552 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2553 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2554 ** forces an automatic rollback of the changes.  See the
2555 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2556 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2557 ** this is important.
2558 **
2559 ** ^(There can only be a single busy handler defined for each
2560 ** [database connection].  Setting a new busy handler clears any
2561 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2562 ** will also set or clear the busy handler.
2563 **
2564 ** The busy callback should not take any actions which modify the
2565 ** database connection that invoked the busy handler.  Any such actions
2566 ** result in undefined behavior.
2567 ** 
2568 ** A busy handler must not close the database connection
2569 ** or [prepared statement] that invoked the busy handler.
2570 */
2571 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2572
2573 /*
2574 ** CAPI3REF: Set A Busy Timeout
2575 **
2576 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2577 ** for a specified amount of time when a table is locked.  ^The handler
2578 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2579 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2580 ** the handler returns 0 which causes [sqlite3_step()] to return
2581 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2582 **
2583 ** ^Calling this routine with an argument less than or equal to zero
2584 ** turns off all busy handlers.
2585 **
2586 ** ^(There can only be a single busy handler for a particular
2587 ** [database connection] any any given moment.  If another busy handler
2588 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2589 ** this routine, that other busy handler is cleared.)^
2590 */
2591 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2592
2593 /*
2594 ** CAPI3REF: Convenience Routines For Running Queries
2595 **
2596 ** This is a legacy interface that is preserved for backwards compatibility.
2597 ** Use of this interface is not recommended.
2598 **
2599 ** Definition: A <b>result table</b> is memory data structure created by the
2600 ** [sqlite3_get_table()] interface.  A result table records the
2601 ** complete query results from one or more queries.
2602 **
2603 ** The table conceptually has a number of rows and columns.  But
2604 ** these numbers are not part of the result table itself.  These
2605 ** numbers are obtained separately.  Let N be the number of rows
2606 ** and M be the number of columns.
2607 **
2608 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2609 ** There are (N+1)*M elements in the array.  The first M pointers point
2610 ** to zero-terminated strings that  contain the names of the columns.
2611 ** The remaining entries all point to query results.  NULL values result
2612 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2613 ** string representation as returned by [sqlite3_column_text()].
2614 **
2615 ** A result table might consist of one or more memory allocations.
2616 ** It is not safe to pass a result table directly to [sqlite3_free()].
2617 ** A result table should be deallocated using [sqlite3_free_table()].
2618 **
2619 ** ^(As an example of the result table format, suppose a query result
2620 ** is as follows:
2621 **
2622 ** <blockquote><pre>
2623 **        Name        | Age
2624 **        -----------------------
2625 **        Alice       | 43
2626 **        Bob         | 28
2627 **        Cindy       | 21
2628 ** </pre></blockquote>
2629 **
2630 ** There are two column (M==2) and three rows (N==3).  Thus the
2631 ** result table has 8 entries.  Suppose the result table is stored
2632 ** in an array names azResult.  Then azResult holds this content:
2633 **
2634 ** <blockquote><pre>
2635 **        azResult&#91;0] = "Name";
2636 **        azResult&#91;1] = "Age";
2637 **        azResult&#91;2] = "Alice";
2638 **        azResult&#91;3] = "43";
2639 **        azResult&#91;4] = "Bob";
2640 **        azResult&#91;5] = "28";
2641 **        azResult&#91;6] = "Cindy";
2642 **        azResult&#91;7] = "21";
2643 ** </pre></blockquote>)^
2644 **
2645 ** ^The sqlite3_get_table() function evaluates one or more
2646 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2647 ** string of its 2nd parameter and returns a result table to the
2648 ** pointer given in its 3rd parameter.
2649 **
2650 ** After the application has finished with the result from sqlite3_get_table(),
2651 ** it must pass the result table pointer to sqlite3_free_table() in order to
2652 ** release the memory that was malloced.  Because of the way the
2653 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2654 ** function must not try to call [sqlite3_free()] directly.  Only
2655 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2656 **
2657 ** The sqlite3_get_table() interface is implemented as a wrapper around
2658 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2659 ** to any internal data structures of SQLite.  It uses only the public
2660 ** interface defined here.  As a consequence, errors that occur in the
2661 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2662 ** reflected in subsequent calls to [sqlite3_errcode()] or
2663 ** [sqlite3_errmsg()].
2664 */
2665 SQLITE_API int sqlite3_get_table(
2666   sqlite3 *db,          /* An open database */
2667   const char *zSql,     /* SQL to be evaluated */
2668   char ***pazResult,    /* Results of the query */
2669   int *pnRow,           /* Number of result rows written here */
2670   int *pnColumn,        /* Number of result columns written here */
2671   char **pzErrmsg       /* Error msg written here */
2672 );
2673 SQLITE_API void sqlite3_free_table(char **result);
2674
2675 /*
2676 ** CAPI3REF: Formatted String Printing Functions
2677 **
2678 ** These routines are work-alikes of the "printf()" family of functions
2679 ** from the standard C library.
2680 **
2681 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2682 ** results into memory obtained from [sqlite3_malloc()].
2683 ** The strings returned by these two routines should be
2684 ** released by [sqlite3_free()].  ^Both routines return a
2685 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2686 ** memory to hold the resulting string.
2687 **
2688 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2689 ** the standard C library.  The result is written into the
2690 ** buffer supplied as the second parameter whose size is given by
2691 ** the first parameter. Note that the order of the
2692 ** first two parameters is reversed from snprintf().)^  This is an
2693 ** historical accident that cannot be fixed without breaking
2694 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2695 ** returns a pointer to its buffer instead of the number of
2696 ** characters actually written into the buffer.)^  We admit that
2697 ** the number of characters written would be a more useful return
2698 ** value but we cannot change the implementation of sqlite3_snprintf()
2699 ** now without breaking compatibility.
2700 **
2701 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2702 ** guarantees that the buffer is always zero-terminated.  ^The first
2703 ** parameter "n" is the total size of the buffer, including space for
2704 ** the zero terminator.  So the longest string that can be completely
2705 ** written will be n-1 characters.
2706 **
2707 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2708 **
2709 ** These routines all implement some additional formatting
2710 ** options that are useful for constructing SQL statements.
2711 ** All of the usual printf() formatting options apply.  In addition, there
2712 ** is are "%q", "%Q", and "%z" options.
2713 **
2714 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2715 ** string from the argument list.  But %q also doubles every '\'' character.
2716 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2717 ** character it escapes that character and allows it to be inserted into
2718 ** the string.
2719 **
2720 ** For example, assume the string variable zText contains text as follows:
2721 **
2722 ** <blockquote><pre>
2723 **  char *zText = "It's a happy day!";
2724 ** </pre></blockquote>
2725 **
2726 ** One can use this text in an SQL statement as follows:
2727 **
2728 ** <blockquote><pre>
2729 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2730 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2731 **  sqlite3_free(zSQL);
2732 ** </pre></blockquote>
2733 **
2734 ** Because the %q format string is used, the '\'' character in zText
2735 ** is escaped and the SQL generated is as follows:
2736 **
2737 ** <blockquote><pre>
2738 **  INSERT INTO table1 VALUES('It''s a happy day!')
2739 ** </pre></blockquote>
2740 **
2741 ** This is correct.  Had we used %s instead of %q, the generated SQL
2742 ** would have looked like this:
2743 **
2744 ** <blockquote><pre>
2745 **  INSERT INTO table1 VALUES('It's a happy day!');
2746 ** </pre></blockquote>
2747 **
2748 ** This second example is an SQL syntax error.  As a general rule you should
2749 ** always use %q instead of %s when inserting text into a string literal.
2750 **
2751 ** ^(The %Q option works like %q except it also adds single quotes around
2752 ** the outside of the total string.  Additionally, if the parameter in the
2753 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2754 ** single quotes).)^  So, for example, one could say:
2755 **
2756 ** <blockquote><pre>
2757 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2758 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2759 **  sqlite3_free(zSQL);
2760 ** </pre></blockquote>
2761 **
2762 ** The code above will render a correct SQL statement in the zSQL
2763 ** variable even if the zText variable is a NULL pointer.
2764 **
2765 ** ^(The "%z" formatting option works like "%s" but with the
2766 ** addition that after the string has been read and copied into
2767 ** the result, [sqlite3_free()] is called on the input string.)^
2768 */
2769 SQLITE_API char *sqlite3_mprintf(const char*,...);
2770 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2771 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2772 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2773
2774 /*
2775 ** CAPI3REF: Memory Allocation Subsystem
2776 **
2777 ** The SQLite core uses these three routines for all of its own
2778 ** internal memory allocation needs. "Core" in the previous sentence
2779 ** does not include operating-system specific VFS implementation.  The
2780 ** Windows VFS uses native malloc() and free() for some operations.
2781 **
2782 ** ^The sqlite3_malloc() routine returns a pointer to a block
2783 ** of memory at least N bytes in length, where N is the parameter.
2784 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2785 ** memory, it returns a NULL pointer.  ^If the parameter N to
2786 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2787 ** a NULL pointer.
2788 **
2789 ** ^Calling sqlite3_free() with a pointer previously returned
2790 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2791 ** that it might be reused.  ^The sqlite3_free() routine is
2792 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2793 ** to sqlite3_free() is harmless.  After being freed, memory
2794 ** should neither be read nor written.  Even reading previously freed
2795 ** memory might result in a segmentation fault or other severe error.
2796 ** Memory corruption, a segmentation fault, or other severe error
2797 ** might result if sqlite3_free() is called with a non-NULL pointer that
2798 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2799 **
2800 ** ^(The sqlite3_realloc() interface attempts to resize a
2801 ** prior memory allocation to be at least N bytes, where N is the
2802 ** second parameter.  The memory allocation to be resized is the first
2803 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2804 ** is a NULL pointer then its behavior is identical to calling
2805 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2806 ** ^If the second parameter to sqlite3_realloc() is zero or
2807 ** negative then the behavior is exactly the same as calling
2808 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2809 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2810 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2811 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2812 ** of the prior allocation are copied into the beginning of buffer returned
2813 ** by sqlite3_realloc() and the prior allocation is freed.
2814 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2815 ** is not freed.
2816 **
2817 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2818 ** is always aligned to at least an 8 byte boundary, or to a
2819 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2820 ** option is used.
2821 **
2822 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2823 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2824 ** implementation of these routines to be omitted.  That capability
2825 ** is no longer provided.  Only built-in memory allocators can be used.
2826 **
2827 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2828 ** the system malloc() and free() directly when converting
2829 ** filenames between the UTF-8 encoding used by SQLite
2830 ** and whatever filename encoding is used by the particular Windows
2831 ** installation.  Memory allocation errors were detected, but
2832 ** they were reported back as [SQLITE_CANTOPEN] or
2833 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2834 **
2835 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2836 ** must be either NULL or else pointers obtained from a prior
2837 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2838 ** not yet been released.
2839 **
2840 ** The application must not read or write any part of
2841 ** a block of memory after it has been released using
2842 ** [sqlite3_free()] or [sqlite3_realloc()].
2843 */
2844 SQLITE_API void *sqlite3_malloc(int);
2845 SQLITE_API void *sqlite3_realloc(void*, int);
2846 SQLITE_API void sqlite3_free(void*);
2847
2848 /*
2849 ** CAPI3REF: Memory Allocator Statistics
2850 **
2851 ** SQLite provides these two interfaces for reporting on the status
2852 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2853 ** routines, which form the built-in memory allocation subsystem.
2854 **
2855 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2856 ** of memory currently outstanding (malloced but not freed).
2857 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2858 ** value of [sqlite3_memory_used()] since the high-water mark
2859 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2860 ** [sqlite3_memory_highwater()] include any overhead
2861 ** added by SQLite in its implementation of [sqlite3_malloc()],
2862 ** but not overhead added by the any underlying system library
2863 ** routines that [sqlite3_malloc()] may call.
2864 **
2865 ** ^The memory high-water mark is reset to the current value of
2866 ** [sqlite3_memory_used()] if and only if the parameter to
2867 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2868 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2869 ** prior to the reset.
2870 */
2871 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2872 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2873
2874 /*
2875 ** CAPI3REF: Pseudo-Random Number Generator
2876 **
2877 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2878 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2879 ** already uses the largest possible [ROWID].  The PRNG is also used for
2880 ** the build-in random() and randomblob() SQL functions.  This interface allows
2881 ** applications to access the same PRNG for other purposes.
2882 **
2883 ** ^A call to this routine stores N bytes of randomness into buffer P.
2884 **
2885 ** ^The first time this routine is invoked (either internally or by
2886 ** the application) the PRNG is seeded using randomness obtained
2887 ** from the xRandomness method of the default [sqlite3_vfs] object.
2888 ** ^On all subsequent invocations, the pseudo-randomness is generated
2889 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2890 ** method.
2891 */
2892 SQLITE_API void sqlite3_randomness(int N, void *P);
2893
2894 /*
2895 ** CAPI3REF: Compile-Time Authorization Callbacks
2896 **
2897 ** ^This routine registers an authorizer callback with a particular
2898 ** [database connection], supplied in the first argument.
2899 ** ^The authorizer callback is invoked as SQL statements are being compiled
2900 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2901 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2902 ** points during the compilation process, as logic is being created
2903 ** to perform various actions, the authorizer callback is invoked to
2904 ** see if those actions are allowed.  ^The authorizer callback should
2905 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2906 ** specific action but allow the SQL statement to continue to be
2907 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2908 ** rejected with an error.  ^If the authorizer callback returns
2909 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2910 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2911 ** the authorizer will fail with an error message.
2912 **
2913 ** When the callback returns [SQLITE_OK], that means the operation
2914 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2915 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2916 ** authorizer will fail with an error message explaining that
2917 ** access is denied. 
2918 **
2919 ** ^The first parameter to the authorizer callback is a copy of the third
2920 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2921 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2922 ** the particular action to be authorized. ^The third through sixth parameters
2923 ** to the callback are zero-terminated strings that contain additional
2924 ** details about the action to be authorized.
2925 **
2926 ** ^If the action code is [SQLITE_READ]
2927 ** and the callback returns [SQLITE_IGNORE] then the
2928 ** [prepared statement] statement is constructed to substitute
2929 ** a NULL value in place of the table column that would have
2930 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2931 ** return can be used to deny an untrusted user access to individual
2932 ** columns of a table.
2933 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2934 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2935 ** [truncate optimization] is disabled and all rows are deleted individually.
2936 **
2937 ** An authorizer is used when [sqlite3_prepare | preparing]
2938 ** SQL statements from an untrusted source, to ensure that the SQL statements
2939 ** do not try to access data they are not allowed to see, or that they do not
2940 ** try to execute malicious statements that damage the database.  For
2941 ** example, an application may allow a user to enter arbitrary
2942 ** SQL queries for evaluation by a database.  But the application does
2943 ** not want the user to be able to make arbitrary changes to the
2944 ** database.  An authorizer could then be put in place while the
2945 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2946 ** disallows everything except [SELECT] statements.
2947 **
2948 ** Applications that need to process SQL from untrusted sources
2949 ** might also consider lowering resource limits using [sqlite3_limit()]
2950 ** and limiting database size using the [max_page_count] [PRAGMA]
2951 ** in addition to using an authorizer.
2952 **
2953 ** ^(Only a single authorizer can be in place on a database connection
2954 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2955 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2956 ** The authorizer is disabled by default.
2957 **
2958 ** The authorizer callback must not do anything that will modify
2959 ** the database connection that invoked the authorizer callback.
2960 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2961 ** database connections for the meaning of "modify" in this paragraph.
2962 **
2963 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2964 ** statement might be re-prepared during [sqlite3_step()] due to a 
2965 ** schema change.  Hence, the application should ensure that the
2966 ** correct authorizer callback remains in place during the [sqlite3_step()].
2967 **
2968 ** ^Note that the authorizer callback is invoked only during
2969 ** [sqlite3_prepare()] or its variants.  Authorization is not
2970 ** performed during statement evaluation in [sqlite3_step()], unless
2971 ** as stated in the previous paragraph, sqlite3_step() invokes
2972 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2973 */
2974 SQLITE_API int sqlite3_set_authorizer(
2975   sqlite3*,
2976   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2977   void *pUserData
2978 );
2979
2980 /*
2981 ** CAPI3REF: Authorizer Return Codes
2982 **
2983 ** The [sqlite3_set_authorizer | authorizer callback function] must
2984 ** return either [SQLITE_OK] or one of these two constants in order
2985 ** to signal SQLite whether or not the action is permitted.  See the
2986 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2987 ** information.
2988 **
2989 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
2990 ** from the [sqlite3_vtab_on_conflict()] interface.
2991 */
2992 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2993 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2994
2995 /*
2996 ** CAPI3REF: Authorizer Action Codes
2997 **
2998 ** The [sqlite3_set_authorizer()] interface registers a callback function
2999 ** that is invoked to authorize certain SQL statement actions.  The
3000 ** second parameter to the callback is an integer code that specifies
3001 ** what action is being authorized.  These are the integer action codes that
3002 ** the authorizer callback may be passed.
3003 **
3004 ** These action code values signify what kind of operation is to be
3005 ** authorized.  The 3rd and 4th parameters to the authorization
3006 ** callback function will be parameters or NULL depending on which of these
3007 ** codes is used as the second parameter.  ^(The 5th parameter to the
3008 ** authorizer callback is the name of the database ("main", "temp",
3009 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
3010 ** is the name of the inner-most trigger or view that is responsible for
3011 ** the access attempt or NULL if this access attempt is directly from
3012 ** top-level SQL code.
3013 */
3014 /******************************************* 3rd ************ 4th ***********/
3015 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
3016 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
3017 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
3018 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
3019 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
3020 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
3021 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
3022 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
3023 #define SQLITE_DELETE                9   /* Table Name      NULL            */
3024 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
3025 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
3026 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
3027 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
3028 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
3029 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
3030 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
3031 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
3032 #define SQLITE_INSERT               18   /* Table Name      NULL            */
3033 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
3034 #define SQLITE_READ                 20   /* Table Name      Column Name     */
3035 #define SQLITE_SELECT               21   /* NULL            NULL            */
3036 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
3037 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
3038 #define SQLITE_ATTACH               24   /* Filename        NULL            */
3039 #define SQLITE_DETACH               25   /* Database Name   NULL            */
3040 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
3041 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
3042 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
3043 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
3044 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
3045 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
3046 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
3047 #define SQLITE_COPY                  0   /* No longer used */
3048
3049 /*
3050 ** CAPI3REF: Tracing And Profiling Functions
3051 **
3052 ** These routines register callback functions that can be used for
3053 ** tracing and profiling the execution of SQL statements.
3054 **
3055 ** ^The callback function registered by sqlite3_trace() is invoked at
3056 ** various times when an SQL statement is being run by [sqlite3_step()].
3057 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3058 ** SQL statement text as the statement first begins executing.
3059 ** ^(Additional sqlite3_trace() callbacks might occur
3060 ** as each triggered subprogram is entered.  The callbacks for triggers
3061 ** contain a UTF-8 SQL comment that identifies the trigger.)^
3062 **
3063 ** ^The callback function registered by sqlite3_profile() is invoked
3064 ** as each SQL statement finishes.  ^The profile callback contains
3065 ** the original statement text and an estimate of wall-clock time
3066 ** of how long that statement took to run.  ^The profile callback
3067 ** time is in units of nanoseconds, however the current implementation
3068 ** is only capable of millisecond resolution so the six least significant
3069 ** digits in the time are meaningless.  Future versions of SQLite
3070 ** might provide greater resolution on the profiler callback.  The
3071 ** sqlite3_profile() function is considered experimental and is
3072 ** subject to change in future versions of SQLite.
3073 */
3074 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
3075 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
3076    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3077
3078 /*
3079 ** CAPI3REF: Query Progress Callbacks
3080 **
3081 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3082 ** function X to be invoked periodically during long running calls to
3083 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3084 ** database connection D.  An example use for this
3085 ** interface is to keep a GUI updated during a large query.
3086 **
3087 ** ^The parameter P is passed through as the only parameter to the 
3088 ** callback function X.  ^The parameter N is the number of 
3089 ** [virtual machine instructions] that are evaluated between successive
3090 ** invocations of the callback X.
3091 **
3092 ** ^Only a single progress handler may be defined at one time per
3093 ** [database connection]; setting a new progress handler cancels the
3094 ** old one.  ^Setting parameter X to NULL disables the progress handler.
3095 ** ^The progress handler is also disabled by setting N to a value less
3096 ** than 1.
3097 **
3098 ** ^If the progress callback returns non-zero, the operation is
3099 ** interrupted.  This feature can be used to implement a
3100 ** "Cancel" button on a GUI progress dialog box.
3101 **
3102 ** The progress handler callback must not do anything that will modify
3103 ** the database connection that invoked the progress handler.
3104 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3105 ** database connections for the meaning of "modify" in this paragraph.
3106 **
3107 */
3108 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3109
3110 /*
3111 ** CAPI3REF: Opening A New Database Connection
3112 **
3113 ** ^These routines open an SQLite database file as specified by the 
3114 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3115 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3116 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
3117 ** returned in *ppDb, even if an error occurs.  The only exception is that
3118 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3119 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3120 ** object.)^ ^(If the database is opened (and/or created) successfully, then
3121 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
3122 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3123 ** an English language description of the error following a failure of any
3124 ** of the sqlite3_open() routines.
3125 **
3126 ** ^The default encoding for the database will be UTF-8 if
3127 ** sqlite3_open() or sqlite3_open_v2() is called and
3128 ** UTF-16 in the native byte order if sqlite3_open16() is used.
3129 **
3130 ** Whether or not an error occurs when it is opened, resources
3131 ** associated with the [database connection] handle should be released by
3132 ** passing it to [sqlite3_close()] when it is no longer required.
3133 **
3134 ** The sqlite3_open_v2() interface works like sqlite3_open()
3135 ** except that it accepts two additional parameters for additional control
3136 ** over the new database connection.  ^(The flags parameter to
3137 ** sqlite3_open_v2() can take one of
3138 ** the following three values, optionally combined with the 
3139 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3140 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3141 **
3142 ** <dl>
3143 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3144 ** <dd>The database is opened in read-only mode.  If the database does not
3145 ** already exist, an error is returned.</dd>)^
3146 **
3147 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3148 ** <dd>The database is opened for reading and writing if possible, or reading
3149 ** only if the file is write protected by the operating system.  In either
3150 ** case the database must already exist, otherwise an error is returned.</dd>)^
3151 **
3152 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3153 ** <dd>The database is opened for reading and writing, and is created if
3154 ** it does not already exist. This is the behavior that is always used for
3155 ** sqlite3_open() and sqlite3_open16().</dd>)^
3156 ** </dl>
3157 **
3158 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3159 ** combinations shown above optionally combined with other
3160 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3161 ** then the behavior is undefined.
3162 **
3163 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3164 ** opens in the multi-thread [threading mode] as long as the single-thread
3165 ** mode has not been set at compile-time or start-time.  ^If the
3166 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3167 ** in the serialized [threading mode] unless single-thread was
3168 ** previously selected at compile-time or start-time.
3169 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3170 ** eligible to use [shared cache mode], regardless of whether or not shared
3171 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3172 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3173 ** participate in [shared cache mode] even if it is enabled.
3174 **
3175 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3176 ** [sqlite3_vfs] object that defines the operating system interface that
3177 ** the new database connection should use.  ^If the fourth parameter is
3178 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3179 **
3180 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3181 ** is created for the connection.  ^This in-memory database will vanish when
3182 ** the database connection is closed.  Future versions of SQLite might
3183 ** make use of additional special filenames that begin with the ":" character.
3184 ** It is recommended that when a database filename actually does begin with
3185 ** a ":" character you should prefix the filename with a pathname such as
3186 ** "./" to avoid ambiguity.
3187 **
3188 ** ^If the filename is an empty string, then a private, temporary
3189 ** on-disk database will be created.  ^This private database will be
3190 ** automatically deleted as soon as the database connection is closed.
3191 **
3192 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3193 **
3194 ** ^If [URI filename] interpretation is enabled, and the filename argument
3195 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3196 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3197 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3198 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3199 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3200 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3201 ** by default, but future releases of SQLite might enable URI filename
3202 ** interpretation by default.  See "[URI filenames]" for additional
3203 ** information.
3204 **
3205 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3206 ** authority, then it must be either an empty string or the string 
3207 ** "localhost". ^If the authority is not an empty string or "localhost", an 
3208 ** error is returned to the caller. ^The fragment component of a URI, if 
3209 ** present, is ignored.
3210 **
3211 ** ^SQLite uses the path component of the URI as the name of the disk file
3212 ** which contains the database. ^If the path begins with a '/' character, 
3213 ** then it is interpreted as an absolute path. ^If the path does not begin 
3214 ** with a '/' (meaning that the authority section is omitted from the URI)
3215 ** then the path is interpreted as a relative path. 
3216 ** ^On windows, the first component of an absolute path 
3217 ** is a drive specification (e.g. "C:").
3218 **
3219 ** [[core URI query parameters]]
3220 ** The query component of a URI may contain parameters that are interpreted
3221 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3222 ** SQLite interprets the following three query parameters:
3223 **
3224 ** <ul>
3225 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3226 **     a VFS object that provides the operating system interface that should
3227 **     be used to access the database file on disk. ^If this option is set to
3228 **     an empty string the default VFS object is used. ^Specifying an unknown
3229 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3230 **     present, then the VFS specified by the option takes precedence over
3231 **     the value passed as the fourth parameter to sqlite3_open_v2().
3232 **
3233 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3234 **     "rwc", or "memory". Attempting to set it to any other value is
3235 **     an error)^. 
3236 **     ^If "ro" is specified, then the database is opened for read-only 
3237 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
3238 **     third argument to sqlite3_open_v2(). ^If the mode option is set to 
3239 **     "rw", then the database is opened for read-write (but not create) 
3240 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
3241 **     been set. ^Value "rwc" is equivalent to setting both 
3242 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3243 **     set to "memory" then a pure [in-memory database] that never reads
3244 **     or writes from disk is used. ^It is an error to specify a value for
3245 **     the mode parameter that is less restrictive than that specified by
3246 **     the flags passed in the third parameter to sqlite3_open_v2().
3247 **
3248 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3249 **     "private". ^Setting it to "shared" is equivalent to setting the
3250 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3251 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
3252 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3253 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3254 **     a URI filename, its value overrides any behavior requested by setting
3255 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3256 ** </ul>
3257 **
3258 ** ^Specifying an unknown parameter in the query component of a URI is not an
3259 ** error.  Future versions of SQLite might understand additional query
3260 ** parameters.  See "[query parameters with special meaning to SQLite]" for
3261 ** additional information.
3262 **
3263 ** [[URI filename examples]] <h3>URI filename examples</h3>
3264 **
3265 ** <table border="1" align=center cellpadding=5>
3266 ** <tr><th> URI filenames <th> Results
3267 ** <tr><td> file:data.db <td> 
3268 **          Open the file "data.db" in the current directory.
3269 ** <tr><td> file:/home/fred/data.db<br>
3270 **          file:///home/fred/data.db <br> 
3271 **          file://localhost/home/fred/data.db <br> <td> 
3272 **          Open the database file "/home/fred/data.db".
3273 ** <tr><td> file://darkstar/home/fred/data.db <td> 
3274 **          An error. "darkstar" is not a recognized authority.
3275 ** <tr><td style="white-space:nowrap"> 
3276 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3277 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3278 **          C:. Note that the %20 escaping in this example is not strictly 
3279 **          necessary - space characters can be used literally
3280 **          in URI filenames.
3281 ** <tr><td> file:data.db?mode=ro&cache=private <td> 
3282 **          Open file "data.db" in the current directory for read-only access.
3283 **          Regardless of whether or not shared-cache mode is enabled by
3284 **          default, use a private cache.
3285 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3286 **          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3287 ** <tr><td> file:data.db?mode=readonly <td> 
3288 **          An error. "readonly" is not a valid option for the "mode" parameter.
3289 ** </table>
3290 **
3291 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3292 ** query components of a URI. A hexadecimal escape sequence consists of a
3293 ** percent sign - "%" - followed by exactly two hexadecimal digits 
3294 ** specifying an octet value. ^Before the path or query components of a
3295 ** URI filename are interpreted, they are encoded using UTF-8 and all 
3296 ** hexadecimal escape sequences replaced by a single byte containing the
3297 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3298 ** the results are undefined.
3299 **
3300 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3301 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3302 ** codepage is currently defined.  Filenames containing international
3303 ** characters must be converted to UTF-8 prior to passing them into
3304 ** sqlite3_open() or sqlite3_open_v2().
3305 **
3306 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
3307 ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
3308 ** features that require the use of temporary files may fail.
3309 **
3310 ** See also: [sqlite3_temp_directory]
3311 */
3312 SQLITE_API int sqlite3_open(
3313   const char *filename,   /* Database filename (UTF-8) */
3314   sqlite3 **ppDb          /* OUT: SQLite db handle */
3315 );
3316 SQLITE_API int sqlite3_open16(
3317   const void *filename,   /* Database filename (UTF-16) */
3318   sqlite3 **ppDb          /* OUT: SQLite db handle */
3319 );
3320 SQLITE_API int sqlite3_open_v2(
3321   const char *filename,   /* Database filename (UTF-8) */
3322   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3323   int flags,              /* Flags */
3324   const char *zVfs        /* Name of VFS module to use */
3325 );
3326
3327 /*
3328 ** CAPI3REF: Obtain Values For URI Parameters
3329 **
3330 ** These are utility routines, useful to VFS implementations, that check
3331 ** to see if a database file was a URI that contained a specific query 
3332 ** parameter, and if so obtains the value of that query parameter.
3333 **
3334 ** If F is the database filename pointer passed into the xOpen() method of 
3335 ** a VFS implementation when the flags parameter to xOpen() has one or 
3336 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3337 ** P is the name of the query parameter, then
3338 ** sqlite3_uri_parameter(F,P) returns the value of the P
3339 ** parameter if it exists or a NULL pointer if P does not appear as a 
3340 ** query parameter on F.  If P is a query parameter of F
3341 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3342 ** a pointer to an empty string.
3343 **
3344 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3345 ** parameter and returns true (1) or false (0) according to the value
3346 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3347 ** value of query parameter P is one of "yes", "true", or "on" in any
3348 ** case or if the value begins with a non-zero number.  The 
3349 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3350 ** query parameter P is one of "no", "false", or "off" in any case or
3351 ** if the value begins with a numeric zero.  If P is not a query
3352 ** parameter on F or if the value of P is does not match any of the
3353 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3354 **
3355 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3356 ** 64-bit signed integer and returns that integer, or D if P does not
3357 ** exist.  If the value of P is something other than an integer, then
3358 ** zero is returned.
3359 ** 
3360 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3361 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3362 ** is not a database file pathname pointer that SQLite passed into the xOpen
3363 ** VFS method, then the behavior of this routine is undefined and probably
3364 ** undesirable.
3365 */
3366 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3367 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3368 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3369
3370
3371 /*
3372 ** CAPI3REF: Error Codes And Messages
3373 **
3374 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
3375 ** [extended result code] for the most recent failed sqlite3_* API call
3376 ** associated with a [database connection]. If a prior API call failed
3377 ** but the most recent API call succeeded, the return value from
3378 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3379 ** interface is the same except that it always returns the 
3380 ** [extended result code] even when extended result codes are
3381 ** disabled.
3382 **
3383 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3384 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3385 ** ^(Memory to hold the error message string is managed internally.
3386 ** The application does not need to worry about freeing the result.
3387 ** However, the error string might be overwritten or deallocated by
3388 ** subsequent calls to other SQLite interface functions.)^
3389 **
3390 ** ^The sqlite3_errstr() interface returns the English-language text
3391 ** that describes the [result code], as UTF-8.
3392 ** ^(Memory to hold the error message string is managed internally
3393 ** and must not be freed by the application)^.
3394 **
3395 ** When the serialized [threading mode] is in use, it might be the
3396 ** case that a second error occurs on a separate thread in between
3397 ** the time of the first error and the call to these interfaces.
3398 ** When that happens, the second error will be reported since these
3399 ** interfaces always report the most recent result.  To avoid
3400 ** this, each thread can obtain exclusive use of the [database connection] D
3401 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3402 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3403 ** all calls to the interfaces listed here are completed.
3404 **
3405 ** If an interface fails with SQLITE_MISUSE, that means the interface
3406 ** was invoked incorrectly by the application.  In that case, the
3407 ** error code and message may or may not be set.
3408 */
3409 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3410 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3411 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3412 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3413 SQLITE_API const char *sqlite3_errstr(int);
3414
3415 /*
3416 ** CAPI3REF: SQL Statement Object
3417 ** KEYWORDS: {prepared statement} {prepared statements}
3418 **
3419 ** An instance of this object represents a single SQL statement.
3420 ** This object is variously known as a "prepared statement" or a
3421 ** "compiled SQL statement" or simply as a "statement".
3422 **
3423 ** The life of a statement object goes something like this:
3424 **
3425 ** <ol>
3426 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3427 **      function.
3428 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3429 **      interfaces.
3430 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3431 ** <li> Reset the statement using [sqlite3_reset()] then go back
3432 **      to step 2.  Do this zero or more times.
3433 ** <li> Destroy the object using [sqlite3_finalize()].
3434 ** </ol>
3435 **
3436 ** Refer to documentation on individual methods above for additional
3437 ** information.
3438 */
3439 typedef struct sqlite3_stmt sqlite3_stmt;
3440
3441 /*
3442 ** CAPI3REF: Run-time Limits
3443 **
3444 ** ^(This interface allows the size of various constructs to be limited
3445 ** on a connection by connection basis.  The first parameter is the
3446 ** [database connection] whose limit is to be set or queried.  The
3447 ** second parameter is one of the [limit categories] that define a
3448 ** class of constructs to be size limited.  The third parameter is the
3449 ** new limit for that construct.)^
3450 **
3451 ** ^If the new limit is a negative number, the limit is unchanged.
3452 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
3453 ** [limits | hard upper bound]
3454 ** set at compile-time by a C preprocessor macro called
3455 ** [limits | SQLITE_MAX_<i>NAME</i>].
3456 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3457 ** ^Attempts to increase a limit above its hard upper bound are
3458 ** silently truncated to the hard upper bound.
3459 **
3460 ** ^Regardless of whether or not the limit was changed, the 
3461 ** [sqlite3_limit()] interface returns the prior value of the limit.
3462 ** ^Hence, to find the current value of a limit without changing it,
3463 ** simply invoke this interface with the third parameter set to -1.
3464 **
3465 ** Run-time limits are intended for use in applications that manage
3466 ** both their own internal database and also databases that are controlled
3467 ** by untrusted external sources.  An example application might be a
3468 ** web browser that has its own databases for storing history and
3469 ** separate databases controlled by JavaScript applications downloaded
3470 ** off the Internet.  The internal databases can be given the
3471 ** large, default limits.  Databases managed by external sources can
3472 ** be given much smaller limits designed to prevent a denial of service
3473 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3474 ** interface to further control untrusted SQL.  The size of the database
3475 ** created by an untrusted script can be contained using the
3476 ** [max_page_count] [PRAGMA].
3477 **
3478 ** New run-time limit categories may be added in future releases.
3479 */
3480 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3481
3482 /*
3483 ** CAPI3REF: Run-Time Limit Categories
3484 ** KEYWORDS: {limit category} {*limit categories}
3485 **
3486 ** These constants define various performance limits
3487 ** that can be lowered at run-time using [sqlite3_limit()].
3488 ** The synopsis of the meanings of the various limits is shown below.
3489 ** Additional information is available at [limits | Limits in SQLite].
3490 **
3491 ** <dl>
3492 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3493 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3494 **
3495 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3496 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3497 **
3498 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3499 ** <dd>The maximum number of columns in a table definition or in the
3500 ** result set of a [SELECT] or the maximum number of columns in an index
3501 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3502 **
3503 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3504 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3505 **
3506 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3507 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3508 **
3509 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3510 ** <dd>The maximum number of instructions in a virtual machine program
3511 ** used to implement an SQL statement.  This limit is not currently
3512 ** enforced, though that might be added in some future release of
3513 ** SQLite.</dd>)^
3514 **
3515 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3516 ** <dd>The maximum number of arguments on a function.</dd>)^
3517 **
3518 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3519 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3520 **
3521 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3522 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3523 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3524 ** [GLOB] operators.</dd>)^
3525 **
3526 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3527 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3528 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3529 **
3530 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3531 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3532 ** </dl>
3533 */
3534 #define SQLITE_LIMIT_LENGTH                    0
3535 #define SQLITE_LIMIT_SQL_LENGTH                1
3536 #define SQLITE_LIMIT_COLUMN                    2
3537 #define SQLITE_LIMIT_EXPR_DEPTH                3
3538 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3539 #define SQLITE_LIMIT_VDBE_OP                   5
3540 #define SQLITE_LIMIT_FUNCTION_ARG              6
3541 #define SQLITE_LIMIT_ATTACHED                  7
3542 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3543 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3544 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3545
3546 /*
3547 ** CAPI3REF: Compiling An SQL Statement
3548 ** KEYWORDS: {SQL statement compiler}
3549 **
3550 ** To execute an SQL query, it must first be compiled into a byte-code
3551 ** program using one of these routines.
3552 **
3553 ** The first argument, "db", is a [database connection] obtained from a
3554 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3555 ** [sqlite3_open16()].  The database connection must not have been closed.
3556 **
3557 ** The second argument, "zSql", is the statement to be compiled, encoded
3558 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3559 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3560 ** use UTF-16.
3561 **
3562 ** ^If the nByte argument is less than zero, then zSql is read up to the
3563 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3564 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3565 ** zSql string ends at either the first '\000' or '\u0000' character or
3566 ** the nByte-th byte, whichever comes first. If the caller knows
3567 ** that the supplied string is nul-terminated, then there is a small
3568 ** performance advantage to be gained by passing an nByte parameter that
3569 ** is equal to the number of bytes in the input string <i>including</i>
3570 ** the nul-terminator bytes as this saves SQLite from having to
3571 ** make a copy of the input string.
3572 **
3573 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3574 ** past the end of the first SQL statement in zSql.  These routines only
3575 ** compile the first statement in zSql, so *pzTail is left pointing to
3576 ** what remains uncompiled.
3577 **
3578 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3579 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3580 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3581 ** string or a comment) then *ppStmt is set to NULL.
3582 ** The calling procedure is responsible for deleting the compiled
3583 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3584 ** ppStmt may not be NULL.
3585 **
3586 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3587 ** otherwise an [error code] is returned.
3588 **
3589 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3590 ** recommended for all new programs. The two older interfaces are retained
3591 ** for backwards compatibility, but their use is discouraged.
3592 ** ^In the "v2" interfaces, the prepared statement
3593 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3594 ** original SQL text. This causes the [sqlite3_step()] interface to
3595 ** behave differently in three ways:
3596 **
3597 ** <ol>
3598 ** <li>
3599 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3600 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3601 ** statement and try to run it again.
3602 ** </li>
3603 **
3604 ** <li>
3605 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3606 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3607 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3608 ** and the application would have to make a second call to [sqlite3_reset()]
3609 ** in order to find the underlying cause of the problem. With the "v2" prepare
3610 ** interfaces, the underlying reason for the error is returned immediately.
3611 ** </li>
3612 **
3613 ** <li>
3614 ** ^If the specific value bound to [parameter | host parameter] in the 
3615 ** WHERE clause might influence the choice of query plan for a statement,
3616 ** then the statement will be automatically recompiled, as if there had been 
3617 ** a schema change, on the first  [sqlite3_step()] call following any change
3618 ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
3619 ** ^The specific value of WHERE-clause [parameter] might influence the 
3620 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3621 ** or [GLOB] operator or if the parameter is compared to an indexed column
3622 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3623 ** the 
3624 ** </li>
3625 ** </ol>
3626 */
3627 SQLITE_API int sqlite3_prepare(
3628   sqlite3 *db,            /* Database handle */
3629   const char *zSql,       /* SQL statement, UTF-8 encoded */
3630   int nByte,              /* Maximum length of zSql in bytes. */
3631   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3632   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3633 );
3634 SQLITE_API int sqlite3_prepare_v2(
3635   sqlite3 *db,            /* Database handle */
3636   const char *zSql,       /* SQL statement, UTF-8 encoded */
3637   int nByte,              /* Maximum length of zSql in bytes. */
3638   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3639   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3640 );
3641 SQLITE_API int sqlite3_prepare16(
3642   sqlite3 *db,            /* Database handle */
3643   const void *zSql,       /* SQL statement, UTF-16 encoded */
3644   int nByte,              /* Maximum length of zSql in bytes. */
3645   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3646   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3647 );
3648 SQLITE_API int sqlite3_prepare16_v2(
3649   sqlite3 *db,            /* Database handle */
3650   const void *zSql,       /* SQL statement, UTF-16 encoded */
3651   int nByte,              /* Maximum length of zSql in bytes. */
3652   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3653   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3654 );
3655
3656 /*
3657 ** CAPI3REF: Retrieving Statement SQL
3658 **
3659 ** ^This interface can be used to retrieve a saved copy of the original
3660 ** SQL text used to create a [prepared statement] if that statement was
3661 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3662 */
3663 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3664
3665 /*
3666 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3667 **
3668 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3669 ** and only if the [prepared statement] X makes no direct changes to
3670 ** the content of the database file.
3671 **
3672 ** Note that [application-defined SQL functions] or
3673 ** [virtual tables] might change the database indirectly as a side effect.  
3674 ** ^(For example, if an application defines a function "eval()" that 
3675 ** calls [sqlite3_exec()], then the following SQL statement would
3676 ** change the database file through side-effects:
3677 **
3678 ** <blockquote><pre>
3679 **    SELECT eval('DELETE FROM t1') FROM t2;
3680 ** </pre></blockquote>
3681 **
3682 ** But because the [SELECT] statement does not change the database file
3683 ** directly, sqlite3_stmt_readonly() would still return true.)^
3684 **
3685 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3686 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3687 ** since the statements themselves do not actually modify the database but
3688 ** rather they control the timing of when other statements modify the 
3689 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3690 ** sqlite3_stmt_readonly() to return true since, while those statements
3691 ** change the configuration of a database connection, they do not make 
3692 ** changes to the content of the database files on disk.
3693 */
3694 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3695
3696 /*
3697 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3698 **
3699 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3700 ** [prepared statement] S has been stepped at least once using 
3701 ** [sqlite3_step(S)] but has not run to completion and/or has not 
3702 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3703 ** interface returns false if S is a NULL pointer.  If S is not a 
3704 ** NULL pointer and is not a pointer to a valid [prepared statement]
3705 ** object, then the behavior is undefined and probably undesirable.
3706 **
3707 ** This interface can be used in combination [sqlite3_next_stmt()]
3708 ** to locate all prepared statements associated with a database 
3709 ** connection that are in need of being reset.  This can be used,
3710 ** for example, in diagnostic routines to search for prepared 
3711 ** statements that are holding a transaction open.
3712 */
3713 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3714
3715 /*
3716 ** CAPI3REF: Dynamically Typed Value Object
3717 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3718 **
3719 ** SQLite uses the sqlite3_value object to represent all values
3720 ** that can be stored in a database table. SQLite uses dynamic typing
3721 ** for the values it stores.  ^Values stored in sqlite3_value objects
3722 ** can be integers, floating point values, strings, BLOBs, or NULL.
3723 **
3724 ** An sqlite3_value object may be either "protected" or "unprotected".
3725 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3726 ** will accept either a protected or an unprotected sqlite3_value.
3727 ** Every interface that accepts sqlite3_value arguments specifies
3728 ** whether or not it requires a protected sqlite3_value.
3729 **
3730 ** The terms "protected" and "unprotected" refer to whether or not
3731 ** a mutex is held.  An internal mutex is held for a protected
3732 ** sqlite3_value object but no mutex is held for an unprotected
3733 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3734 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3735 ** or if SQLite is run in one of reduced mutex modes 
3736 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3737 ** then there is no distinction between protected and unprotected
3738 ** sqlite3_value objects and they can be used interchangeably.  However,
3739 ** for maximum code portability it is recommended that applications
3740 ** still make the distinction between protected and unprotected
3741 ** sqlite3_value objects even when not strictly required.
3742 **
3743 ** ^The sqlite3_value objects that are passed as parameters into the
3744 ** implementation of [application-defined SQL functions] are protected.
3745 ** ^The sqlite3_value object returned by
3746 ** [sqlite3_column_value()] is unprotected.
3747 ** Unprotected sqlite3_value objects may only be used with
3748 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3749 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3750 ** interfaces require protected sqlite3_value objects.
3751 */
3752 typedef struct Mem sqlite3_value;
3753
3754 /*
3755 ** CAPI3REF: SQL Function Context Object
3756 **
3757 ** The context in which an SQL function executes is stored in an
3758 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3759 ** is always first parameter to [application-defined SQL functions].
3760 ** The application-defined SQL function implementation will pass this
3761 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3762 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3763 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3764 ** and/or [sqlite3_set_auxdata()].
3765 */
3766 typedef struct sqlite3_context sqlite3_context;
3767
3768 /*
3769 ** CAPI3REF: Binding Values To Prepared Statements
3770 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3771 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3772 **
3773 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3774 ** literals may be replaced by a [parameter] that matches one of following
3775 ** templates:
3776 **
3777 ** <ul>
3778 ** <li>  ?
3779 ** <li>  ?NNN
3780 ** <li>  :VVV
3781 ** <li>  @VVV
3782 ** <li>  $VVV
3783 ** </ul>
3784 **
3785 ** In the templates above, NNN represents an integer literal,
3786 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3787 ** parameters (also called "host parameter names" or "SQL parameters")
3788 ** can be set using the sqlite3_bind_*() routines defined here.
3789 **
3790 ** ^The first argument to the sqlite3_bind_*() routines is always
3791 ** a pointer to the [sqlite3_stmt] object returned from
3792 ** [sqlite3_prepare_v2()] or its variants.
3793 **
3794 ** ^The second argument is the index of the SQL parameter to be set.
3795 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3796 ** SQL parameter is used more than once, second and subsequent
3797 ** occurrences have the same index as the first occurrence.
3798 ** ^The index for named parameters can be looked up using the
3799 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3800 ** for "?NNN" parameters is the value of NNN.
3801 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3802 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3803 **
3804 ** ^The third argument is the value to bind to the parameter.
3805 **
3806 ** ^(In those routines that have a fourth argument, its value is the
3807 ** number of bytes in the parameter.  To be clear: the value is the
3808 ** number of <u>bytes</u> in the value, not the number of characters.)^
3809 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3810 ** is negative, then the length of the string is
3811 ** the number of bytes up to the first zero terminator.
3812 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3813 ** the behavior is undefined.
3814 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3815 ** or sqlite3_bind_text16() then that parameter must be the byte offset
3816 ** where the NUL terminator would occur assuming the string were NUL
3817 ** terminated.  If any NUL characters occur at byte offsets less than 
3818 ** the value of the fourth parameter then the resulting string value will
3819 ** contain embedded NULs.  The result of expressions involving strings
3820 ** with embedded NULs is undefined.
3821 **
3822 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3823 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3824 ** string after SQLite has finished with it.  ^The destructor is called
3825 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3826 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  
3827 ** ^If the fifth argument is
3828 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3829 ** information is in static, unmanaged space and does not need to be freed.
3830 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3831 ** SQLite makes its own private copy of the data immediately, before
3832 ** the sqlite3_bind_*() routine returns.
3833 **
3834 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3835 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3836 ** (just an integer to hold its size) while it is being processed.
3837 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3838 ** content is later written using
3839 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3840 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3841 **
3842 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3843 ** for the [prepared statement] or with a prepared statement for which
3844 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3845 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3846 ** routine is passed a [prepared statement] that has been finalized, the
3847 ** result is undefined and probably harmful.
3848 **
3849 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3850 ** ^Unbound parameters are interpreted as NULL.
3851 **
3852 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3853 ** [error code] if anything goes wrong.
3854 ** ^[SQLITE_RANGE] is returned if the parameter
3855 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3856 **
3857 ** See also: [sqlite3_bind_parameter_count()],
3858 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3859 */
3860 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3861 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3862 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3863 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3864 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3865 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3866 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3867 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3868 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3869
3870 /*
3871 ** CAPI3REF: Number Of SQL Parameters
3872 **
3873 ** ^This routine can be used to find the number of [SQL parameters]
3874 ** in a [prepared statement].  SQL parameters are tokens of the
3875 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3876 ** placeholders for values that are [sqlite3_bind_blob | bound]
3877 ** to the parameters at a later time.
3878 **
3879 ** ^(This routine actually returns the index of the largest (rightmost)
3880 ** parameter. For all forms except ?NNN, this will correspond to the
3881 ** number of unique parameters.  If parameters of the ?NNN form are used,
3882 ** there may be gaps in the list.)^
3883 **
3884 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3885 ** [sqlite3_bind_parameter_name()], and
3886 ** [sqlite3_bind_parameter_index()].
3887 */
3888 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3889
3890 /*
3891 ** CAPI3REF: Name Of A Host Parameter
3892 **
3893 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3894 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3895 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3896 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3897 ** respectively.
3898 ** In other words, the initial ":" or "$" or "@" or "?"
3899 ** is included as part of the name.)^
3900 ** ^Parameters of the form "?" without a following integer have no name
3901 ** and are referred to as "nameless" or "anonymous parameters".
3902 **
3903 ** ^The first host parameter has an index of 1, not 0.
3904 **
3905 ** ^If the value N is out of range or if the N-th parameter is
3906 ** nameless, then NULL is returned.  ^The returned string is
3907 ** always in UTF-8 encoding even if the named parameter was
3908 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3909 ** [sqlite3_prepare16_v2()].
3910 **
3911 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3912 ** [sqlite3_bind_parameter_count()], and
3913 ** [sqlite3_bind_parameter_index()].
3914 */
3915 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3916
3917 /*
3918 ** CAPI3REF: Index Of A Parameter With A Given Name
3919 **
3920 ** ^Return the index of an SQL parameter given its name.  ^The
3921 ** index value returned is suitable for use as the second
3922 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3923 ** is returned if no matching parameter is found.  ^The parameter
3924 ** name must be given in UTF-8 even if the original statement
3925 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3926 **
3927 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3928 ** [sqlite3_bind_parameter_count()], and
3929 ** [sqlite3_bind_parameter_index()].
3930 */
3931 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3932
3933 /*
3934 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3935 **
3936 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3937 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3938 ** ^Use this routine to reset all host parameters to NULL.
3939 */
3940 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3941
3942 /*
3943 ** CAPI3REF: Number Of Columns In A Result Set
3944 **
3945 ** ^Return the number of columns in the result set returned by the
3946 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3947 ** statement that does not return data (for example an [UPDATE]).
3948 **
3949 ** See also: [sqlite3_data_count()]
3950 */
3951 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3952
3953 /*
3954 ** CAPI3REF: Column Names In A Result Set
3955 **
3956 ** ^These routines return the name assigned to a particular column
3957 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3958 ** interface returns a pointer to a zero-terminated UTF-8 string
3959 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3960 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3961 ** that implements the [SELECT] statement. ^The second parameter is the
3962 ** column number.  ^The leftmost column is number 0.
3963 **
3964 ** ^The returned string pointer is valid until either the [prepared statement]
3965 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3966 ** reprepared by the first call to [sqlite3_step()] for a particular run
3967 ** or until the next call to
3968 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3969 **
3970 ** ^If sqlite3_malloc() fails during the processing of either routine
3971 ** (for example during a conversion from UTF-8 to UTF-16) then a
3972 ** NULL pointer is returned.
3973 **
3974 ** ^The name of a result column is the value of the "AS" clause for
3975 ** that column, if there is an AS clause.  If there is no AS clause
3976 ** then the name of the column is unspecified and may change from
3977 ** one release of SQLite to the next.
3978 */
3979 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3980 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3981
3982 /*
3983 ** CAPI3REF: Source Of Data In A Query Result
3984 **
3985 ** ^These routines provide a means to determine the database, table, and
3986 ** table column that is the origin of a particular result column in
3987 ** [SELECT] statement.
3988 ** ^The name of the database or table or column can be returned as
3989 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3990 ** the database name, the _table_ routines return the table name, and
3991 ** the origin_ routines return the column name.
3992 ** ^The returned string is valid until the [prepared statement] is destroyed
3993 ** using [sqlite3_finalize()] or until the statement is automatically
3994 ** reprepared by the first call to [sqlite3_step()] for a particular run
3995 ** or until the same information is requested
3996 ** again in a different encoding.
3997 **
3998 ** ^The names returned are the original un-aliased names of the
3999 ** database, table, and column.
4000 **
4001 ** ^The first argument to these interfaces is a [prepared statement].
4002 ** ^These functions return information about the Nth result column returned by
4003 ** the statement, where N is the second function argument.
4004 ** ^The left-most column is column 0 for these routines.
4005 **
4006 ** ^If the Nth column returned by the statement is an expression or
4007 ** subquery and is not a column value, then all of these functions return
4008 ** NULL.  ^These routine might also return NULL if a memory allocation error
4009 ** occurs.  ^Otherwise, they return the name of the attached database, table,
4010 ** or column that query result column was extracted from.
4011 **
4012 ** ^As with all other SQLite APIs, those whose names end with "16" return
4013 ** UTF-16 encoded strings and the other functions return UTF-8.
4014 **
4015 ** ^These APIs are only available if the library was compiled with the
4016 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4017 **
4018 ** If two or more threads call one or more of these routines against the same
4019 ** prepared statement and column at the same time then the results are
4020 ** undefined.
4021 **
4022 ** If two or more threads call one or more
4023 ** [sqlite3_column_database_name | column metadata interfaces]
4024 ** for the same [prepared statement] and result column
4025 ** at the same time then the results are undefined.
4026 */
4027 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
4028 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
4029 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
4030 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
4031 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
4032 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
4033
4034 /*
4035 ** CAPI3REF: Declared Datatype Of A Query Result
4036 **
4037 ** ^(The first parameter is a [prepared statement].
4038 ** If this statement is a [SELECT] statement and the Nth column of the
4039 ** returned result set of that [SELECT] is a table column (not an
4040 ** expression or subquery) then the declared type of the table
4041 ** column is returned.)^  ^If the Nth column of the result set is an
4042 ** expression or subquery, then a NULL pointer is returned.
4043 ** ^The returned string is always UTF-8 encoded.
4044 **
4045 ** ^(For example, given the database schema:
4046 **
4047 ** CREATE TABLE t1(c1 VARIANT);
4048 **
4049 ** and the following statement to be compiled:
4050 **
4051 ** SELECT c1 + 1, c1 FROM t1;
4052 **
4053 ** this routine would return the string "VARIANT" for the second result
4054 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
4055 **
4056 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
4057 ** is declared to contain a particular type does not mean that the
4058 ** data stored in that column is of the declared type.  SQLite is
4059 ** strongly typed, but the typing is dynamic not static.  ^Type
4060 ** is associated with individual values, not with the containers
4061 ** used to hold those values.
4062 */
4063 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
4064 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
4065
4066 /*
4067 ** CAPI3REF: Evaluate An SQL Statement
4068 **
4069 ** After a [prepared statement] has been prepared using either
4070 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4071 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4072 ** must be called one or more times to evaluate the statement.
4073 **
4074 ** The details of the behavior of the sqlite3_step() interface depend
4075 ** on whether the statement was prepared using the newer "v2" interface
4076 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4077 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
4078 ** new "v2" interface is recommended for new applications but the legacy
4079 ** interface will continue to be supported.
4080 **
4081 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4082 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4083 ** ^With the "v2" interface, any of the other [result codes] or
4084 ** [extended result codes] might be returned as well.
4085 **
4086 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4087 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
4088 ** or occurs outside of an explicit transaction, then you can retry the
4089 ** statement.  If the statement is not a [COMMIT] and occurs within an
4090 ** explicit transaction then you should rollback the transaction before
4091 ** continuing.
4092 **
4093 ** ^[SQLITE_DONE] means that the statement has finished executing
4094 ** successfully.  sqlite3_step() should not be called again on this virtual
4095 ** machine without first calling [sqlite3_reset()] to reset the virtual
4096 ** machine back to its initial state.
4097 **
4098 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4099 ** is returned each time a new row of data is ready for processing by the
4100 ** caller. The values may be accessed using the [column access functions].
4101 ** sqlite3_step() is called again to retrieve the next row of data.
4102 **
4103 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4104 ** violation) has occurred.  sqlite3_step() should not be called again on
4105 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4106 ** ^With the legacy interface, a more specific error code (for example,
4107 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4108 ** can be obtained by calling [sqlite3_reset()] on the
4109 ** [prepared statement].  ^In the "v2" interface,
4110 ** the more specific error code is returned directly by sqlite3_step().
4111 **
4112 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4113 ** Perhaps it was called on a [prepared statement] that has
4114 ** already been [sqlite3_finalize | finalized] or on one that had
4115 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4116 ** be the case that the same database connection is being used by two or
4117 ** more threads at the same moment in time.
4118 **
4119 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4120 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4121 ** other than [SQLITE_ROW] before any subsequent invocation of
4122 ** sqlite3_step().  Failure to reset the prepared statement using 
4123 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4124 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
4125 ** calling [sqlite3_reset()] automatically in this circumstance rather
4126 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4127 ** break because any application that ever receives an SQLITE_MISUSE error
4128 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4129 ** can be used to restore the legacy behavior.
4130 **
4131 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4132 ** API always returns a generic error code, [SQLITE_ERROR], following any
4133 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4134 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4135 ** specific [error codes] that better describes the error.
4136 ** We admit that this is a goofy design.  The problem has been fixed
4137 ** with the "v2" interface.  If you prepare all of your SQL statements
4138 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4139 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4140 ** then the more specific [error codes] are returned directly
4141 ** by sqlite3_step().  The use of the "v2" interface is recommended.
4142 */
4143 SQLITE_API int sqlite3_step(sqlite3_stmt*);
4144
4145 /*
4146 ** CAPI3REF: Number of columns in a result set
4147 **
4148 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4149 ** current row of the result set of [prepared statement] P.
4150 ** ^If prepared statement P does not have results ready to return
4151 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4152 ** interfaces) then sqlite3_data_count(P) returns 0.
4153 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4154 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4155 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4156 ** will return non-zero if previous call to [sqlite3_step](P) returned
4157 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4158 ** where it always returns zero since each step of that multi-step
4159 ** pragma returns 0 columns of data.
4160 **
4161 ** See also: [sqlite3_column_count()]
4162 */
4163 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4164
4165 /*
4166 ** CAPI3REF: Fundamental Datatypes
4167 ** KEYWORDS: SQLITE_TEXT
4168 **
4169 ** ^(Every value in SQLite has one of five fundamental datatypes:
4170 **
4171 ** <ul>
4172 ** <li> 64-bit signed integer
4173 ** <li> 64-bit IEEE floating point number
4174 ** <li> string
4175 ** <li> BLOB
4176 ** <li> NULL
4177 ** </ul>)^
4178 **
4179 ** These constants are codes for each of those types.
4180 **
4181 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4182 ** for a completely different meaning.  Software that links against both
4183 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4184 ** SQLITE_TEXT.
4185 */
4186 #define SQLITE_INTEGER  1
4187 #define SQLITE_FLOAT    2
4188 #define SQLITE_BLOB     4
4189 #define SQLITE_NULL     5
4190 #ifdef SQLITE_TEXT
4191 # undef SQLITE_TEXT
4192 #else
4193 # define SQLITE_TEXT     3
4194 #endif
4195 #define SQLITE3_TEXT     3
4196
4197 /*
4198 ** CAPI3REF: Result Values From A Query
4199 ** KEYWORDS: {column access functions}
4200 **
4201 ** These routines form the "result set" interface.
4202 **
4203 ** ^These routines return information about a single column of the current
4204 ** result row of a query.  ^In every case the first argument is a pointer
4205 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4206 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4207 ** and the second argument is the index of the column for which information
4208 ** should be returned. ^The leftmost column of the result set has the index 0.
4209 ** ^The number of columns in the result can be determined using
4210 ** [sqlite3_column_count()].
4211 **
4212 ** If the SQL statement does not currently point to a valid row, or if the
4213 ** column index is out of range, the result is undefined.
4214 ** These routines may only be called when the most recent call to
4215 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4216 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4217 ** If any of these routines are called after [sqlite3_reset()] or
4218 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4219 ** something other than [SQLITE_ROW], the results are undefined.
4220 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4221 ** are called from a different thread while any of these routines
4222 ** are pending, then the results are undefined.
4223 **
4224 ** ^The sqlite3_column_type() routine returns the
4225 ** [SQLITE_INTEGER | datatype code] for the initial data type
4226 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4227 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4228 ** returned by sqlite3_column_type() is only meaningful if no type
4229 ** conversions have occurred as described below.  After a type conversion,
4230 ** the value returned by sqlite3_column_type() is undefined.  Future
4231 ** versions of SQLite may change the behavior of sqlite3_column_type()
4232 ** following a type conversion.
4233 **
4234 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4235 ** routine returns the number of bytes in that BLOB or string.
4236 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4237 ** the string to UTF-8 and then returns the number of bytes.
4238 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4239 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4240 ** the number of bytes in that string.
4241 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4242 **
4243 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4244 ** routine returns the number of bytes in that BLOB or string.
4245 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4246 ** the string to UTF-16 and then returns the number of bytes.
4247 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4248 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4249 ** the number of bytes in that string.
4250 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4251 **
4252 ** ^The values returned by [sqlite3_column_bytes()] and 
4253 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4254 ** of the string.  ^For clarity: the values returned by
4255 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4256 ** bytes in the string, not the number of characters.
4257 **
4258 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4259 ** even empty strings, are always zero-terminated.  ^The return
4260 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4261 **
4262 ** ^The object returned by [sqlite3_column_value()] is an
4263 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4264 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4265 ** If the [unprotected sqlite3_value] object returned by
4266 ** [sqlite3_column_value()] is used in any other way, including calls
4267 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4268 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4269 **
4270 ** These routines attempt to convert the value where appropriate.  ^For
4271 ** example, if the internal representation is FLOAT and a text result
4272 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4273 ** conversion automatically.  ^(The following table details the conversions
4274 ** that are applied:
4275 **
4276 ** <blockquote>
4277 ** <table border="1">
4278 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4279 **
4280 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4281 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4282 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4283 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4284 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4285 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4286 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4287 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4288 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4289 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4290 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4291 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4292 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4293 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4294 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4295 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4296 ** </table>
4297 ** </blockquote>)^
4298 **
4299 ** The table above makes reference to standard C library functions atoi()
4300 ** and atof().  SQLite does not really use these functions.  It has its
4301 ** own equivalent internal routines.  The atoi() and atof() names are
4302 ** used in the table for brevity and because they are familiar to most
4303 ** C programmers.
4304 **
4305 ** Note that when type conversions occur, pointers returned by prior
4306 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4307 ** sqlite3_column_text16() may be invalidated.
4308 ** Type conversions and pointer invalidations might occur
4309 ** in the following cases:
4310 **
4311 ** <ul>
4312 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4313 **      sqlite3_column_text16() is called.  A zero-terminator might
4314 **      need to be added to the string.</li>
4315 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4316 **      sqlite3_column_text16() is called.  The content must be converted
4317 **      to UTF-16.</li>
4318 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4319 **      sqlite3_column_text() is called.  The content must be converted
4320 **      to UTF-8.</li>
4321 ** </ul>
4322 **
4323 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4324 ** not invalidate a prior pointer, though of course the content of the buffer
4325 ** that the prior pointer references will have been modified.  Other kinds
4326 ** of conversion are done in place when it is possible, but sometimes they
4327 ** are not possible and in those cases prior pointers are invalidated.
4328 **
4329 ** The safest and easiest to remember policy is to invoke these routines
4330 ** in one of the following ways:
4331 **
4332 ** <ul>
4333 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4334 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4335 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4336 ** </ul>
4337 **
4338 ** In other words, you should call sqlite3_column_text(),
4339 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4340 ** into the desired format, then invoke sqlite3_column_bytes() or
4341 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4342 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4343 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4344 ** with calls to sqlite3_column_bytes().
4345 **
4346 ** ^The pointers returned are valid until a type conversion occurs as
4347 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4348 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4349 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4350 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4351 ** [sqlite3_free()].
4352 **
4353 ** ^(If a memory allocation error occurs during the evaluation of any
4354 ** of these routines, a default value is returned.  The default value
4355 ** is either the integer 0, the floating point number 0.0, or a NULL
4356 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4357 ** [SQLITE_NOMEM].)^
4358 */
4359 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4360 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4361 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4362 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4363 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4364 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4365 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4366 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4367 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4368 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4369
4370 /*
4371 ** CAPI3REF: Destroy A Prepared Statement Object
4372 **
4373 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4374 ** ^If the most recent evaluation of the statement encountered no errors
4375 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4376 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4377 ** sqlite3_finalize(S) returns the appropriate [error code] or
4378 ** [extended error code].
4379 **
4380 ** ^The sqlite3_finalize(S) routine can be called at any point during
4381 ** the life cycle of [prepared statement] S:
4382 ** before statement S is ever evaluated, after
4383 ** one or more calls to [sqlite3_reset()], or after any call
4384 ** to [sqlite3_step()] regardless of whether or not the statement has
4385 ** completed execution.
4386 **
4387 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4388 **
4389 ** The application must finalize every [prepared statement] in order to avoid
4390 ** resource leaks.  It is a grievous error for the application to try to use
4391 ** a prepared statement after it has been finalized.  Any use of a prepared
4392 ** statement after it has been finalized can result in undefined and
4393 ** undesirable behavior such as segfaults and heap corruption.
4394 */
4395 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4396
4397 /*
4398 ** CAPI3REF: Reset A Prepared Statement Object
4399 **
4400 ** The sqlite3_reset() function is called to reset a [prepared statement]
4401 ** object back to its initial state, ready to be re-executed.
4402 ** ^Any SQL statement variables that had values bound to them using
4403 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4404 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4405 **
4406 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4407 ** back to the beginning of its program.
4408 **
4409 ** ^If the most recent call to [sqlite3_step(S)] for the
4410 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4411 ** or if [sqlite3_step(S)] has never before been called on S,
4412 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4413 **
4414 ** ^If the most recent call to [sqlite3_step(S)] for the
4415 ** [prepared statement] S indicated an error, then
4416 ** [sqlite3_reset(S)] returns an appropriate [error code].
4417 **
4418 ** ^The [sqlite3_reset(S)] interface does not change the values
4419 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4420 */
4421 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4422
4423 /*
4424 ** CAPI3REF: Create Or Redefine SQL Functions
4425 ** KEYWORDS: {function creation routines}
4426 ** KEYWORDS: {application-defined SQL function}
4427 ** KEYWORDS: {application-defined SQL functions}
4428 **
4429 ** ^These functions (collectively known as "function creation routines")
4430 ** are used to add SQL functions or aggregates or to redefine the behavior
4431 ** of existing SQL functions or aggregates.  The only differences between
4432 ** these routines are the text encoding expected for
4433 ** the second parameter (the name of the function being created)
4434 ** and the presence or absence of a destructor callback for
4435 ** the application data pointer.
4436 **
4437 ** ^The first parameter is the [database connection] to which the SQL
4438 ** function is to be added.  ^If an application uses more than one database
4439 ** connection then application-defined SQL functions must be added
4440 ** to each database connection separately.
4441 **
4442 ** ^The second parameter is the name of the SQL function to be created or
4443 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4444 ** representation, exclusive of the zero-terminator.  ^Note that the name
4445 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
4446 ** ^Any attempt to create a function with a longer name
4447 ** will result in [SQLITE_MISUSE] being returned.
4448 **
4449 ** ^The third parameter (nArg)
4450 ** is the number of arguments that the SQL function or
4451 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4452 ** aggregate may take any number of arguments between 0 and the limit
4453 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4454 ** parameter is less than -1 or greater than 127 then the behavior is
4455 ** undefined.
4456 **
4457 ** ^The fourth parameter, eTextRep, specifies what
4458 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4459 ** its parameters.  Every SQL function implementation must be able to work
4460 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4461 ** more efficient with one encoding than another.  ^An application may
4462 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4463 ** times with the same function but with different values of eTextRep.
4464 ** ^When multiple implementations of the same function are available, SQLite
4465 ** will pick the one that involves the least amount of data conversion.
4466 ** If there is only a single implementation which does not care what text
4467 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4468 **
4469 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4470 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4471 **
4472 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4473 ** pointers to C-language functions that implement the SQL function or
4474 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4475 ** callback only; NULL pointers must be passed as the xStep and xFinal
4476 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4477 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4478 ** SQL function or aggregate, pass NULL pointers for all three function
4479 ** callbacks.
4480 **
4481 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4482 ** then it is destructor for the application data pointer. 
4483 ** The destructor is invoked when the function is deleted, either by being
4484 ** overloaded or when the database connection closes.)^
4485 ** ^The destructor is also invoked if the call to
4486 ** sqlite3_create_function_v2() fails.
4487 ** ^When the destructor callback of the tenth parameter is invoked, it
4488 ** is passed a single argument which is a copy of the application data 
4489 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4490 **
4491 ** ^It is permitted to register multiple implementations of the same
4492 ** functions with the same name but with either differing numbers of
4493 ** arguments or differing preferred text encodings.  ^SQLite will use
4494 ** the implementation that most closely matches the way in which the
4495 ** SQL function is used.  ^A function implementation with a non-negative
4496 ** nArg parameter is a better match than a function implementation with
4497 ** a negative nArg.  ^A function where the preferred text encoding
4498 ** matches the database encoding is a better
4499 ** match than a function where the encoding is different.  
4500 ** ^A function where the encoding difference is between UTF16le and UTF16be
4501 ** is a closer match than a function where the encoding difference is
4502 ** between UTF8 and UTF16.
4503 **
4504 ** ^Built-in functions may be overloaded by new application-defined functions.
4505 **
4506 ** ^An application-defined function is permitted to call other
4507 ** SQLite interfaces.  However, such calls must not
4508 ** close the database connection nor finalize or reset the prepared
4509 ** statement in which the function is running.
4510 */
4511 SQLITE_API int sqlite3_create_function(
4512   sqlite3 *db,
4513   const char *zFunctionName,
4514   int nArg,
4515   int eTextRep,
4516   void *pApp,
4517   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4518   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4519   void (*xFinal)(sqlite3_context*)
4520 );
4521 SQLITE_API int sqlite3_create_function16(
4522   sqlite3 *db,
4523   const void *zFunctionName,
4524   int nArg,
4525   int eTextRep,
4526   void *pApp,
4527   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4528   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4529   void (*xFinal)(sqlite3_context*)
4530 );
4531 SQLITE_API int sqlite3_create_function_v2(
4532   sqlite3 *db,
4533   const char *zFunctionName,
4534   int nArg,
4535   int eTextRep,
4536   void *pApp,
4537   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4538   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4539   void (*xFinal)(sqlite3_context*),
4540   void(*xDestroy)(void*)
4541 );
4542
4543 /*
4544 ** CAPI3REF: Text Encodings
4545 **
4546 ** These constant define integer codes that represent the various
4547 ** text encodings supported by SQLite.
4548 */
4549 #define SQLITE_UTF8           1
4550 #define SQLITE_UTF16LE        2
4551 #define SQLITE_UTF16BE        3
4552 #define SQLITE_UTF16          4    /* Use native byte order */
4553 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4554 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4555
4556 /*
4557 ** CAPI3REF: Deprecated Functions
4558 ** DEPRECATED
4559 **
4560 ** These functions are [deprecated].  In order to maintain
4561 ** backwards compatibility with older code, these functions continue 
4562 ** to be supported.  However, new applications should avoid
4563 ** the use of these functions.  To help encourage people to avoid
4564 ** using these functions, we are not going to tell you what they do.
4565 */
4566 #ifndef SQLITE_OMIT_DEPRECATED
4567 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4568 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4569 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4570 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4571 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4572 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4573                       void*,sqlite3_int64);
4574 #endif
4575
4576 /*
4577 ** CAPI3REF: Obtaining SQL Function Parameter Values
4578 **
4579 ** The C-language implementation of SQL functions and aggregates uses
4580 ** this set of interface routines to access the parameter values on
4581 ** the function or aggregate.
4582 **
4583 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4584 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4585 ** define callbacks that implement the SQL functions and aggregates.
4586 ** The 3rd parameter to these callbacks is an array of pointers to
4587 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4588 ** each parameter to the SQL function.  These routines are used to
4589 ** extract values from the [sqlite3_value] objects.
4590 **
4591 ** These routines work only with [protected sqlite3_value] objects.
4592 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4593 ** object results in undefined behavior.
4594 **
4595 ** ^These routines work just like the corresponding [column access functions]
4596 ** except that  these routines take a single [protected sqlite3_value] object
4597 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4598 **
4599 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4600 ** in the native byte-order of the host machine.  ^The
4601 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4602 ** extract UTF-16 strings as big-endian and little-endian respectively.
4603 **
4604 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4605 ** numeric affinity to the value.  This means that an attempt is
4606 ** made to convert the value to an integer or floating point.  If
4607 ** such a conversion is possible without loss of information (in other
4608 ** words, if the value is a string that looks like a number)
4609 ** then the conversion is performed.  Otherwise no conversion occurs.
4610 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4611 **
4612 ** Please pay particular attention to the fact that the pointer returned
4613 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4614 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4615 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4616 ** or [sqlite3_value_text16()].
4617 **
4618 ** These routines must be called from the same thread as
4619 ** the SQL function that supplied the [sqlite3_value*] parameters.
4620 */
4621 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4622 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4623 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4624 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4625 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4626 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4627 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4628 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4629 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4630 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4631 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4632 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4633
4634 /*
4635 ** CAPI3REF: Obtain Aggregate Function Context
4636 **
4637 ** Implementations of aggregate SQL functions use this
4638 ** routine to allocate memory for storing their state.
4639 **
4640 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
4641 ** for a particular aggregate function, SQLite
4642 ** allocates N of memory, zeroes out that memory, and returns a pointer
4643 ** to the new memory. ^On second and subsequent calls to
4644 ** sqlite3_aggregate_context() for the same aggregate function instance,
4645 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4646 ** called once for each invocation of the xStep callback and then one
4647 ** last time when the xFinal callback is invoked.  ^(When no rows match
4648 ** an aggregate query, the xStep() callback of the aggregate function
4649 ** implementation is never called and xFinal() is called exactly once.
4650 ** In those cases, sqlite3_aggregate_context() might be called for the
4651 ** first time from within xFinal().)^
4652 **
4653 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer 
4654 ** when first called if N is less than or equal to zero or if a memory
4655 ** allocate error occurs.
4656 **
4657 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4658 ** determined by the N parameter on first successful call.  Changing the
4659 ** value of N in subsequent call to sqlite3_aggregate_context() within
4660 ** the same aggregate function instance will not resize the memory
4661 ** allocation.)^  Within the xFinal callback, it is customary to set
4662 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no 
4663 ** pointless memory allocations occur.
4664 **
4665 ** ^SQLite automatically frees the memory allocated by 
4666 ** sqlite3_aggregate_context() when the aggregate query concludes.
4667 **
4668 ** The first parameter must be a copy of the
4669 ** [sqlite3_context | SQL function context] that is the first parameter
4670 ** to the xStep or xFinal callback routine that implements the aggregate
4671 ** function.
4672 **
4673 ** This routine must be called from the same thread in which
4674 ** the aggregate SQL function is running.
4675 */
4676 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4677
4678 /*
4679 ** CAPI3REF: User Data For Functions
4680 **
4681 ** ^The sqlite3_user_data() interface returns a copy of
4682 ** the pointer that was the pUserData parameter (the 5th parameter)
4683 ** of the [sqlite3_create_function()]
4684 ** and [sqlite3_create_function16()] routines that originally
4685 ** registered the application defined function.
4686 **
4687 ** This routine must be called from the same thread in which
4688 ** the application-defined function is running.
4689 */
4690 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4691
4692 /*
4693 ** CAPI3REF: Database Connection For Functions
4694 **
4695 ** ^The sqlite3_context_db_handle() interface returns a copy of
4696 ** the pointer to the [database connection] (the 1st parameter)
4697 ** of the [sqlite3_create_function()]
4698 ** and [sqlite3_create_function16()] routines that originally
4699 ** registered the application defined function.
4700 */
4701 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4702
4703 /*
4704 ** CAPI3REF: Function Auxiliary Data
4705 **
4706 ** The following two functions may be used by scalar SQL functions to
4707 ** associate metadata with argument values. If the same value is passed to
4708 ** multiple invocations of the same SQL function during query execution, under
4709 ** some circumstances the associated metadata may be preserved. This may
4710 ** be used, for example, to add a regular-expression matching scalar
4711 ** function. The compiled version of the regular expression is stored as
4712 ** metadata associated with the SQL value passed as the regular expression
4713 ** pattern.  The compiled regular expression can be reused on multiple
4714 ** invocations of the same function so that the original pattern string
4715 ** does not need to be recompiled on each invocation.
4716 **
4717 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4718 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4719 ** value to the application-defined function. ^If no metadata has been ever
4720 ** been set for the Nth argument of the function, or if the corresponding
4721 ** function parameter has changed since the meta-data was set,
4722 ** then sqlite3_get_auxdata() returns a NULL pointer.
4723 **
4724 ** ^The sqlite3_set_auxdata() interface saves the metadata
4725 ** pointed to by its 3rd parameter as the metadata for the N-th
4726 ** argument of the application-defined function.  Subsequent
4727 ** calls to sqlite3_get_auxdata() might return this data, if it has
4728 ** not been destroyed.
4729 ** ^If it is not NULL, SQLite will invoke the destructor
4730 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4731 ** the metadata when the corresponding function parameter changes
4732 ** or when the SQL statement completes, whichever comes first.
4733 **
4734 ** SQLite is free to call the destructor and drop metadata on any
4735 ** parameter of any function at any time.  ^The only guarantee is that
4736 ** the destructor will be called before the metadata is dropped.
4737 **
4738 ** ^(In practice, metadata is preserved between function calls for
4739 ** expressions that are constant at compile time. This includes literal
4740 ** values and [parameters].)^
4741 **
4742 ** These routines must be called from the same thread in which
4743 ** the SQL function is running.
4744 */
4745 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4746 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4747
4748
4749 /*
4750 ** CAPI3REF: Constants Defining Special Destructor Behavior
4751 **
4752 ** These are special values for the destructor that is passed in as the
4753 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4754 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4755 ** and will never change.  It does not need to be destroyed.  ^The
4756 ** SQLITE_TRANSIENT value means that the content will likely change in
4757 ** the near future and that SQLite should make its own private copy of
4758 ** the content before returning.
4759 **
4760 ** The typedef is necessary to work around problems in certain
4761 ** C++ compilers.  See ticket #2191.
4762 */
4763 typedef void (*sqlite3_destructor_type)(void*);
4764 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4765 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4766
4767 /*
4768 ** CAPI3REF: Setting The Result Of An SQL Function
4769 **
4770 ** These routines are used by the xFunc or xFinal callbacks that
4771 ** implement SQL functions and aggregates.  See
4772 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4773 ** for additional information.
4774 **
4775 ** These functions work very much like the [parameter binding] family of
4776 ** functions used to bind values to host parameters in prepared statements.
4777 ** Refer to the [SQL parameter] documentation for additional information.
4778 **
4779 ** ^The sqlite3_result_blob() interface sets the result from
4780 ** an application-defined function to be the BLOB whose content is pointed
4781 ** to by the second parameter and which is N bytes long where N is the
4782 ** third parameter.
4783 **
4784 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4785 ** the application-defined function to be a BLOB containing all zero
4786 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4787 **
4788 ** ^The sqlite3_result_double() interface sets the result from
4789 ** an application-defined function to be a floating point value specified
4790 ** by its 2nd argument.
4791 **
4792 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4793 ** cause the implemented SQL function to throw an exception.
4794 ** ^SQLite uses the string pointed to by the
4795 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4796 ** as the text of an error message.  ^SQLite interprets the error
4797 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4798 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4799 ** byte order.  ^If the third parameter to sqlite3_result_error()
4800 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4801 ** message all text up through the first zero character.
4802 ** ^If the third parameter to sqlite3_result_error() or
4803 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4804 ** bytes (not characters) from the 2nd parameter as the error message.
4805 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4806 ** routines make a private copy of the error message text before
4807 ** they return.  Hence, the calling function can deallocate or
4808 ** modify the text after they return without harm.
4809 ** ^The sqlite3_result_error_code() function changes the error code
4810 ** returned by SQLite as a result of an error in a function.  ^By default,
4811 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4812 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4813 **
4814 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4815 ** error indicating that a string or BLOB is too long to represent.
4816 **
4817 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4818 ** error indicating that a memory allocation failed.
4819 **
4820 ** ^The sqlite3_result_int() interface sets the return value
4821 ** of the application-defined function to be the 32-bit signed integer
4822 ** value given in the 2nd argument.
4823 ** ^The sqlite3_result_int64() interface sets the return value
4824 ** of the application-defined function to be the 64-bit signed integer
4825 ** value given in the 2nd argument.
4826 **
4827 ** ^The sqlite3_result_null() interface sets the return value
4828 ** of the application-defined function to be NULL.
4829 **
4830 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4831 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4832 ** set the return value of the application-defined function to be
4833 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4834 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4835 ** ^SQLite takes the text result from the application from
4836 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4837 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4838 ** is negative, then SQLite takes result text from the 2nd parameter
4839 ** through the first zero character.
4840 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4841 ** is non-negative, then as many bytes (not characters) of the text
4842 ** pointed to by the 2nd parameter are taken as the application-defined
4843 ** function result.  If the 3rd parameter is non-negative, then it
4844 ** must be the byte offset into the string where the NUL terminator would
4845 ** appear if the string where NUL terminated.  If any NUL characters occur
4846 ** in the string at a byte offset that is less than the value of the 3rd
4847 ** parameter, then the resulting string will contain embedded NULs and the
4848 ** result of expressions operating on strings with embedded NULs is undefined.
4849 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4850 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4851 ** function as the destructor on the text or BLOB result when it has
4852 ** finished using that result.
4853 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4854 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4855 ** assumes that the text or BLOB result is in constant space and does not
4856 ** copy the content of the parameter nor call a destructor on the content
4857 ** when it has finished using that result.
4858 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4859 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4860 ** then SQLite makes a copy of the result into space obtained from
4861 ** from [sqlite3_malloc()] before it returns.
4862 **
4863 ** ^The sqlite3_result_value() interface sets the result of
4864 ** the application-defined function to be a copy the
4865 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4866 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4867 ** so that the [sqlite3_value] specified in the parameter may change or
4868 ** be deallocated after sqlite3_result_value() returns without harm.
4869 ** ^A [protected sqlite3_value] object may always be used where an
4870 ** [unprotected sqlite3_value] object is required, so either
4871 ** kind of [sqlite3_value] object can be used with this interface.
4872 **
4873 ** If these routines are called from within the different thread
4874 ** than the one containing the application-defined function that received
4875 ** the [sqlite3_context] pointer, the results are undefined.
4876 */
4877 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4878 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4879 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4880 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4881 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4882 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4883 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4884 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4885 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4886 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4887 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4888 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4889 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4890 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4891 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4892 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4893
4894 /*
4895 ** CAPI3REF: Define New Collating Sequences
4896 **
4897 ** ^These functions add, remove, or modify a [collation] associated
4898 ** with the [database connection] specified as the first argument.
4899 **
4900 ** ^The name of the collation is a UTF-8 string
4901 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4902 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4903 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4904 ** considered to be the same name.
4905 **
4906 ** ^(The third argument (eTextRep) must be one of the constants:
4907 ** <ul>
4908 ** <li> [SQLITE_UTF8],
4909 ** <li> [SQLITE_UTF16LE],
4910 ** <li> [SQLITE_UTF16BE],
4911 ** <li> [SQLITE_UTF16], or
4912 ** <li> [SQLITE_UTF16_ALIGNED].
4913 ** </ul>)^
4914 ** ^The eTextRep argument determines the encoding of strings passed
4915 ** to the collating function callback, xCallback.
4916 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4917 ** force strings to be UTF16 with native byte order.
4918 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4919 ** on an even byte address.
4920 **
4921 ** ^The fourth argument, pArg, is an application data pointer that is passed
4922 ** through as the first argument to the collating function callback.
4923 **
4924 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4925 ** ^Multiple collating functions can be registered using the same name but
4926 ** with different eTextRep parameters and SQLite will use whichever
4927 ** function requires the least amount of data transformation.
4928 ** ^If the xCallback argument is NULL then the collating function is
4929 ** deleted.  ^When all collating functions having the same name are deleted,
4930 ** that collation is no longer usable.
4931 **
4932 ** ^The collating function callback is invoked with a copy of the pArg 
4933 ** application data pointer and with two strings in the encoding specified
4934 ** by the eTextRep argument.  The collating function must return an
4935 ** integer that is negative, zero, or positive
4936 ** if the first string is less than, equal to, or greater than the second,
4937 ** respectively.  A collating function must always return the same answer
4938 ** given the same inputs.  If two or more collating functions are registered
4939 ** to the same collation name (using different eTextRep values) then all
4940 ** must give an equivalent answer when invoked with equivalent strings.
4941 ** The collating function must obey the following properties for all
4942 ** strings A, B, and C:
4943 **
4944 ** <ol>
4945 ** <li> If A==B then B==A.
4946 ** <li> If A==B and B==C then A==C.
4947 ** <li> If A&lt;B THEN B&gt;A.
4948 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4949 ** </ol>
4950 **
4951 ** If a collating function fails any of the above constraints and that
4952 ** collating function is  registered and used, then the behavior of SQLite
4953 ** is undefined.
4954 **
4955 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4956 ** with the addition that the xDestroy callback is invoked on pArg when
4957 ** the collating function is deleted.
4958 ** ^Collating functions are deleted when they are overridden by later
4959 ** calls to the collation creation functions or when the
4960 ** [database connection] is closed using [sqlite3_close()].
4961 **
4962 ** ^The xDestroy callback is <u>not</u> called if the 
4963 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4964 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
4965 ** check the return code and dispose of the application data pointer
4966 ** themselves rather than expecting SQLite to deal with it for them.
4967 ** This is different from every other SQLite interface.  The inconsistency 
4968 ** is unfortunate but cannot be changed without breaking backwards 
4969 ** compatibility.
4970 **
4971 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4972 */
4973 SQLITE_API int sqlite3_create_collation(
4974   sqlite3*, 
4975   const char *zName, 
4976   int eTextRep, 
4977   void *pArg,
4978   int(*xCompare)(void*,int,const void*,int,const void*)
4979 );
4980 SQLITE_API int sqlite3_create_collation_v2(
4981   sqlite3*, 
4982   const char *zName, 
4983   int eTextRep, 
4984   void *pArg,
4985   int(*xCompare)(void*,int,const void*,int,const void*),
4986   void(*xDestroy)(void*)
4987 );
4988 SQLITE_API int sqlite3_create_collation16(
4989   sqlite3*, 
4990   const void *zName,
4991   int eTextRep, 
4992   void *pArg,
4993   int(*xCompare)(void*,int,const void*,int,const void*)
4994 );
4995
4996 /*
4997 ** CAPI3REF: Collation Needed Callbacks
4998 **
4999 ** ^To avoid having to register all collation sequences before a database
5000 ** can be used, a single callback function may be registered with the
5001 ** [database connection] to be invoked whenever an undefined collation
5002 ** sequence is required.
5003 **
5004 ** ^If the function is registered using the sqlite3_collation_needed() API,
5005 ** then it is passed the names of undefined collation sequences as strings
5006 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5007 ** the names are passed as UTF-16 in machine native byte order.
5008 ** ^A call to either function replaces the existing collation-needed callback.
5009 **
5010 ** ^(When the callback is invoked, the first argument passed is a copy
5011 ** of the second argument to sqlite3_collation_needed() or
5012 ** sqlite3_collation_needed16().  The second argument is the database
5013 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5014 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5015 ** sequence function required.  The fourth parameter is the name of the
5016 ** required collation sequence.)^
5017 **
5018 ** The callback function should register the desired collation using
5019 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5020 ** [sqlite3_create_collation_v2()].
5021 */
5022 SQLITE_API int sqlite3_collation_needed(
5023   sqlite3*, 
5024   void*, 
5025   void(*)(void*,sqlite3*,int eTextRep,const char*)
5026 );
5027 SQLITE_API int sqlite3_collation_needed16(
5028   sqlite3*, 
5029   void*,
5030   void(*)(void*,sqlite3*,int eTextRep,const void*)
5031 );
5032
5033 #ifdef SQLITE_HAS_CODEC
5034 /*
5035 ** Specify the key for an encrypted database.  This routine should be
5036 ** called right after sqlite3_open().
5037 **
5038 ** The code to implement this API is not available in the public release
5039 ** of SQLite.
5040 */
5041 SQLITE_API int sqlite3_key(
5042   sqlite3 *db,                   /* Database to be rekeyed */
5043   const void *pKey, int nKey     /* The key */
5044 );
5045
5046 /*
5047 ** Change the key on an open database.  If the current database is not
5048 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5049 ** database is decrypted.
5050 **
5051 ** The code to implement this API is not available in the public release
5052 ** of SQLite.
5053 */
5054 SQLITE_API int sqlite3_rekey(
5055   sqlite3 *db,                   /* Database to be rekeyed */
5056   const void *pKey, int nKey     /* The new key */
5057 );
5058
5059 /*
5060 ** Specify the activation key for a SEE database.  Unless 
5061 ** activated, none of the SEE routines will work.
5062 */
5063 SQLITE_API void sqlite3_activate_see(
5064   const char *zPassPhrase        /* Activation phrase */
5065 );
5066 #endif
5067
5068 #ifdef SQLITE_ENABLE_CEROD
5069 /*
5070 ** Specify the activation key for a CEROD database.  Unless 
5071 ** activated, none of the CEROD routines will work.
5072 */
5073 SQLITE_API void sqlite3_activate_cerod(
5074   const char *zPassPhrase        /* Activation phrase */
5075 );
5076 #endif
5077
5078 /*
5079 ** CAPI3REF: Suspend Execution For A Short Time
5080 **
5081 ** The sqlite3_sleep() function causes the current thread to suspend execution
5082 ** for at least a number of milliseconds specified in its parameter.
5083 **
5084 ** If the operating system does not support sleep requests with
5085 ** millisecond time resolution, then the time will be rounded up to
5086 ** the nearest second. The number of milliseconds of sleep actually
5087 ** requested from the operating system is returned.
5088 **
5089 ** ^SQLite implements this interface by calling the xSleep()
5090 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
5091 ** of the default VFS is not implemented correctly, or not implemented at
5092 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5093 ** in the previous paragraphs.
5094 */
5095 SQLITE_API int sqlite3_sleep(int);
5096
5097 /*
5098 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5099 **
5100 ** ^(If this global variable is made to point to a string which is
5101 ** the name of a folder (a.k.a. directory), then all temporary files
5102 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5103 ** will be placed in that directory.)^  ^If this variable
5104 ** is a NULL pointer, then SQLite performs a search for an appropriate
5105 ** temporary file directory.
5106 **
5107 ** It is not safe to read or modify this variable in more than one
5108 ** thread at a time.  It is not safe to read or modify this variable
5109 ** if a [database connection] is being used at the same time in a separate
5110 ** thread.
5111 ** It is intended that this variable be set once
5112 ** as part of process initialization and before any SQLite interface
5113 ** routines have been called and that this variable remain unchanged
5114 ** thereafter.
5115 **
5116 ** ^The [temp_store_directory pragma] may modify this variable and cause
5117 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5118 ** the [temp_store_directory pragma] always assumes that any string
5119 ** that this variable points to is held in memory obtained from 
5120 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5121 ** using [sqlite3_free].
5122 ** Hence, if this variable is modified directly, either it should be
5123 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5124 ** or else the use of the [temp_store_directory pragma] should be avoided.
5125 **
5126 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
5127 ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
5128 ** features that require the use of temporary files may fail.  Here is an
5129 ** example of how to do this using C++ with the Windows Runtime:
5130 **
5131 ** <blockquote><pre>
5132 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5133 ** &nbsp;     TemporaryFolder->Path->Data();
5134 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
5135 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5136 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5137 ** &nbsp;     NULL, NULL);
5138 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5139 ** </pre></blockquote>
5140 */
5141 SQLITE_API char *sqlite3_temp_directory;
5142
5143 /*
5144 ** CAPI3REF: Name Of The Folder Holding Database Files
5145 **
5146 ** ^(If this global variable is made to point to a string which is
5147 ** the name of a folder (a.k.a. directory), then all database files
5148 ** specified with a relative pathname and created or accessed by
5149 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5150 ** to be relative to that directory.)^ ^If this variable is a NULL
5151 ** pointer, then SQLite assumes that all database files specified
5152 ** with a relative pathname are relative to the current directory
5153 ** for the process.  Only the windows VFS makes use of this global
5154 ** variable; it is ignored by the unix VFS.
5155 **
5156 ** Changing the value of this variable while a database connection is
5157 ** open can result in a corrupt database.
5158 **
5159 ** It is not safe to read or modify this variable in more than one
5160 ** thread at a time.  It is not safe to read or modify this variable
5161 ** if a [database connection] is being used at the same time in a separate
5162 ** thread.
5163 ** It is intended that this variable be set once
5164 ** as part of process initialization and before any SQLite interface
5165 ** routines have been called and that this variable remain unchanged
5166 ** thereafter.
5167 **
5168 ** ^The [data_store_directory pragma] may modify this variable and cause
5169 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5170 ** the [data_store_directory pragma] always assumes that any string
5171 ** that this variable points to is held in memory obtained from 
5172 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5173 ** using [sqlite3_free].
5174 ** Hence, if this variable is modified directly, either it should be
5175 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5176 ** or else the use of the [data_store_directory pragma] should be avoided.
5177 */
5178 SQLITE_API char *sqlite3_data_directory;
5179
5180 /*
5181 ** CAPI3REF: Test For Auto-Commit Mode
5182 ** KEYWORDS: {autocommit mode}
5183 **
5184 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5185 ** zero if the given database connection is or is not in autocommit mode,
5186 ** respectively.  ^Autocommit mode is on by default.
5187 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5188 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5189 **
5190 ** If certain kinds of errors occur on a statement within a multi-statement
5191 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5192 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5193 ** transaction might be rolled back automatically.  The only way to
5194 ** find out whether SQLite automatically rolled back the transaction after
5195 ** an error is to use this function.
5196 **
5197 ** If another thread changes the autocommit status of the database
5198 ** connection while this routine is running, then the return value
5199 ** is undefined.
5200 */
5201 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5202
5203 /*
5204 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5205 **
5206 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5207 ** to which a [prepared statement] belongs.  ^The [database connection]
5208 ** returned by sqlite3_db_handle is the same [database connection]
5209 ** that was the first argument
5210 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5211 ** create the statement in the first place.
5212 */
5213 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5214
5215 /*
5216 ** CAPI3REF: Return The Filename For A Database Connection
5217 **
5218 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5219 ** associated with database N of connection D.  ^The main database file
5220 ** has the name "main".  If there is no attached database N on the database
5221 ** connection D, or if database N is a temporary or in-memory database, then
5222 ** a NULL pointer is returned.
5223 **
5224 ** ^The filename returned by this function is the output of the
5225 ** xFullPathname method of the [VFS].  ^In other words, the filename
5226 ** will be an absolute pathname, even if the filename used
5227 ** to open the database originally was a URI or relative pathname.
5228 */
5229 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5230
5231 /*
5232 ** CAPI3REF: Determine if a database is read-only
5233 **
5234 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5235 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5236 ** the name of a database on connection D.
5237 */
5238 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5239
5240 /*
5241 ** CAPI3REF: Find the next prepared statement
5242 **
5243 ** ^This interface returns a pointer to the next [prepared statement] after
5244 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5245 ** then this interface returns a pointer to the first prepared statement
5246 ** associated with the database connection pDb.  ^If no prepared statement
5247 ** satisfies the conditions of this routine, it returns NULL.
5248 **
5249 ** The [database connection] pointer D in a call to
5250 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5251 ** connection and in particular must not be a NULL pointer.
5252 */
5253 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5254
5255 /*
5256 ** CAPI3REF: Commit And Rollback Notification Callbacks
5257 **
5258 ** ^The sqlite3_commit_hook() interface registers a callback
5259 ** function to be invoked whenever a transaction is [COMMIT | committed].
5260 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5261 ** for the same database connection is overridden.
5262 ** ^The sqlite3_rollback_hook() interface registers a callback
5263 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5264 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5265 ** for the same database connection is overridden.
5266 ** ^The pArg argument is passed through to the callback.
5267 ** ^If the callback on a commit hook function returns non-zero,
5268 ** then the commit is converted into a rollback.
5269 **
5270 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5271 ** return the P argument from the previous call of the same function
5272 ** on the same [database connection] D, or NULL for
5273 ** the first call for each function on D.
5274 **
5275 ** The commit and rollback hook callbacks are not reentrant.
5276 ** The callback implementation must not do anything that will modify
5277 ** the database connection that invoked the callback.  Any actions
5278 ** to modify the database connection must be deferred until after the
5279 ** completion of the [sqlite3_step()] call that triggered the commit
5280 ** or rollback hook in the first place.
5281 ** Note that running any other SQL statements, including SELECT statements,
5282 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5283 ** the database connections for the meaning of "modify" in this paragraph.
5284 **
5285 ** ^Registering a NULL function disables the callback.
5286 **
5287 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5288 ** operation is allowed to continue normally.  ^If the commit hook
5289 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5290 ** ^The rollback hook is invoked on a rollback that results from a commit
5291 ** hook returning non-zero, just as it would be with any other rollback.
5292 **
5293 ** ^For the purposes of this API, a transaction is said to have been
5294 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5295 ** an error or constraint causes an implicit rollback to occur.
5296 ** ^The rollback callback is not invoked if a transaction is
5297 ** automatically rolled back because the database connection is closed.
5298 **
5299 ** See also the [sqlite3_update_hook()] interface.
5300 */
5301 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5302 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5303
5304 /*
5305 ** CAPI3REF: Data Change Notification Callbacks
5306 **
5307 ** ^The sqlite3_update_hook() interface registers a callback function
5308 ** with the [database connection] identified by the first argument
5309 ** to be invoked whenever a row is updated, inserted or deleted.
5310 ** ^Any callback set by a previous call to this function
5311 ** for the same database connection is overridden.
5312 **
5313 ** ^The second argument is a pointer to the function to invoke when a
5314 ** row is updated, inserted or deleted.
5315 ** ^The first argument to the callback is a copy of the third argument
5316 ** to sqlite3_update_hook().
5317 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5318 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5319 ** to be invoked.
5320 ** ^The third and fourth arguments to the callback contain pointers to the
5321 ** database and table name containing the affected row.
5322 ** ^The final callback parameter is the [rowid] of the row.
5323 ** ^In the case of an update, this is the [rowid] after the update takes place.
5324 **
5325 ** ^(The update hook is not invoked when internal system tables are
5326 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5327 **
5328 ** ^In the current implementation, the update hook
5329 ** is not invoked when duplication rows are deleted because of an
5330 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5331 ** invoked when rows are deleted using the [truncate optimization].
5332 ** The exceptions defined in this paragraph might change in a future
5333 ** release of SQLite.
5334 **
5335 ** The update hook implementation must not do anything that will modify
5336 ** the database connection that invoked the update hook.  Any actions
5337 ** to modify the database connection must be deferred until after the
5338 ** completion of the [sqlite3_step()] call that triggered the update hook.
5339 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5340 ** database connections for the meaning of "modify" in this paragraph.
5341 **
5342 ** ^The sqlite3_update_hook(D,C,P) function
5343 ** returns the P argument from the previous call
5344 ** on the same [database connection] D, or NULL for
5345 ** the first call on D.
5346 **
5347 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5348 ** interfaces.
5349 */
5350 SQLITE_API void *sqlite3_update_hook(
5351   sqlite3*, 
5352   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5353   void*
5354 );
5355
5356 /*
5357 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5358 **
5359 ** ^(This routine enables or disables the sharing of the database cache
5360 ** and schema data structures between [database connection | connections]
5361 ** to the same database. Sharing is enabled if the argument is true
5362 ** and disabled if the argument is false.)^
5363 **
5364 ** ^Cache sharing is enabled and disabled for an entire process.
5365 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5366 ** sharing was enabled or disabled for each thread separately.
5367 **
5368 ** ^(The cache sharing mode set by this interface effects all subsequent
5369 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5370 ** Existing database connections continue use the sharing mode
5371 ** that was in effect at the time they were opened.)^
5372 **
5373 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5374 ** successfully.  An [error code] is returned otherwise.)^
5375 **
5376 ** ^Shared cache is disabled by default. But this might change in
5377 ** future releases of SQLite.  Applications that care about shared
5378 ** cache setting should set it explicitly.
5379 **
5380 ** This interface is threadsafe on processors where writing a
5381 ** 32-bit integer is atomic.
5382 **
5383 ** See Also:  [SQLite Shared-Cache Mode]
5384 */
5385 SQLITE_API int sqlite3_enable_shared_cache(int);
5386
5387 /*
5388 ** CAPI3REF: Attempt To Free Heap Memory
5389 **
5390 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5391 ** of heap memory by deallocating non-essential memory allocations
5392 ** held by the database library.   Memory used to cache database
5393 ** pages to improve performance is an example of non-essential memory.
5394 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5395 ** which might be more or less than the amount requested.
5396 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5397 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5398 **
5399 ** See also: [sqlite3_db_release_memory()]
5400 */
5401 SQLITE_API int sqlite3_release_memory(int);
5402
5403 /*
5404 ** CAPI3REF: Free Memory Used By A Database Connection
5405 **
5406 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5407 ** memory as possible from database connection D. Unlike the
5408 ** [sqlite3_release_memory()] interface, this interface is effect even
5409 ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5410 ** omitted.
5411 **
5412 ** See also: [sqlite3_release_memory()]
5413 */
5414 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5415
5416 /*
5417 ** CAPI3REF: Impose A Limit On Heap Size
5418 **
5419 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5420 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5421 ** ^SQLite strives to keep heap memory utilization below the soft heap
5422 ** limit by reducing the number of pages held in the page cache
5423 ** as heap memory usages approaches the limit.
5424 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5425 ** below the limit, it will exceed the limit rather than generate
5426 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
5427 ** is advisory only.
5428 **
5429 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5430 ** the soft heap limit prior to the call, or negative in the case of an
5431 ** error.  ^If the argument N is negative
5432 ** then no change is made to the soft heap limit.  Hence, the current
5433 ** size of the soft heap limit can be determined by invoking
5434 ** sqlite3_soft_heap_limit64() with a negative argument.
5435 **
5436 ** ^If the argument N is zero then the soft heap limit is disabled.
5437 **
5438 ** ^(The soft heap limit is not enforced in the current implementation
5439 ** if one or more of following conditions are true:
5440 **
5441 ** <ul>
5442 ** <li> The soft heap limit is set to zero.
5443 ** <li> Memory accounting is disabled using a combination of the
5444 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5445 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5446 ** <li> An alternative page cache implementation is specified using
5447 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5448 ** <li> The page cache allocates from its own memory pool supplied
5449 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5450 **      from the heap.
5451 ** </ul>)^
5452 **
5453 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5454 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5455 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5456 ** the soft heap limit is enforced on every memory allocation.  Without
5457 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5458 ** when memory is allocated by the page cache.  Testing suggests that because
5459 ** the page cache is the predominate memory user in SQLite, most
5460 ** applications will achieve adequate soft heap limit enforcement without
5461 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5462 **
5463 ** The circumstances under which SQLite will enforce the soft heap limit may
5464 ** changes in future releases of SQLite.
5465 */
5466 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5467
5468 /*
5469 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5470 ** DEPRECATED
5471 **
5472 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5473 ** interface.  This routine is provided for historical compatibility
5474 ** only.  All new applications should use the
5475 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5476 */
5477 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5478
5479
5480 /*
5481 ** CAPI3REF: Extract Metadata About A Column Of A Table
5482 **
5483 ** ^This routine returns metadata about a specific column of a specific
5484 ** database table accessible using the [database connection] handle
5485 ** passed as the first function argument.
5486 **
5487 ** ^The column is identified by the second, third and fourth parameters to
5488 ** this function. ^The second parameter is either the name of the database
5489 ** (i.e. "main", "temp", or an attached database) containing the specified
5490 ** table or NULL. ^If it is NULL, then all attached databases are searched
5491 ** for the table using the same algorithm used by the database engine to
5492 ** resolve unqualified table references.
5493 **
5494 ** ^The third and fourth parameters to this function are the table and column
5495 ** name of the desired column, respectively. Neither of these parameters
5496 ** may be NULL.
5497 **
5498 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5499 ** and subsequent parameters to this function. ^Any of these arguments may be
5500 ** NULL, in which case the corresponding element of metadata is omitted.
5501 **
5502 ** ^(<blockquote>
5503 ** <table border="1">
5504 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5505 **
5506 ** <tr><td> 5th <td> const char* <td> Data type
5507 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5508 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5509 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5510 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5511 ** </table>
5512 ** </blockquote>)^
5513 **
5514 ** ^The memory pointed to by the character pointers returned for the
5515 ** declaration type and collation sequence is valid only until the next
5516 ** call to any SQLite API function.
5517 **
5518 ** ^If the specified table is actually a view, an [error code] is returned.
5519 **
5520 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5521 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5522 ** parameters are set for the explicitly declared column. ^(If there is no
5523 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5524 ** parameters are set as follows:
5525 **
5526 ** <pre>
5527 **     data type: "INTEGER"
5528 **     collation sequence: "BINARY"
5529 **     not null: 0
5530 **     primary key: 1
5531 **     auto increment: 0
5532 ** </pre>)^
5533 **
5534 ** ^(This function may load one or more schemas from database files. If an
5535 ** error occurs during this process, or if the requested table or column
5536 ** cannot be found, an [error code] is returned and an error message left
5537 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5538 **
5539 ** ^This API is only available if the library was compiled with the
5540 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5541 */
5542 SQLITE_API int sqlite3_table_column_metadata(
5543   sqlite3 *db,                /* Connection handle */
5544   const char *zDbName,        /* Database name or NULL */
5545   const char *zTableName,     /* Table name */
5546   const char *zColumnName,    /* Column name */
5547   char const **pzDataType,    /* OUTPUT: Declared data type */
5548   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5549   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5550   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5551   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5552 );
5553
5554 /*
5555 ** CAPI3REF: Load An Extension
5556 **
5557 ** ^This interface loads an SQLite extension library from the named file.
5558 **
5559 ** ^The sqlite3_load_extension() interface attempts to load an
5560 ** SQLite extension library contained in the file zFile.
5561 **
5562 ** ^The entry point is zProc.
5563 ** ^zProc may be 0, in which case the name of the entry point
5564 ** defaults to "sqlite3_extension_init".
5565 ** ^The sqlite3_load_extension() interface returns
5566 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5567 ** ^If an error occurs and pzErrMsg is not 0, then the
5568 ** [sqlite3_load_extension()] interface shall attempt to
5569 ** fill *pzErrMsg with error message text stored in memory
5570 ** obtained from [sqlite3_malloc()]. The calling function
5571 ** should free this memory by calling [sqlite3_free()].
5572 **
5573 ** ^Extension loading must be enabled using
5574 ** [sqlite3_enable_load_extension()] prior to calling this API,
5575 ** otherwise an error will be returned.
5576 **
5577 ** See also the [load_extension() SQL function].
5578 */
5579 SQLITE_API int sqlite3_load_extension(
5580   sqlite3 *db,          /* Load the extension into this database connection */
5581   const char *zFile,    /* Name of the shared library containing extension */
5582   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5583   char **pzErrMsg       /* Put error message here if not 0 */
5584 );
5585
5586 /*
5587 ** CAPI3REF: Enable Or Disable Extension Loading
5588 **
5589 ** ^So as not to open security holes in older applications that are
5590 ** unprepared to deal with extension loading, and as a means of disabling
5591 ** extension loading while evaluating user-entered SQL, the following API
5592 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5593 **
5594 ** ^Extension loading is off by default. See ticket #1863.
5595 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5596 ** to turn extension loading on and call it with onoff==0 to turn
5597 ** it back off again.
5598 */
5599 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5600
5601 /*
5602 ** CAPI3REF: Automatically Load Statically Linked Extensions
5603 **
5604 ** ^This interface causes the xEntryPoint() function to be invoked for
5605 ** each new [database connection] that is created.  The idea here is that
5606 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5607 ** that is to be automatically loaded into all new database connections.
5608 **
5609 ** ^(Even though the function prototype shows that xEntryPoint() takes
5610 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5611 ** arguments and expects and integer result as if the signature of the
5612 ** entry point where as follows:
5613 **
5614 ** <blockquote><pre>
5615 ** &nbsp;  int xEntryPoint(
5616 ** &nbsp;    sqlite3 *db,
5617 ** &nbsp;    const char **pzErrMsg,
5618 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5619 ** &nbsp;  );
5620 ** </pre></blockquote>)^
5621 **
5622 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5623 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5624 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5625 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5626 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5627 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5628 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5629 **
5630 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5631 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5632 ** will be called more than once for each database connection that is opened.
5633 **
5634 ** See also: [sqlite3_reset_auto_extension()].
5635 */
5636 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5637
5638 /*
5639 ** CAPI3REF: Reset Automatic Extension Loading
5640 **
5641 ** ^This interface disables all automatic extensions previously
5642 ** registered using [sqlite3_auto_extension()].
5643 */
5644 SQLITE_API void sqlite3_reset_auto_extension(void);
5645
5646 /*
5647 ** The interface to the virtual-table mechanism is currently considered
5648 ** to be experimental.  The interface might change in incompatible ways.
5649 ** If this is a problem for you, do not use the interface at this time.
5650 **
5651 ** When the virtual-table mechanism stabilizes, we will declare the
5652 ** interface fixed, support it indefinitely, and remove this comment.
5653 */
5654
5655 /*
5656 ** Structures used by the virtual table interface
5657 */
5658 typedef struct sqlite3_vtab sqlite3_vtab;
5659 typedef struct sqlite3_index_info sqlite3_index_info;
5660 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5661 typedef struct sqlite3_module sqlite3_module;
5662
5663 /*
5664 ** CAPI3REF: Virtual Table Object
5665 ** KEYWORDS: sqlite3_module {virtual table module}
5666 **
5667 ** This structure, sometimes called a "virtual table module", 
5668 ** defines the implementation of a [virtual tables].  
5669 ** This structure consists mostly of methods for the module.
5670 **
5671 ** ^A virtual table module is created by filling in a persistent
5672 ** instance of this structure and passing a pointer to that instance
5673 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5674 ** ^The registration remains valid until it is replaced by a different
5675 ** module or until the [database connection] closes.  The content
5676 ** of this structure must not change while it is registered with
5677 ** any database connection.
5678 */
5679 struct sqlite3_module {
5680   int iVersion;
5681   int (*xCreate)(sqlite3*, void *pAux,
5682                int argc, const char *const*argv,
5683                sqlite3_vtab **ppVTab, char**);
5684   int (*xConnect)(sqlite3*, void *pAux,
5685                int argc, const char *const*argv,
5686                sqlite3_vtab **ppVTab, char**);
5687   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5688   int (*xDisconnect)(sqlite3_vtab *pVTab);
5689   int (*xDestroy)(sqlite3_vtab *pVTab);
5690   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5691   int (*xClose)(sqlite3_vtab_cursor*);
5692   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5693                 int argc, sqlite3_value **argv);
5694   int (*xNext)(sqlite3_vtab_cursor*);
5695   int (*xEof)(sqlite3_vtab_cursor*);
5696   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5697   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5698   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5699   int (*xBegin)(sqlite3_vtab *pVTab);
5700   int (*xSync)(sqlite3_vtab *pVTab);
5701   int (*xCommit)(sqlite3_vtab *pVTab);
5702   int (*xRollback)(sqlite3_vtab *pVTab);
5703   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5704                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5705                        void **ppArg);
5706   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5707   /* The methods above are in version 1 of the sqlite_module object. Those 
5708   ** below are for version 2 and greater. */
5709   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5710   int (*xRelease)(sqlite3_vtab *pVTab, int);
5711   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5712 };
5713
5714 /*
5715 ** CAPI3REF: Virtual Table Indexing Information
5716 ** KEYWORDS: sqlite3_index_info
5717 **
5718 ** The sqlite3_index_info structure and its substructures is used as part
5719 ** of the [virtual table] interface to
5720 ** pass information into and receive the reply from the [xBestIndex]
5721 ** method of a [virtual table module].  The fields under **Inputs** are the
5722 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5723 ** results into the **Outputs** fields.
5724 **
5725 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5726 **
5727 ** <blockquote>column OP expr</blockquote>
5728 **
5729 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5730 ** stored in aConstraint[].op using one of the
5731 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5732 ** ^(The index of the column is stored in
5733 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5734 ** expr on the right-hand side can be evaluated (and thus the constraint
5735 ** is usable) and false if it cannot.)^
5736 **
5737 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5738 ** and makes other simplifications to the WHERE clause in an attempt to
5739 ** get as many WHERE clause terms into the form shown above as possible.
5740 ** ^The aConstraint[] array only reports WHERE clause terms that are
5741 ** relevant to the particular virtual table being queried.
5742 **
5743 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5744 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5745 **
5746 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5747 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5748 ** the right-hand side of the corresponding aConstraint[] is evaluated
5749 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5750 ** is true, then the constraint is assumed to be fully handled by the
5751 ** virtual table and is not checked again by SQLite.)^
5752 **
5753 ** ^The idxNum and idxPtr values are recorded and passed into the
5754 ** [xFilter] method.
5755 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5756 ** needToFreeIdxPtr is true.
5757 **
5758 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5759 ** the correct order to satisfy the ORDER BY clause so that no separate
5760 ** sorting step is required.
5761 **
5762 ** ^The estimatedCost value is an estimate of the cost of doing the
5763 ** particular lookup.  A full scan of a table with N entries should have
5764 ** a cost of N.  A binary search of a table of N entries should have a
5765 ** cost of approximately log(N).
5766 */
5767 struct sqlite3_index_info {
5768   /* Inputs */
5769   int nConstraint;           /* Number of entries in aConstraint */
5770   struct sqlite3_index_constraint {
5771      int iColumn;              /* Column on left-hand side of constraint */
5772      unsigned char op;         /* Constraint operator */
5773      unsigned char usable;     /* True if this constraint is usable */
5774      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5775   } *aConstraint;            /* Table of WHERE clause constraints */
5776   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5777   struct sqlite3_index_orderby {
5778      int iColumn;              /* Column number */
5779      unsigned char desc;       /* True for DESC.  False for ASC. */
5780   } *aOrderBy;               /* The ORDER BY clause */
5781   /* Outputs */
5782   struct sqlite3_index_constraint_usage {
5783     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5784     unsigned char omit;      /* Do not code a test for this constraint */
5785   } *aConstraintUsage;
5786   int idxNum;                /* Number used to identify the index */
5787   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5788   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5789   int orderByConsumed;       /* True if output is already ordered */
5790   double estimatedCost;      /* Estimated cost of using this index */
5791 };
5792
5793 /*
5794 ** CAPI3REF: Virtual Table Constraint Operator Codes
5795 **
5796 ** These macros defined the allowed values for the
5797 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5798 ** an operator that is part of a constraint term in the wHERE clause of
5799 ** a query that uses a [virtual table].
5800 */
5801 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5802 #define SQLITE_INDEX_CONSTRAINT_GT    4
5803 #define SQLITE_INDEX_CONSTRAINT_LE    8
5804 #define SQLITE_INDEX_CONSTRAINT_LT    16
5805 #define SQLITE_INDEX_CONSTRAINT_GE    32
5806 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5807
5808 /*
5809 ** CAPI3REF: Register A Virtual Table Implementation
5810 **
5811 ** ^These routines are used to register a new [virtual table module] name.
5812 ** ^Module names must be registered before
5813 ** creating a new [virtual table] using the module and before using a
5814 ** preexisting [virtual table] for the module.
5815 **
5816 ** ^The module name is registered on the [database connection] specified
5817 ** by the first parameter.  ^The name of the module is given by the 
5818 ** second parameter.  ^The third parameter is a pointer to
5819 ** the implementation of the [virtual table module].   ^The fourth
5820 ** parameter is an arbitrary client data pointer that is passed through
5821 ** into the [xCreate] and [xConnect] methods of the virtual table module
5822 ** when a new virtual table is be being created or reinitialized.
5823 **
5824 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5825 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5826 ** invoke the destructor function (if it is not NULL) when SQLite
5827 ** no longer needs the pClientData pointer.  ^The destructor will also
5828 ** be invoked if the call to sqlite3_create_module_v2() fails.
5829 ** ^The sqlite3_create_module()
5830 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5831 ** destructor.
5832 */
5833 SQLITE_API int sqlite3_create_module(
5834   sqlite3 *db,               /* SQLite connection to register module with */
5835   const char *zName,         /* Name of the module */
5836   const sqlite3_module *p,   /* Methods for the module */
5837   void *pClientData          /* Client data for xCreate/xConnect */
5838 );
5839 SQLITE_API int sqlite3_create_module_v2(
5840   sqlite3 *db,               /* SQLite connection to register module with */
5841   const char *zName,         /* Name of the module */
5842   const sqlite3_module *p,   /* Methods for the module */
5843   void *pClientData,         /* Client data for xCreate/xConnect */
5844   void(*xDestroy)(void*)     /* Module destructor function */
5845 );
5846
5847 /*
5848 ** CAPI3REF: Virtual Table Instance Object
5849 ** KEYWORDS: sqlite3_vtab
5850 **
5851 ** Every [virtual table module] implementation uses a subclass
5852 ** of this object to describe a particular instance
5853 ** of the [virtual table].  Each subclass will
5854 ** be tailored to the specific needs of the module implementation.
5855 ** The purpose of this superclass is to define certain fields that are
5856 ** common to all module implementations.
5857 **
5858 ** ^Virtual tables methods can set an error message by assigning a
5859 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5860 ** take care that any prior string is freed by a call to [sqlite3_free()]
5861 ** prior to assigning a new string to zErrMsg.  ^After the error message
5862 ** is delivered up to the client application, the string will be automatically
5863 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5864 */
5865 struct sqlite3_vtab {
5866   const sqlite3_module *pModule;  /* The module for this virtual table */
5867   int nRef;                       /* NO LONGER USED */
5868   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5869   /* Virtual table implementations will typically add additional fields */
5870 };
5871
5872 /*
5873 ** CAPI3REF: Virtual Table Cursor Object
5874 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5875 **
5876 ** Every [virtual table module] implementation uses a subclass of the
5877 ** following structure to describe cursors that point into the
5878 ** [virtual table] and are used
5879 ** to loop through the virtual table.  Cursors are created using the
5880 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5881 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5882 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5883 ** of the module.  Each module implementation will define
5884 ** the content of a cursor structure to suit its own needs.
5885 **
5886 ** This superclass exists in order to define fields of the cursor that
5887 ** are common to all implementations.
5888 */
5889 struct sqlite3_vtab_cursor {
5890   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5891   /* Virtual table implementations will typically add additional fields */
5892 };
5893
5894 /*
5895 ** CAPI3REF: Declare The Schema Of A Virtual Table
5896 **
5897 ** ^The [xCreate] and [xConnect] methods of a
5898 ** [virtual table module] call this interface
5899 ** to declare the format (the names and datatypes of the columns) of
5900 ** the virtual tables they implement.
5901 */
5902 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5903
5904 /*
5905 ** CAPI3REF: Overload A Function For A Virtual Table
5906 **
5907 ** ^(Virtual tables can provide alternative implementations of functions
5908 ** using the [xFindFunction] method of the [virtual table module].  
5909 ** But global versions of those functions
5910 ** must exist in order to be overloaded.)^
5911 **
5912 ** ^(This API makes sure a global version of a function with a particular
5913 ** name and number of parameters exists.  If no such function exists
5914 ** before this API is called, a new function is created.)^  ^The implementation
5915 ** of the new function always causes an exception to be thrown.  So
5916 ** the new function is not good for anything by itself.  Its only
5917 ** purpose is to be a placeholder function that can be overloaded
5918 ** by a [virtual table].
5919 */
5920 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5921
5922 /*
5923 ** The interface to the virtual-table mechanism defined above (back up
5924 ** to a comment remarkably similar to this one) is currently considered
5925 ** to be experimental.  The interface might change in incompatible ways.
5926 ** If this is a problem for you, do not use the interface at this time.
5927 **
5928 ** When the virtual-table mechanism stabilizes, we will declare the
5929 ** interface fixed, support it indefinitely, and remove this comment.
5930 */
5931
5932 /*
5933 ** CAPI3REF: A Handle To An Open BLOB
5934 ** KEYWORDS: {BLOB handle} {BLOB handles}
5935 **
5936 ** An instance of this object represents an open BLOB on which
5937 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5938 ** ^Objects of this type are created by [sqlite3_blob_open()]
5939 ** and destroyed by [sqlite3_blob_close()].
5940 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5941 ** can be used to read or write small subsections of the BLOB.
5942 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5943 */
5944 typedef struct sqlite3_blob sqlite3_blob;
5945
5946 /*
5947 ** CAPI3REF: Open A BLOB For Incremental I/O
5948 **
5949 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5950 ** in row iRow, column zColumn, table zTable in database zDb;
5951 ** in other words, the same BLOB that would be selected by:
5952 **
5953 ** <pre>
5954 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5955 ** </pre>)^
5956 **
5957 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5958 ** and write access. ^If it is zero, the BLOB is opened for read access.
5959 ** ^It is not possible to open a column that is part of an index or primary 
5960 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5961 ** not possible to open a column that is part of a [child key] for writing.
5962 **
5963 ** ^Note that the database name is not the filename that contains
5964 ** the database but rather the symbolic name of the database that
5965 ** appears after the AS keyword when the database is connected using [ATTACH].
5966 ** ^For the main database file, the database name is "main".
5967 ** ^For TEMP tables, the database name is "temp".
5968 **
5969 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5970 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5971 ** to be a null pointer.)^
5972 ** ^This function sets the [database connection] error code and message
5973 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5974 ** functions. ^Note that the *ppBlob variable is always initialized in a
5975 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5976 ** regardless of the success or failure of this routine.
5977 **
5978 ** ^(If the row that a BLOB handle points to is modified by an
5979 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5980 ** then the BLOB handle is marked as "expired".
5981 ** This is true if any column of the row is changed, even a column
5982 ** other than the one the BLOB handle is open on.)^
5983 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5984 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5985 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5986 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5987 ** commit if the transaction continues to completion.)^
5988 **
5989 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5990 ** the opened blob.  ^The size of a blob may not be changed by this
5991 ** interface.  Use the [UPDATE] SQL command to change the size of a
5992 ** blob.
5993 **
5994 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5995 ** and the built-in [zeroblob] SQL function can be used, if desired,
5996 ** to create an empty, zero-filled blob in which to read or write using
5997 ** this interface.
5998 **
5999 ** To avoid a resource leak, every open [BLOB handle] should eventually
6000 ** be released by a call to [sqlite3_blob_close()].
6001 */
6002 SQLITE_API int sqlite3_blob_open(
6003   sqlite3*,
6004   const char *zDb,
6005   const char *zTable,
6006   const char *zColumn,
6007   sqlite3_int64 iRow,
6008   int flags,
6009   sqlite3_blob **ppBlob
6010 );
6011
6012 /*
6013 ** CAPI3REF: Move a BLOB Handle to a New Row
6014 **
6015 ** ^This function is used to move an existing blob handle so that it points
6016 ** to a different row of the same database table. ^The new row is identified
6017 ** by the rowid value passed as the second argument. Only the row can be
6018 ** changed. ^The database, table and column on which the blob handle is open
6019 ** remain the same. Moving an existing blob handle to a new row can be
6020 ** faster than closing the existing handle and opening a new one.
6021 **
6022 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6023 ** it must exist and there must be either a blob or text value stored in
6024 ** the nominated column.)^ ^If the new row is not present in the table, or if
6025 ** it does not contain a blob or text value, or if another error occurs, an
6026 ** SQLite error code is returned and the blob handle is considered aborted.
6027 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6028 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6029 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6030 ** always returns zero.
6031 **
6032 ** ^This function sets the database handle error code and message.
6033 */
6034 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6035
6036 /*
6037 ** CAPI3REF: Close A BLOB Handle
6038 **
6039 ** ^Closes an open [BLOB handle].
6040 **
6041 ** ^Closing a BLOB shall cause the current transaction to commit
6042 ** if there are no other BLOBs, no pending prepared statements, and the
6043 ** database connection is in [autocommit mode].
6044 ** ^If any writes were made to the BLOB, they might be held in cache
6045 ** until the close operation if they will fit.
6046 **
6047 ** ^(Closing the BLOB often forces the changes
6048 ** out to disk and so if any I/O errors occur, they will likely occur
6049 ** at the time when the BLOB is closed.  Any errors that occur during
6050 ** closing are reported as a non-zero return value.)^
6051 **
6052 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
6053 ** an error code, the BLOB is still closed.)^
6054 **
6055 ** ^Calling this routine with a null pointer (such as would be returned
6056 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
6057 */
6058 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6059
6060 /*
6061 ** CAPI3REF: Return The Size Of An Open BLOB
6062 **
6063 ** ^Returns the size in bytes of the BLOB accessible via the 
6064 ** successfully opened [BLOB handle] in its only argument.  ^The
6065 ** incremental blob I/O routines can only read or overwriting existing
6066 ** blob content; they cannot change the size of a blob.
6067 **
6068 ** This routine only works on a [BLOB handle] which has been created
6069 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6070 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6071 ** to this routine results in undefined and probably undesirable behavior.
6072 */
6073 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6074
6075 /*
6076 ** CAPI3REF: Read Data From A BLOB Incrementally
6077 **
6078 ** ^(This function is used to read data from an open [BLOB handle] into a
6079 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6080 ** from the open BLOB, starting at offset iOffset.)^
6081 **
6082 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6083 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
6084 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6085 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6086 ** can be determined using the [sqlite3_blob_bytes()] interface.
6087 **
6088 ** ^An attempt to read from an expired [BLOB handle] fails with an
6089 ** error code of [SQLITE_ABORT].
6090 **
6091 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6092 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6093 **
6094 ** This routine only works on a [BLOB handle] which has been created
6095 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6096 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6097 ** to this routine results in undefined and probably undesirable behavior.
6098 **
6099 ** See also: [sqlite3_blob_write()].
6100 */
6101 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6102
6103 /*
6104 ** CAPI3REF: Write Data Into A BLOB Incrementally
6105 **
6106 ** ^This function is used to write data into an open [BLOB handle] from a
6107 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
6108 ** into the open BLOB, starting at offset iOffset.
6109 **
6110 ** ^If the [BLOB handle] passed as the first argument was not opened for
6111 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6112 ** this function returns [SQLITE_READONLY].
6113 **
6114 ** ^This function may only modify the contents of the BLOB; it is
6115 ** not possible to increase the size of a BLOB using this API.
6116 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6117 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
6118 ** less than zero [SQLITE_ERROR] is returned and no data is written.
6119 ** The size of the BLOB (and hence the maximum value of N+iOffset)
6120 ** can be determined using the [sqlite3_blob_bytes()] interface.
6121 **
6122 ** ^An attempt to write to an expired [BLOB handle] fails with an
6123 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
6124 ** before the [BLOB handle] expired are not rolled back by the
6125 ** expiration of the handle, though of course those changes might
6126 ** have been overwritten by the statement that expired the BLOB handle
6127 ** or by other independent statements.
6128 **
6129 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6130 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
6131 **
6132 ** This routine only works on a [BLOB handle] which has been created
6133 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6134 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6135 ** to this routine results in undefined and probably undesirable behavior.
6136 **
6137 ** See also: [sqlite3_blob_read()].
6138 */
6139 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6140
6141 /*
6142 ** CAPI3REF: Virtual File System Objects
6143 **
6144 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6145 ** that SQLite uses to interact
6146 ** with the underlying operating system.  Most SQLite builds come with a
6147 ** single default VFS that is appropriate for the host computer.
6148 ** New VFSes can be registered and existing VFSes can be unregistered.
6149 ** The following interfaces are provided.
6150 **
6151 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6152 ** ^Names are case sensitive.
6153 ** ^Names are zero-terminated UTF-8 strings.
6154 ** ^If there is no match, a NULL pointer is returned.
6155 ** ^If zVfsName is NULL then the default VFS is returned.
6156 **
6157 ** ^New VFSes are registered with sqlite3_vfs_register().
6158 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6159 ** ^The same VFS can be registered multiple times without injury.
6160 ** ^To make an existing VFS into the default VFS, register it again
6161 ** with the makeDflt flag set.  If two different VFSes with the
6162 ** same name are registered, the behavior is undefined.  If a
6163 ** VFS is registered with a name that is NULL or an empty string,
6164 ** then the behavior is undefined.
6165 **
6166 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6167 ** ^(If the default VFS is unregistered, another VFS is chosen as
6168 ** the default.  The choice for the new VFS is arbitrary.)^
6169 */
6170 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6171 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6172 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6173
6174 /*
6175 ** CAPI3REF: Mutexes
6176 **
6177 ** The SQLite core uses these routines for thread
6178 ** synchronization. Though they are intended for internal
6179 ** use by SQLite, code that links against SQLite is
6180 ** permitted to use any of these routines.
6181 **
6182 ** The SQLite source code contains multiple implementations
6183 ** of these mutex routines.  An appropriate implementation
6184 ** is selected automatically at compile-time.  ^(The following
6185 ** implementations are available in the SQLite core:
6186 **
6187 ** <ul>
6188 ** <li>   SQLITE_MUTEX_PTHREADS
6189 ** <li>   SQLITE_MUTEX_W32
6190 ** <li>   SQLITE_MUTEX_NOOP
6191 ** </ul>)^
6192 **
6193 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
6194 ** that does no real locking and is appropriate for use in
6195 ** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and
6196 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6197 ** and Windows.
6198 **
6199 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6200 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6201 ** implementation is included with the library. In this case the
6202 ** application must supply a custom mutex implementation using the
6203 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6204 ** before calling sqlite3_initialize() or any other public sqlite3_
6205 ** function that calls sqlite3_initialize().)^
6206 **
6207 ** ^The sqlite3_mutex_alloc() routine allocates a new
6208 ** mutex and returns a pointer to it. ^If it returns NULL
6209 ** that means that a mutex could not be allocated.  ^SQLite
6210 ** will unwind its stack and return an error.  ^(The argument
6211 ** to sqlite3_mutex_alloc() is one of these integer constants:
6212 **
6213 ** <ul>
6214 ** <li>  SQLITE_MUTEX_FAST
6215 ** <li>  SQLITE_MUTEX_RECURSIVE
6216 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6217 ** <li>  SQLITE_MUTEX_STATIC_MEM
6218 ** <li>  SQLITE_MUTEX_STATIC_MEM2
6219 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6220 ** <li>  SQLITE_MUTEX_STATIC_LRU
6221 ** <li>  SQLITE_MUTEX_STATIC_LRU2
6222 ** </ul>)^
6223 **
6224 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6225 ** cause sqlite3_mutex_alloc() to create
6226 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6227 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6228 ** The mutex implementation does not need to make a distinction
6229 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6230 ** not want to.  ^SQLite will only request a recursive mutex in
6231 ** cases where it really needs one.  ^If a faster non-recursive mutex
6232 ** implementation is available on the host platform, the mutex subsystem
6233 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6234 **
6235 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6236 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6237 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
6238 ** used by the current version of SQLite.  Future versions of SQLite
6239 ** may add additional static mutexes.  Static mutexes are for internal
6240 ** use by SQLite only.  Applications that use SQLite mutexes should
6241 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6242 ** SQLITE_MUTEX_RECURSIVE.
6243 **
6244 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6245 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6246 ** returns a different mutex on every call.  ^But for the static
6247 ** mutex types, the same mutex is returned on every call that has
6248 ** the same type number.
6249 **
6250 ** ^The sqlite3_mutex_free() routine deallocates a previously
6251 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
6252 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
6253 ** use when they are deallocated.  Attempting to deallocate a static
6254 ** mutex results in undefined behavior.  ^SQLite never deallocates
6255 ** a static mutex.
6256 **
6257 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6258 ** to enter a mutex.  ^If another thread is already within the mutex,
6259 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6260 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6261 ** upon successful entry.  ^(Mutexes created using
6262 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6263 ** In such cases the,
6264 ** mutex must be exited an equal number of times before another thread
6265 ** can enter.)^  ^(If the same thread tries to enter any other
6266 ** kind of mutex more than once, the behavior is undefined.
6267 ** SQLite will never exhibit
6268 ** such behavior in its own use of mutexes.)^
6269 **
6270 ** ^(Some systems (for example, Windows 95) do not support the operation
6271 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6272 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
6273 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6274 **
6275 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6276 ** previously entered by the same thread.   ^(The behavior
6277 ** is undefined if the mutex is not currently entered by the
6278 ** calling thread or is not currently allocated.  SQLite will
6279 ** never do either.)^
6280 **
6281 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6282 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6283 ** behave as no-ops.
6284 **
6285 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6286 */
6287 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6288 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6289 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6290 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6291 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6292
6293 /*
6294 ** CAPI3REF: Mutex Methods Object
6295 **
6296 ** An instance of this structure defines the low-level routines
6297 ** used to allocate and use mutexes.
6298 **
6299 ** Usually, the default mutex implementations provided by SQLite are
6300 ** sufficient, however the user has the option of substituting a custom
6301 ** implementation for specialized deployments or systems for which SQLite
6302 ** does not provide a suitable implementation. In this case, the user
6303 ** creates and populates an instance of this structure to pass
6304 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6305 ** Additionally, an instance of this structure can be used as an
6306 ** output variable when querying the system for the current mutex
6307 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6308 **
6309 ** ^The xMutexInit method defined by this structure is invoked as
6310 ** part of system initialization by the sqlite3_initialize() function.
6311 ** ^The xMutexInit routine is called by SQLite exactly once for each
6312 ** effective call to [sqlite3_initialize()].
6313 **
6314 ** ^The xMutexEnd method defined by this structure is invoked as
6315 ** part of system shutdown by the sqlite3_shutdown() function. The
6316 ** implementation of this method is expected to release all outstanding
6317 ** resources obtained by the mutex methods implementation, especially
6318 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
6319 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6320 **
6321 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6322 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6323 ** xMutexNotheld) implement the following interfaces (respectively):
6324 **
6325 ** <ul>
6326 **   <li>  [sqlite3_mutex_alloc()] </li>
6327 **   <li>  [sqlite3_mutex_free()] </li>
6328 **   <li>  [sqlite3_mutex_enter()] </li>
6329 **   <li>  [sqlite3_mutex_try()] </li>
6330 **   <li>  [sqlite3_mutex_leave()] </li>
6331 **   <li>  [sqlite3_mutex_held()] </li>
6332 **   <li>  [sqlite3_mutex_notheld()] </li>
6333 ** </ul>)^
6334 **
6335 ** The only difference is that the public sqlite3_XXX functions enumerated
6336 ** above silently ignore any invocations that pass a NULL pointer instead
6337 ** of a valid mutex handle. The implementations of the methods defined
6338 ** by this structure are not required to handle this case, the results
6339 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6340 ** (i.e. it is acceptable to provide an implementation that segfaults if
6341 ** it is passed a NULL pointer).
6342 **
6343 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6344 ** invoke xMutexInit() multiple times within the same process and without
6345 ** intervening calls to xMutexEnd().  Second and subsequent calls to
6346 ** xMutexInit() must be no-ops.
6347 **
6348 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6349 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6350 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6351 ** memory allocation for a fast or recursive mutex.
6352 **
6353 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6354 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6355 ** If xMutexInit fails in any way, it is expected to clean up after itself
6356 ** prior to returning.
6357 */
6358 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6359 struct sqlite3_mutex_methods {
6360   int (*xMutexInit)(void);
6361   int (*xMutexEnd)(void);
6362   sqlite3_mutex *(*xMutexAlloc)(int);
6363   void (*xMutexFree)(sqlite3_mutex *);
6364   void (*xMutexEnter)(sqlite3_mutex *);
6365   int (*xMutexTry)(sqlite3_mutex *);
6366   void (*xMutexLeave)(sqlite3_mutex *);
6367   int (*xMutexHeld)(sqlite3_mutex *);
6368   int (*xMutexNotheld)(sqlite3_mutex *);
6369 };
6370
6371 /*
6372 ** CAPI3REF: Mutex Verification Routines
6373 **
6374 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6375 ** are intended for use inside assert() statements.  ^The SQLite core
6376 ** never uses these routines except inside an assert() and applications
6377 ** are advised to follow the lead of the core.  ^The SQLite core only
6378 ** provides implementations for these routines when it is compiled
6379 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
6380 ** are only required to provide these routines if SQLITE_DEBUG is
6381 ** defined and if NDEBUG is not defined.
6382 **
6383 ** ^These routines should return true if the mutex in their argument
6384 ** is held or not held, respectively, by the calling thread.
6385 **
6386 ** ^The implementation is not required to provide versions of these
6387 ** routines that actually work. If the implementation does not provide working
6388 ** versions of these routines, it should at least provide stubs that always
6389 ** return true so that one does not get spurious assertion failures.
6390 **
6391 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6392 ** the routine should return 1.   This seems counter-intuitive since
6393 ** clearly the mutex cannot be held if it does not exist.  But
6394 ** the reason the mutex does not exist is because the build is not
6395 ** using mutexes.  And we do not want the assert() containing the
6396 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6397 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6398 ** interface should also return 1 when given a NULL pointer.
6399 */
6400 #ifndef NDEBUG
6401 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6402 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6403 #endif
6404
6405 /*
6406 ** CAPI3REF: Mutex Types
6407 **
6408 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6409 ** which is one of these integer constants.
6410 **
6411 ** The set of static mutexes may change from one SQLite release to the
6412 ** next.  Applications that override the built-in mutex logic must be
6413 ** prepared to accommodate additional static mutexes.
6414 */
6415 #define SQLITE_MUTEX_FAST             0
6416 #define SQLITE_MUTEX_RECURSIVE        1
6417 #define SQLITE_MUTEX_STATIC_MASTER    2
6418 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6419 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6420 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6421 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6422 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6423 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6424 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6425
6426 /*
6427 ** CAPI3REF: Retrieve the mutex for a database connection
6428 **
6429 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
6430 ** serializes access to the [database connection] given in the argument
6431 ** when the [threading mode] is Serialized.
6432 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6433 ** routine returns a NULL pointer.
6434 */
6435 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6436
6437 /*
6438 ** CAPI3REF: Low-Level Control Of Database Files
6439 **
6440 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6441 ** xFileControl method for the [sqlite3_io_methods] object associated
6442 ** with a particular database identified by the second argument. ^The
6443 ** name of the database is "main" for the main database or "temp" for the
6444 ** TEMP database, or the name that appears after the AS keyword for
6445 ** databases that are added using the [ATTACH] SQL command.
6446 ** ^A NULL pointer can be used in place of "main" to refer to the
6447 ** main database file.
6448 ** ^The third and fourth parameters to this routine
6449 ** are passed directly through to the second and third parameters of
6450 ** the xFileControl method.  ^The return value of the xFileControl
6451 ** method becomes the return value of this routine.
6452 **
6453 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6454 ** a pointer to the underlying [sqlite3_file] object to be written into
6455 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6456 ** case is a short-circuit path which does not actually invoke the
6457 ** underlying sqlite3_io_methods.xFileControl method.
6458 **
6459 ** ^If the second parameter (zDbName) does not match the name of any
6460 ** open database file, then SQLITE_ERROR is returned.  ^This error
6461 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6462 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
6463 ** also return SQLITE_ERROR.  There is no way to distinguish between
6464 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6465 ** xFileControl method.
6466 **
6467 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6468 */
6469 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6470
6471 /*
6472 ** CAPI3REF: Testing Interface
6473 **
6474 ** ^The sqlite3_test_control() interface is used to read out internal
6475 ** state of SQLite and to inject faults into SQLite for testing
6476 ** purposes.  ^The first parameter is an operation code that determines
6477 ** the number, meaning, and operation of all subsequent parameters.
6478 **
6479 ** This interface is not for use by applications.  It exists solely
6480 ** for verifying the correct operation of the SQLite library.  Depending
6481 ** on how the SQLite library is compiled, this interface might not exist.
6482 **
6483 ** The details of the operation codes, their meanings, the parameters
6484 ** they take, and what they do are all subject to change without notice.
6485 ** Unlike most of the SQLite API, this function is not guaranteed to
6486 ** operate consistently from one release to the next.
6487 */
6488 SQLITE_API int sqlite3_test_control(int op, ...);
6489
6490 /*
6491 ** CAPI3REF: Testing Interface Operation Codes
6492 **
6493 ** These constants are the valid operation code parameters used
6494 ** as the first argument to [sqlite3_test_control()].
6495 **
6496 ** These parameters and their meanings are subject to change
6497 ** without notice.  These values are for testing purposes only.
6498 ** Applications should not use any of these parameters or the
6499 ** [sqlite3_test_control()] interface.
6500 */
6501 #define SQLITE_TESTCTRL_FIRST                    5
6502 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6503 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6504 #define SQLITE_TESTCTRL_PRNG_RESET               7
6505 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6506 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6507 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6508 #define SQLITE_TESTCTRL_PENDING_BYTE            11
6509 #define SQLITE_TESTCTRL_ASSERT                  12
6510 #define SQLITE_TESTCTRL_ALWAYS                  13
6511 #define SQLITE_TESTCTRL_RESERVE                 14
6512 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6513 #define SQLITE_TESTCTRL_ISKEYWORD               16
6514 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6515 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6516 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19
6517 #define SQLITE_TESTCTRL_LAST                    19
6518
6519 /*
6520 ** CAPI3REF: SQLite Runtime Status
6521 **
6522 ** ^This interface is used to retrieve runtime status information
6523 ** about the performance of SQLite, and optionally to reset various
6524 ** highwater marks.  ^The first argument is an integer code for
6525 ** the specific parameter to measure.  ^(Recognized integer codes
6526 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6527 ** ^The current value of the parameter is returned into *pCurrent.
6528 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6529 ** resetFlag is true, then the highest record value is reset after
6530 ** *pHighwater is written.  ^(Some parameters do not record the highest
6531 ** value.  For those parameters
6532 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6533 ** ^(Other parameters record only the highwater mark and not the current
6534 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6535 **
6536 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6537 ** non-zero [error code] on failure.
6538 **
6539 ** This routine is threadsafe but is not atomic.  This routine can be
6540 ** called while other threads are running the same or different SQLite
6541 ** interfaces.  However the values returned in *pCurrent and
6542 ** *pHighwater reflect the status of SQLite at different points in time
6543 ** and it is possible that another thread might change the parameter
6544 ** in between the times when *pCurrent and *pHighwater are written.
6545 **
6546 ** See also: [sqlite3_db_status()]
6547 */
6548 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6549
6550
6551 /*
6552 ** CAPI3REF: Status Parameters
6553 ** KEYWORDS: {status parameters}
6554 **
6555 ** These integer constants designate various run-time status parameters
6556 ** that can be returned by [sqlite3_status()].
6557 **
6558 ** <dl>
6559 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6560 ** <dd>This parameter is the current amount of memory checked out
6561 ** using [sqlite3_malloc()], either directly or indirectly.  The
6562 ** figure includes calls made to [sqlite3_malloc()] by the application
6563 ** and internal memory usage by the SQLite library.  Scratch memory
6564 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6565 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6566 ** this parameter.  The amount returned is the sum of the allocation
6567 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6568 **
6569 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6570 ** <dd>This parameter records the largest memory allocation request
6571 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6572 ** internal equivalents).  Only the value returned in the
6573 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6574 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6575 **
6576 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6577 ** <dd>This parameter records the number of separate memory allocations
6578 ** currently checked out.</dd>)^
6579 **
6580 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6581 ** <dd>This parameter returns the number of pages used out of the
6582 ** [pagecache memory allocator] that was configured using 
6583 ** [SQLITE_CONFIG_PAGECACHE].  The
6584 ** value returned is in pages, not in bytes.</dd>)^
6585 **
6586 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
6587 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6588 ** <dd>This parameter returns the number of bytes of page cache
6589 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6590 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6591 ** returned value includes allocations that overflowed because they
6592 ** where too large (they were larger than the "sz" parameter to
6593 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6594 ** no space was left in the page cache.</dd>)^
6595 **
6596 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6597 ** <dd>This parameter records the largest memory allocation request
6598 ** handed to [pagecache memory allocator].  Only the value returned in the
6599 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6600 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6601 **
6602 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6603 ** <dd>This parameter returns the number of allocations used out of the
6604 ** [scratch memory allocator] configured using
6605 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6606 ** in bytes.  Since a single thread may only have one scratch allocation
6607 ** outstanding at time, this parameter also reports the number of threads
6608 ** using scratch memory at the same time.</dd>)^
6609 **
6610 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6611 ** <dd>This parameter returns the number of bytes of scratch memory
6612 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6613 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6614 ** returned include overflows because the requested allocation was too
6615 ** larger (that is, because the requested allocation was larger than the
6616 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6617 ** slots were available.
6618 ** </dd>)^
6619 **
6620 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6621 ** <dd>This parameter records the largest memory allocation request
6622 ** handed to [scratch memory allocator].  Only the value returned in the
6623 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6624 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6625 **
6626 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6627 ** <dd>This parameter records the deepest parser stack.  It is only
6628 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6629 ** </dl>
6630 **
6631 ** New status parameters may be added from time to time.
6632 */
6633 #define SQLITE_STATUS_MEMORY_USED          0
6634 #define SQLITE_STATUS_PAGECACHE_USED       1
6635 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6636 #define SQLITE_STATUS_SCRATCH_USED         3
6637 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6638 #define SQLITE_STATUS_MALLOC_SIZE          5
6639 #define SQLITE_STATUS_PARSER_STACK         6
6640 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6641 #define SQLITE_STATUS_SCRATCH_SIZE         8
6642 #define SQLITE_STATUS_MALLOC_COUNT         9
6643
6644 /*
6645 ** CAPI3REF: Database Connection Status
6646 **
6647 ** ^This interface is used to retrieve runtime status information 
6648 ** about a single [database connection].  ^The first argument is the
6649 ** database connection object to be interrogated.  ^The second argument
6650 ** is an integer constant, taken from the set of
6651 ** [SQLITE_DBSTATUS options], that
6652 ** determines the parameter to interrogate.  The set of 
6653 ** [SQLITE_DBSTATUS options] is likely
6654 ** to grow in future releases of SQLite.
6655 **
6656 ** ^The current value of the requested parameter is written into *pCur
6657 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6658 ** the resetFlg is true, then the highest instantaneous value is
6659 ** reset back down to the current value.
6660 **
6661 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6662 ** non-zero [error code] on failure.
6663 **
6664 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6665 */
6666 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6667
6668 /*
6669 ** CAPI3REF: Status Parameters for database connections
6670 ** KEYWORDS: {SQLITE_DBSTATUS options}
6671 **
6672 ** These constants are the available integer "verbs" that can be passed as
6673 ** the second argument to the [sqlite3_db_status()] interface.
6674 **
6675 ** New verbs may be added in future releases of SQLite. Existing verbs
6676 ** might be discontinued. Applications should check the return code from
6677 ** [sqlite3_db_status()] to make sure that the call worked.
6678 ** The [sqlite3_db_status()] interface will return a non-zero error code
6679 ** if a discontinued or unsupported verb is invoked.
6680 **
6681 ** <dl>
6682 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6683 ** <dd>This parameter returns the number of lookaside memory slots currently
6684 ** checked out.</dd>)^
6685 **
6686 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6687 ** <dd>This parameter returns the number malloc attempts that were 
6688 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6689 ** the current value is always zero.)^
6690 **
6691 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6692 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6693 ** <dd>This parameter returns the number malloc attempts that might have
6694 ** been satisfied using lookaside memory but failed due to the amount of
6695 ** memory requested being larger than the lookaside slot size.
6696 ** Only the high-water value is meaningful;
6697 ** the current value is always zero.)^
6698 **
6699 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6700 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6701 ** <dd>This parameter returns the number malloc attempts that might have
6702 ** been satisfied using lookaside memory but failed due to all lookaside
6703 ** memory already being in use.
6704 ** Only the high-water value is meaningful;
6705 ** the current value is always zero.)^
6706 **
6707 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6708 ** <dd>This parameter returns the approximate number of of bytes of heap
6709 ** memory used by all pager caches associated with the database connection.)^
6710 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6711 **
6712 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6713 ** <dd>This parameter returns the approximate number of of bytes of heap
6714 ** memory used to store the schema for all databases associated
6715 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
6716 ** ^The full amount of memory used by the schemas is reported, even if the
6717 ** schema memory is shared with other database connections due to
6718 ** [shared cache mode] being enabled.
6719 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6720 **
6721 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6722 ** <dd>This parameter returns the approximate number of of bytes of heap
6723 ** and lookaside memory used by all prepared statements associated with
6724 ** the database connection.)^
6725 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6726 ** </dd>
6727 **
6728 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6729 ** <dd>This parameter returns the number of pager cache hits that have
6730 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT 
6731 ** is always 0.
6732 ** </dd>
6733 **
6734 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6735 ** <dd>This parameter returns the number of pager cache misses that have
6736 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS 
6737 ** is always 0.
6738 ** </dd>
6739 **
6740 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6741 ** <dd>This parameter returns the number of dirty cache entries that have
6742 ** been written to disk. Specifically, the number of pages written to the
6743 ** wal file in wal mode databases, or the number of pages written to the
6744 ** database file in rollback mode databases. Any pages written as part of
6745 ** transaction rollback or database recovery operations are not included.
6746 ** If an IO or other error occurs while writing a page to disk, the effect
6747 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6748 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6749 ** </dd>
6750 ** </dl>
6751 */
6752 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6753 #define SQLITE_DBSTATUS_CACHE_USED           1
6754 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6755 #define SQLITE_DBSTATUS_STMT_USED            3
6756 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6757 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6758 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6759 #define SQLITE_DBSTATUS_CACHE_HIT            7
6760 #define SQLITE_DBSTATUS_CACHE_MISS           8
6761 #define SQLITE_DBSTATUS_CACHE_WRITE          9
6762 #define SQLITE_DBSTATUS_MAX                  9   /* Largest defined DBSTATUS */
6763
6764
6765 /*
6766 ** CAPI3REF: Prepared Statement Status
6767 **
6768 ** ^(Each prepared statement maintains various
6769 ** [SQLITE_STMTSTATUS counters] that measure the number
6770 ** of times it has performed specific operations.)^  These counters can
6771 ** be used to monitor the performance characteristics of the prepared
6772 ** statements.  For example, if the number of table steps greatly exceeds
6773 ** the number of table searches or result rows, that would tend to indicate
6774 ** that the prepared statement is using a full table scan rather than
6775 ** an index.  
6776 **
6777 ** ^(This interface is used to retrieve and reset counter values from
6778 ** a [prepared statement].  The first argument is the prepared statement
6779 ** object to be interrogated.  The second argument
6780 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6781 ** to be interrogated.)^
6782 ** ^The current value of the requested counter is returned.
6783 ** ^If the resetFlg is true, then the counter is reset to zero after this
6784 ** interface call returns.
6785 **
6786 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6787 */
6788 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6789
6790 /*
6791 ** CAPI3REF: Status Parameters for prepared statements
6792 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6793 **
6794 ** These preprocessor macros define integer codes that name counter
6795 ** values associated with the [sqlite3_stmt_status()] interface.
6796 ** The meanings of the various counters are as follows:
6797 **
6798 ** <dl>
6799 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6800 ** <dd>^This is the number of times that SQLite has stepped forward in
6801 ** a table as part of a full table scan.  Large numbers for this counter
6802 ** may indicate opportunities for performance improvement through 
6803 ** careful use of indices.</dd>
6804 **
6805 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6806 ** <dd>^This is the number of sort operations that have occurred.
6807 ** A non-zero value in this counter may indicate an opportunity to
6808 ** improvement performance through careful use of indices.</dd>
6809 **
6810 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6811 ** <dd>^This is the number of rows inserted into transient indices that
6812 ** were created automatically in order to help joins run faster.
6813 ** A non-zero value in this counter may indicate an opportunity to
6814 ** improvement performance by adding permanent indices that do not
6815 ** need to be reinitialized each time the statement is run.</dd>
6816 ** </dl>
6817 */
6818 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6819 #define SQLITE_STMTSTATUS_SORT              2
6820 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6821
6822 /*
6823 ** CAPI3REF: Custom Page Cache Object
6824 **
6825 ** The sqlite3_pcache type is opaque.  It is implemented by
6826 ** the pluggable module.  The SQLite core has no knowledge of
6827 ** its size or internal structure and never deals with the
6828 ** sqlite3_pcache object except by holding and passing pointers
6829 ** to the object.
6830 **
6831 ** See [sqlite3_pcache_methods2] for additional information.
6832 */
6833 typedef struct sqlite3_pcache sqlite3_pcache;
6834
6835 /*
6836 ** CAPI3REF: Custom Page Cache Object
6837 **
6838 ** The sqlite3_pcache_page object represents a single page in the
6839 ** page cache.  The page cache will allocate instances of this
6840 ** object.  Various methods of the page cache use pointers to instances
6841 ** of this object as parameters or as their return value.
6842 **
6843 ** See [sqlite3_pcache_methods2] for additional information.
6844 */
6845 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6846 struct sqlite3_pcache_page {
6847   void *pBuf;        /* The content of the page */
6848   void *pExtra;      /* Extra information associated with the page */
6849 };
6850
6851 /*
6852 ** CAPI3REF: Application Defined Page Cache.
6853 ** KEYWORDS: {page cache}
6854 **
6855 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6856 ** register an alternative page cache implementation by passing in an 
6857 ** instance of the sqlite3_pcache_methods2 structure.)^
6858 ** In many applications, most of the heap memory allocated by 
6859 ** SQLite is used for the page cache.
6860 ** By implementing a 
6861 ** custom page cache using this API, an application can better control
6862 ** the amount of memory consumed by SQLite, the way in which 
6863 ** that memory is allocated and released, and the policies used to 
6864 ** determine exactly which parts of a database file are cached and for 
6865 ** how long.
6866 **
6867 ** The alternative page cache mechanism is an
6868 ** extreme measure that is only needed by the most demanding applications.
6869 ** The built-in page cache is recommended for most uses.
6870 **
6871 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6872 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6873 ** the application may discard the parameter after the call to
6874 ** [sqlite3_config()] returns.)^
6875 **
6876 ** [[the xInit() page cache method]]
6877 ** ^(The xInit() method is called once for each effective 
6878 ** call to [sqlite3_initialize()])^
6879 ** (usually only once during the lifetime of the process). ^(The xInit()
6880 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6881 ** The intent of the xInit() method is to set up global data structures 
6882 ** required by the custom page cache implementation. 
6883 ** ^(If the xInit() method is NULL, then the 
6884 ** built-in default page cache is used instead of the application defined
6885 ** page cache.)^
6886 **
6887 ** [[the xShutdown() page cache method]]
6888 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6889 ** It can be used to clean up 
6890 ** any outstanding resources before process shutdown, if required.
6891 ** ^The xShutdown() method may be NULL.
6892 **
6893 ** ^SQLite automatically serializes calls to the xInit method,
6894 ** so the xInit method need not be threadsafe.  ^The
6895 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6896 ** not need to be threadsafe either.  All other methods must be threadsafe
6897 ** in multithreaded applications.
6898 **
6899 ** ^SQLite will never invoke xInit() more than once without an intervening
6900 ** call to xShutdown().
6901 **
6902 ** [[the xCreate() page cache methods]]
6903 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6904 ** SQLite will typically create one cache instance for each open database file,
6905 ** though this is not guaranteed. ^The
6906 ** first parameter, szPage, is the size in bytes of the pages that must
6907 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
6908 ** second parameter szExtra is a number of bytes of extra storage 
6909 ** associated with each page cache entry.  ^The szExtra parameter will
6910 ** a number less than 250.  SQLite will use the
6911 ** extra szExtra bytes on each page to store metadata about the underlying
6912 ** database page on disk.  The value passed into szExtra depends
6913 ** on the SQLite version, the target platform, and how SQLite was compiled.
6914 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6915 ** created will be used to cache database pages of a file stored on disk, or
6916 ** false if it is used for an in-memory database. The cache implementation
6917 ** does not have to do anything special based with the value of bPurgeable;
6918 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6919 ** never invoke xUnpin() except to deliberately delete a page.
6920 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6921 ** false will always have the "discard" flag set to true.  
6922 ** ^Hence, a cache created with bPurgeable false will
6923 ** never contain any unpinned pages.
6924 **
6925 ** [[the xCachesize() page cache method]]
6926 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6927 ** suggested maximum cache-size (number of pages stored by) the cache
6928 ** instance passed as the first argument. This is the value configured using
6929 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6930 ** parameter, the implementation is not required to do anything with this
6931 ** value; it is advisory only.
6932 **
6933 ** [[the xPagecount() page cache methods]]
6934 ** The xPagecount() method must return the number of pages currently
6935 ** stored in the cache, both pinned and unpinned.
6936 ** 
6937 ** [[the xFetch() page cache methods]]
6938 ** The xFetch() method locates a page in the cache and returns a pointer to 
6939 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6940 ** The pBuf element of the returned sqlite3_pcache_page object will be a
6941 ** pointer to a buffer of szPage bytes used to store the content of a 
6942 ** single database page.  The pExtra element of sqlite3_pcache_page will be
6943 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
6944 ** for each entry in the page cache.
6945 **
6946 ** The page to be fetched is determined by the key. ^The minimum key value
6947 ** is 1.  After it has been retrieved using xFetch, the page is considered
6948 ** to be "pinned".
6949 **
6950 ** If the requested page is already in the page cache, then the page cache
6951 ** implementation must return a pointer to the page buffer with its content
6952 ** intact.  If the requested page is not already in the cache, then the
6953 ** cache implementation should use the value of the createFlag
6954 ** parameter to help it determined what action to take:
6955 **
6956 ** <table border=1 width=85% align=center>
6957 ** <tr><th> createFlag <th> Behavior when page is not already in cache
6958 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6959 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6960 **                 Otherwise return NULL.
6961 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6962 **                 NULL if allocating a new page is effectively impossible.
6963 ** </table>
6964 **
6965 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6966 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6967 ** failed.)^  In between the to xFetch() calls, SQLite may
6968 ** attempt to unpin one or more cache pages by spilling the content of
6969 ** pinned pages to disk and synching the operating system disk cache.
6970 **
6971 ** [[the xUnpin() page cache method]]
6972 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6973 ** as its second argument.  If the third parameter, discard, is non-zero,
6974 ** then the page must be evicted from the cache.
6975 ** ^If the discard parameter is
6976 ** zero, then the page may be discarded or retained at the discretion of
6977 ** page cache implementation. ^The page cache implementation
6978 ** may choose to evict unpinned pages at any time.
6979 **
6980 ** The cache must not perform any reference counting. A single 
6981 ** call to xUnpin() unpins the page regardless of the number of prior calls 
6982 ** to xFetch().
6983 **
6984 ** [[the xRekey() page cache methods]]
6985 ** The xRekey() method is used to change the key value associated with the
6986 ** page passed as the second argument. If the cache
6987 ** previously contains an entry associated with newKey, it must be
6988 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6989 ** to be pinned.
6990 **
6991 ** When SQLite calls the xTruncate() method, the cache must discard all
6992 ** existing cache entries with page numbers (keys) greater than or equal
6993 ** to the value of the iLimit parameter passed to xTruncate(). If any
6994 ** of these pages are pinned, they are implicitly unpinned, meaning that
6995 ** they can be safely discarded.
6996 **
6997 ** [[the xDestroy() page cache method]]
6998 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6999 ** All resources associated with the specified cache should be freed. ^After
7000 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7001 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7002 ** functions.
7003 **
7004 ** [[the xShrink() page cache method]]
7005 ** ^SQLite invokes the xShrink() method when it wants the page cache to
7006 ** free up as much of heap memory as possible.  The page cache implementation
7007 ** is not obligated to free any memory, but well-behaved implementations should
7008 ** do their best.
7009 */
7010 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7011 struct sqlite3_pcache_methods2 {
7012   int iVersion;
7013   void *pArg;
7014   int (*xInit)(void*);
7015   void (*xShutdown)(void*);
7016   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7017   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7018   int (*xPagecount)(sqlite3_pcache*);
7019   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7020   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7021   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
7022       unsigned oldKey, unsigned newKey);
7023   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7024   void (*xDestroy)(sqlite3_pcache*);
7025   void (*xShrink)(sqlite3_pcache*);
7026 };
7027
7028 /*
7029 ** This is the obsolete pcache_methods object that has now been replaced
7030 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
7031 ** retained in the header file for backwards compatibility only.
7032 */
7033 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7034 struct sqlite3_pcache_methods {
7035   void *pArg;
7036   int (*xInit)(void*);
7037   void (*xShutdown)(void*);
7038   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7039   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7040   int (*xPagecount)(sqlite3_pcache*);
7041   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7042   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7043   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7044   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7045   void (*xDestroy)(sqlite3_pcache*);
7046 };
7047
7048
7049 /*
7050 ** CAPI3REF: Online Backup Object
7051 **
7052 ** The sqlite3_backup object records state information about an ongoing
7053 ** online backup operation.  ^The sqlite3_backup object is created by
7054 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7055 ** [sqlite3_backup_finish()].
7056 **
7057 ** See Also: [Using the SQLite Online Backup API]
7058 */
7059 typedef struct sqlite3_backup sqlite3_backup;
7060
7061 /*
7062 ** CAPI3REF: Online Backup API.
7063 **
7064 ** The backup API copies the content of one database into another.
7065 ** It is useful either for creating backups of databases or
7066 ** for copying in-memory databases to or from persistent files. 
7067 **
7068 ** See Also: [Using the SQLite Online Backup API]
7069 **
7070 ** ^SQLite holds a write transaction open on the destination database file
7071 ** for the duration of the backup operation.
7072 ** ^The source database is read-locked only while it is being read;
7073 ** it is not locked continuously for the entire backup operation.
7074 ** ^Thus, the backup may be performed on a live source database without
7075 ** preventing other database connections from
7076 ** reading or writing to the source database while the backup is underway.
7077 ** 
7078 ** ^(To perform a backup operation: 
7079 **   <ol>
7080 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
7081 **         backup, 
7082 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
7083 **         the data between the two databases, and finally
7084 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
7085 **         associated with the backup operation. 
7086 **   </ol>)^
7087 ** There should be exactly one call to sqlite3_backup_finish() for each
7088 ** successful call to sqlite3_backup_init().
7089 **
7090 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7091 **
7092 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
7093 ** [database connection] associated with the destination database 
7094 ** and the database name, respectively.
7095 ** ^The database name is "main" for the main database, "temp" for the
7096 ** temporary database, or the name specified after the AS keyword in
7097 ** an [ATTACH] statement for an attached database.
7098 ** ^The S and M arguments passed to 
7099 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7100 ** and database name of the source database, respectively.
7101 ** ^The source and destination [database connections] (parameters S and D)
7102 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7103 ** an error.
7104 **
7105 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7106 ** returned and an error code and error message are stored in the
7107 ** destination [database connection] D.
7108 ** ^The error code and message for the failed call to sqlite3_backup_init()
7109 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7110 ** [sqlite3_errmsg16()] functions.
7111 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7112 ** [sqlite3_backup] object.
7113 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7114 ** sqlite3_backup_finish() functions to perform the specified backup 
7115 ** operation.
7116 **
7117 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7118 **
7119 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
7120 ** the source and destination databases specified by [sqlite3_backup] object B.
7121 ** ^If N is negative, all remaining source pages are copied. 
7122 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7123 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7124 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7125 ** from source to destination, then it returns [SQLITE_DONE].
7126 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7127 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7128 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7129 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7130 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7131 **
7132 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7133 ** <ol>
7134 ** <li> the destination database was opened read-only, or
7135 ** <li> the destination database is using write-ahead-log journaling
7136 ** and the destination and source page sizes differ, or
7137 ** <li> the destination database is an in-memory database and the
7138 ** destination and source page sizes differ.
7139 ** </ol>)^
7140 **
7141 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7142 ** the [sqlite3_busy_handler | busy-handler function]
7143 ** is invoked (if one is specified). ^If the 
7144 ** busy-handler returns non-zero before the lock is available, then 
7145 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7146 ** sqlite3_backup_step() can be retried later. ^If the source
7147 ** [database connection]
7148 ** is being used to write to the source database when sqlite3_backup_step()
7149 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7150 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7151 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7152 ** [SQLITE_READONLY] is returned, then 
7153 ** there is no point in retrying the call to sqlite3_backup_step(). These 
7154 ** errors are considered fatal.)^  The application must accept 
7155 ** that the backup operation has failed and pass the backup operation handle 
7156 ** to the sqlite3_backup_finish() to release associated resources.
7157 **
7158 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7159 ** on the destination file. ^The exclusive lock is not released until either 
7160 ** sqlite3_backup_finish() is called or the backup operation is complete 
7161 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7162 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7163 ** lasts for the duration of the sqlite3_backup_step() call.
7164 ** ^Because the source database is not locked between calls to
7165 ** sqlite3_backup_step(), the source database may be modified mid-way
7166 ** through the backup process.  ^If the source database is modified by an
7167 ** external process or via a database connection other than the one being
7168 ** used by the backup operation, then the backup will be automatically
7169 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
7170 ** database is modified by the using the same database connection as is used
7171 ** by the backup operation, then the backup database is automatically
7172 ** updated at the same time.
7173 **
7174 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7175 **
7176 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
7177 ** application wishes to abandon the backup operation, the application
7178 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7179 ** ^The sqlite3_backup_finish() interfaces releases all
7180 ** resources associated with the [sqlite3_backup] object. 
7181 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7182 ** active write-transaction on the destination database is rolled back.
7183 ** The [sqlite3_backup] object is invalid
7184 ** and may not be used following a call to sqlite3_backup_finish().
7185 **
7186 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7187 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7188 ** sqlite3_backup_step() completed.
7189 ** ^If an out-of-memory condition or IO error occurred during any prior
7190 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7191 ** sqlite3_backup_finish() returns the corresponding [error code].
7192 **
7193 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7194 ** is not a permanent error and does not affect the return value of
7195 ** sqlite3_backup_finish().
7196 **
7197 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
7198 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7199 **
7200 ** ^Each call to sqlite3_backup_step() sets two values inside
7201 ** the [sqlite3_backup] object: the number of pages still to be backed
7202 ** up and the total number of pages in the source database file.
7203 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
7204 ** retrieve these two values, respectively.
7205 **
7206 ** ^The values returned by these functions are only updated by
7207 ** sqlite3_backup_step(). ^If the source database is modified during a backup
7208 ** operation, then the values are not updated to account for any extra
7209 ** pages that need to be updated or the size of the source database file
7210 ** changing.
7211 **
7212 ** <b>Concurrent Usage of Database Handles</b>
7213 **
7214 ** ^The source [database connection] may be used by the application for other
7215 ** purposes while a backup operation is underway or being initialized.
7216 ** ^If SQLite is compiled and configured to support threadsafe database
7217 ** connections, then the source database connection may be used concurrently
7218 ** from within other threads.
7219 **
7220 ** However, the application must guarantee that the destination 
7221 ** [database connection] is not passed to any other API (by any thread) after 
7222 ** sqlite3_backup_init() is called and before the corresponding call to
7223 ** sqlite3_backup_finish().  SQLite does not currently check to see
7224 ** if the application incorrectly accesses the destination [database connection]
7225 ** and so no error code is reported, but the operations may malfunction
7226 ** nevertheless.  Use of the destination database connection while a
7227 ** backup is in progress might also also cause a mutex deadlock.
7228 **
7229 ** If running in [shared cache mode], the application must
7230 ** guarantee that the shared cache used by the destination database
7231 ** is not accessed while the backup is running. In practice this means
7232 ** that the application must guarantee that the disk file being 
7233 ** backed up to is not accessed by any connection within the process,
7234 ** not just the specific connection that was passed to sqlite3_backup_init().
7235 **
7236 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
7237 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7238 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7239 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7240 ** same time as another thread is invoking sqlite3_backup_step() it is
7241 ** possible that they return invalid values.
7242 */
7243 SQLITE_API sqlite3_backup *sqlite3_backup_init(
7244   sqlite3 *pDest,                        /* Destination database handle */
7245   const char *zDestName,                 /* Destination database name */
7246   sqlite3 *pSource,                      /* Source database handle */
7247   const char *zSourceName                /* Source database name */
7248 );
7249 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7250 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7251 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7252 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7253
7254 /*
7255 ** CAPI3REF: Unlock Notification
7256 **
7257 ** ^When running in shared-cache mode, a database operation may fail with
7258 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7259 ** individual tables within the shared-cache cannot be obtained. See
7260 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
7261 ** ^This API may be used to register a callback that SQLite will invoke 
7262 ** when the connection currently holding the required lock relinquishes it.
7263 ** ^This API is only available if the library was compiled with the
7264 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7265 **
7266 ** See Also: [Using the SQLite Unlock Notification Feature].
7267 **
7268 ** ^Shared-cache locks are released when a database connection concludes
7269 ** its current transaction, either by committing it or rolling it back. 
7270 **
7271 ** ^When a connection (known as the blocked connection) fails to obtain a
7272 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7273 ** identity of the database connection (the blocking connection) that
7274 ** has locked the required resource is stored internally. ^After an 
7275 ** application receives an SQLITE_LOCKED error, it may call the
7276 ** sqlite3_unlock_notify() method with the blocked connection handle as 
7277 ** the first argument to register for a callback that will be invoked
7278 ** when the blocking connections current transaction is concluded. ^The
7279 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7280 ** call that concludes the blocking connections transaction.
7281 **
7282 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7283 ** there is a chance that the blocking connection will have already
7284 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7285 ** If this happens, then the specified callback is invoked immediately,
7286 ** from within the call to sqlite3_unlock_notify().)^
7287 **
7288 ** ^If the blocked connection is attempting to obtain a write-lock on a
7289 ** shared-cache table, and more than one other connection currently holds
7290 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
7291 ** the other connections to use as the blocking connection.
7292 **
7293 ** ^(There may be at most one unlock-notify callback registered by a 
7294 ** blocked connection. If sqlite3_unlock_notify() is called when the
7295 ** blocked connection already has a registered unlock-notify callback,
7296 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7297 ** called with a NULL pointer as its second argument, then any existing
7298 ** unlock-notify callback is canceled. ^The blocked connections 
7299 ** unlock-notify callback may also be canceled by closing the blocked
7300 ** connection using [sqlite3_close()].
7301 **
7302 ** The unlock-notify callback is not reentrant. If an application invokes
7303 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7304 ** crash or deadlock may be the result.
7305 **
7306 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7307 ** returns SQLITE_OK.
7308 **
7309 ** <b>Callback Invocation Details</b>
7310 **
7311 ** When an unlock-notify callback is registered, the application provides a 
7312 ** single void* pointer that is passed to the callback when it is invoked.
7313 ** However, the signature of the callback function allows SQLite to pass
7314 ** it an array of void* context pointers. The first argument passed to
7315 ** an unlock-notify callback is a pointer to an array of void* pointers,
7316 ** and the second is the number of entries in the array.
7317 **
7318 ** When a blocking connections transaction is concluded, there may be
7319 ** more than one blocked connection that has registered for an unlock-notify
7320 ** callback. ^If two or more such blocked connections have specified the
7321 ** same callback function, then instead of invoking the callback function
7322 ** multiple times, it is invoked once with the set of void* context pointers
7323 ** specified by the blocked connections bundled together into an array.
7324 ** This gives the application an opportunity to prioritize any actions 
7325 ** related to the set of unblocked database connections.
7326 **
7327 ** <b>Deadlock Detection</b>
7328 **
7329 ** Assuming that after registering for an unlock-notify callback a 
7330 ** database waits for the callback to be issued before taking any further
7331 ** action (a reasonable assumption), then using this API may cause the
7332 ** application to deadlock. For example, if connection X is waiting for
7333 ** connection Y's transaction to be concluded, and similarly connection
7334 ** Y is waiting on connection X's transaction, then neither connection
7335 ** will proceed and the system may remain deadlocked indefinitely.
7336 **
7337 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7338 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7339 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7340 ** unlock-notify callback is registered. The system is said to be in
7341 ** a deadlocked state if connection A has registered for an unlock-notify
7342 ** callback on the conclusion of connection B's transaction, and connection
7343 ** B has itself registered for an unlock-notify callback when connection
7344 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7345 ** the system is also considered to be deadlocked if connection B has
7346 ** registered for an unlock-notify callback on the conclusion of connection
7347 ** C's transaction, where connection C is waiting on connection A. ^Any
7348 ** number of levels of indirection are allowed.
7349 **
7350 ** <b>The "DROP TABLE" Exception</b>
7351 **
7352 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
7353 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7354 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7355 ** SQLite checks if there are any currently executing SELECT statements
7356 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7357 ** returned. In this case there is no "blocking connection", so invoking
7358 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7359 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7360 ** or "DROP INDEX" query, an infinite loop might be the result.
7361 **
7362 ** One way around this problem is to check the extended error code returned
7363 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7364 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7365 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
7366 ** SQLITE_LOCKED.)^
7367 */
7368 SQLITE_API int sqlite3_unlock_notify(
7369   sqlite3 *pBlocked,                          /* Waiting connection */
7370   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7371   void *pNotifyArg                            /* Argument to pass to xNotify */
7372 );
7373
7374
7375 /*
7376 ** CAPI3REF: String Comparison
7377 **
7378 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7379 ** and extensions to compare the contents of two buffers containing UTF-8
7380 ** strings in a case-independent fashion, using the same definition of "case
7381 ** independence" that SQLite uses internally when comparing identifiers.
7382 */
7383 SQLITE_API int sqlite3_stricmp(const char *, const char *);
7384 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7385
7386 /*
7387 ** CAPI3REF: Error Logging Interface
7388 **
7389 ** ^The [sqlite3_log()] interface writes a message into the error log
7390 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7391 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7392 ** used with [sqlite3_snprintf()] to generate the final output string.
7393 **
7394 ** The sqlite3_log() interface is intended for use by extensions such as
7395 ** virtual tables, collating functions, and SQL functions.  While there is
7396 ** nothing to prevent an application from calling sqlite3_log(), doing so
7397 ** is considered bad form.
7398 **
7399 ** The zFormat string must not be NULL.
7400 **
7401 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7402 ** will not use dynamically allocated memory.  The log message is stored in
7403 ** a fixed-length buffer on the stack.  If the log message is longer than
7404 ** a few hundred characters, it will be truncated to the length of the
7405 ** buffer.
7406 */
7407 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7408
7409 /*
7410 ** CAPI3REF: Write-Ahead Log Commit Hook
7411 **
7412 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7413 ** will be invoked each time a database connection commits data to a
7414 ** [write-ahead log] (i.e. whenever a transaction is committed in
7415 ** [journal_mode | journal_mode=WAL mode]). 
7416 **
7417 ** ^The callback is invoked by SQLite after the commit has taken place and 
7418 ** the associated write-lock on the database released, so the implementation 
7419 ** may read, write or [checkpoint] the database as required.
7420 **
7421 ** ^The first parameter passed to the callback function when it is invoked
7422 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7423 ** registering the callback. ^The second is a copy of the database handle.
7424 ** ^The third parameter is the name of the database that was written to -
7425 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7426 ** is the number of pages currently in the write-ahead log file,
7427 ** including those that were just committed.
7428 **
7429 ** The callback function should normally return [SQLITE_OK].  ^If an error
7430 ** code is returned, that error will propagate back up through the
7431 ** SQLite code base to cause the statement that provoked the callback
7432 ** to report an error, though the commit will have still occurred. If the
7433 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7434 ** that does not correspond to any valid SQLite error code, the results
7435 ** are undefined.
7436 **
7437 ** A single database handle may have at most a single write-ahead log callback 
7438 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7439 ** previously registered write-ahead log callback. ^Note that the
7440 ** [sqlite3_wal_autocheckpoint()] interface and the
7441 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7442 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7443 */
7444 SQLITE_API void *sqlite3_wal_hook(
7445   sqlite3*, 
7446   int(*)(void *,sqlite3*,const char*,int),
7447   void*
7448 );
7449
7450 /*
7451 ** CAPI3REF: Configure an auto-checkpoint
7452 **
7453 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7454 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7455 ** to automatically [checkpoint]
7456 ** after committing a transaction if there are N or
7457 ** more frames in the [write-ahead log] file.  ^Passing zero or 
7458 ** a negative value as the nFrame parameter disables automatic
7459 ** checkpoints entirely.
7460 **
7461 ** ^The callback registered by this function replaces any existing callback
7462 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7463 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7464 ** configured by this function.
7465 **
7466 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7467 ** from SQL.
7468 **
7469 ** ^Every new [database connection] defaults to having the auto-checkpoint
7470 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7471 ** pages.  The use of this interface
7472 ** is only necessary if the default setting is found to be suboptimal
7473 ** for a particular application.
7474 */
7475 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7476
7477 /*
7478 ** CAPI3REF: Checkpoint a database
7479 **
7480 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7481 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7482 ** empty string, then a checkpoint is run on all databases of
7483 ** connection D.  ^If the database connection D is not in
7484 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7485 **
7486 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7487 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7488 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7489 ** run whenever the WAL reaches a certain size threshold.
7490 **
7491 ** See also: [sqlite3_wal_checkpoint_v2()]
7492 */
7493 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7494
7495 /*
7496 ** CAPI3REF: Checkpoint a database
7497 **
7498 ** Run a checkpoint operation on WAL database zDb attached to database 
7499 ** handle db. The specific operation is determined by the value of the 
7500 ** eMode parameter:
7501 **
7502 ** <dl>
7503 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7504 **   Checkpoint as many frames as possible without waiting for any database 
7505 **   readers or writers to finish. Sync the db file if all frames in the log
7506 **   are checkpointed. This mode is the same as calling 
7507 **   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7508 **
7509 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7510 **   This mode blocks (calls the busy-handler callback) until there is no
7511 **   database writer and all readers are reading from the most recent database
7512 **   snapshot. It then checkpoints all frames in the log file and syncs the
7513 **   database file. This call blocks database writers while it is running,
7514 **   but not database readers.
7515 **
7516 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7517 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after 
7518 **   checkpointing the log file it blocks (calls the busy-handler callback)
7519 **   until all readers are reading from the database file only. This ensures 
7520 **   that the next client to write to the database file restarts the log file 
7521 **   from the beginning. This call blocks database writers while it is running,
7522 **   but not database readers.
7523 ** </dl>
7524 **
7525 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7526 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7527 ** the total number of checkpointed frames (including any that were already
7528 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7529 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7530 ** If no values are available because of an error, they are both set to -1
7531 ** before returning to communicate this to the caller.
7532 **
7533 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7534 ** any other process is running a checkpoint operation at the same time, the 
7535 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a 
7536 ** busy-handler configured, it will not be invoked in this case.
7537 **
7538 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive 
7539 ** "writer" lock on the database file. If the writer lock cannot be obtained
7540 ** immediately, and a busy-handler is configured, it is invoked and the writer
7541 ** lock retried until either the busy-handler returns 0 or the lock is
7542 ** successfully obtained. The busy-handler is also invoked while waiting for
7543 ** database readers as described above. If the busy-handler returns 0 before
7544 ** the writer lock is obtained or while waiting for database readers, the
7545 ** checkpoint operation proceeds from that point in the same way as 
7546 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
7547 ** without blocking any further. SQLITE_BUSY is returned in this case.
7548 **
7549 ** If parameter zDb is NULL or points to a zero length string, then the
7550 ** specified operation is attempted on all WAL databases. In this case the
7551 ** values written to output parameters *pnLog and *pnCkpt are undefined. If 
7552 ** an SQLITE_BUSY error is encountered when processing one or more of the 
7553 ** attached WAL databases, the operation is still attempted on any remaining 
7554 ** attached databases and SQLITE_BUSY is returned to the caller. If any other 
7555 ** error occurs while processing an attached database, processing is abandoned 
7556 ** and the error code returned to the caller immediately. If no error 
7557 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
7558 ** databases, SQLITE_OK is returned.
7559 **
7560 ** If database zDb is the name of an attached database that is not in WAL
7561 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7562 ** zDb is not NULL (or a zero length string) and is not the name of any
7563 ** attached database, SQLITE_ERROR is returned to the caller.
7564 */
7565 SQLITE_API int sqlite3_wal_checkpoint_v2(
7566   sqlite3 *db,                    /* Database handle */
7567   const char *zDb,                /* Name of attached database (or NULL) */
7568   int eMode,                      /* SQLITE_CHECKPOINT_* value */
7569   int *pnLog,                     /* OUT: Size of WAL log in frames */
7570   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7571 );
7572
7573 /*
7574 ** CAPI3REF: Checkpoint operation parameters
7575 **
7576 ** These constants can be used as the 3rd parameter to
7577 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7578 ** documentation for additional information about the meaning and use of
7579 ** each of these values.
7580 */
7581 #define SQLITE_CHECKPOINT_PASSIVE 0
7582 #define SQLITE_CHECKPOINT_FULL    1
7583 #define SQLITE_CHECKPOINT_RESTART 2
7584
7585 /*
7586 ** CAPI3REF: Virtual Table Interface Configuration
7587 **
7588 ** This function may be called by either the [xConnect] or [xCreate] method
7589 ** of a [virtual table] implementation to configure
7590 ** various facets of the virtual table interface.
7591 **
7592 ** If this interface is invoked outside the context of an xConnect or
7593 ** xCreate virtual table method then the behavior is undefined.
7594 **
7595 ** At present, there is only one option that may be configured using
7596 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7597 ** may be added in the future.
7598 */
7599 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7600
7601 /*
7602 ** CAPI3REF: Virtual Table Configuration Options
7603 **
7604 ** These macros define the various options to the
7605 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7606 ** can use to customize and optimize their behavior.
7607 **
7608 ** <dl>
7609 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7610 ** <dd>Calls of the form
7611 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7612 ** where X is an integer.  If X is zero, then the [virtual table] whose
7613 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7614 ** support constraints.  In this configuration (which is the default) if
7615 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7616 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7617 ** specified as part of the users SQL statement, regardless of the actual
7618 ** ON CONFLICT mode specified.
7619 **
7620 ** If X is non-zero, then the virtual table implementation guarantees
7621 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7622 ** any modifications to internal or persistent data structures have been made.
7623 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
7624 ** is able to roll back a statement or database transaction, and abandon
7625 ** or continue processing the current SQL statement as appropriate. 
7626 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7627 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7628 ** had been ABORT.
7629 **
7630 ** Virtual table implementations that are required to handle OR REPLACE
7631 ** must do so within the [xUpdate] method. If a call to the 
7632 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
7633 ** CONFLICT policy is REPLACE, the virtual table implementation should 
7634 ** silently replace the appropriate rows within the xUpdate callback and
7635 ** return SQLITE_OK. Or, if this is not possible, it may return
7636 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
7637 ** constraint handling.
7638 ** </dl>
7639 */
7640 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7641
7642 /*
7643 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7644 **
7645 ** This function may only be called from within a call to the [xUpdate] method
7646 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7647 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7648 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7649 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7650 ** [virtual table].
7651 */
7652 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7653
7654 /*
7655 ** CAPI3REF: Conflict resolution modes
7656 **
7657 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7658 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7659 ** is for the SQL statement being evaluated.
7660 **
7661 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7662 ** return value from the [sqlite3_set_authorizer()] callback and that
7663 ** [SQLITE_ABORT] is also a [result code].
7664 */
7665 #define SQLITE_ROLLBACK 1
7666 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7667 #define SQLITE_FAIL     3
7668 /* #define SQLITE_ABORT 4  // Also an error code */
7669 #define SQLITE_REPLACE  5
7670
7671
7672
7673 /*
7674 ** Undo the hack that converts floating point types to integer for
7675 ** builds on processors without floating point support.
7676 */
7677 #ifdef SQLITE_OMIT_FLOATING_POINT
7678 # undef double
7679 #endif
7680
7681 #if 0
7682 }  /* End of the 'extern "C"' block */
7683 #endif
7684 #endif
7685
7686 /*
7687 ** 2010 August 30
7688 **
7689 ** The author disclaims copyright to this source code.  In place of
7690 ** a legal notice, here is a blessing:
7691 **
7692 **    May you do good and not evil.
7693 **    May you find forgiveness for yourself and forgive others.
7694 **    May you share freely, never taking more than you give.
7695 **
7696 *************************************************************************
7697 */
7698
7699 #ifndef _SQLITE3RTREE_H_
7700 #define _SQLITE3RTREE_H_
7701
7702
7703 #if 0
7704 extern "C" {
7705 #endif
7706
7707 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7708
7709 /*
7710 ** Register a geometry callback named zGeom that can be used as part of an
7711 ** R-Tree geometry query as follows:
7712 **
7713 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7714 */
7715 SQLITE_API int sqlite3_rtree_geometry_callback(
7716   sqlite3 *db,
7717   const char *zGeom,
7718 #ifdef SQLITE_RTREE_INT_ONLY
7719   int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
7720 #else
7721   int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
7722 #endif
7723   void *pContext
7724 );
7725
7726
7727 /*
7728 ** A pointer to a structure of the following type is passed as the first
7729 ** argument to callbacks registered using rtree_geometry_callback().
7730 */
7731 struct sqlite3_rtree_geometry {
7732   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7733   int nParam;                     /* Size of array aParam[] */
7734   double *aParam;                 /* Parameters passed to SQL geom function */
7735   void *pUser;                    /* Callback implementation user data */
7736   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7737 };
7738
7739
7740 #if 0
7741 }  /* end of the 'extern "C"' block */
7742 #endif
7743
7744 #endif  /* ifndef _SQLITE3RTREE_H_ */
7745
7746
7747 /************** End of sqlite3.h *********************************************/
7748 /************** Continuing where we left off in sqliteInt.h ******************/
7749 /************** Include hash.h in the middle of sqliteInt.h ******************/
7750 /************** Begin file hash.h ********************************************/
7751 /*
7752 ** 2001 September 22
7753 **
7754 ** The author disclaims copyright to this source code.  In place of
7755 ** a legal notice, here is a blessing:
7756 **
7757 **    May you do good and not evil.
7758 **    May you find forgiveness for yourself and forgive others.
7759 **    May you share freely, never taking more than you give.
7760 **
7761 *************************************************************************
7762 ** This is the header file for the generic hash-table implementation
7763 ** used in SQLite.
7764 */
7765 #ifndef _SQLITE_HASH_H_
7766 #define _SQLITE_HASH_H_
7767
7768 /* Forward declarations of structures. */
7769 typedef struct Hash Hash;
7770 typedef struct HashElem HashElem;
7771
7772 /* A complete hash table is an instance of the following structure.
7773 ** The internals of this structure are intended to be opaque -- client
7774 ** code should not attempt to access or modify the fields of this structure
7775 ** directly.  Change this structure only by using the routines below.
7776 ** However, some of the "procedures" and "functions" for modifying and
7777 ** accessing this structure are really macros, so we can't really make
7778 ** this structure opaque.
7779 **
7780 ** All elements of the hash table are on a single doubly-linked list.
7781 ** Hash.first points to the head of this list.
7782 **
7783 ** There are Hash.htsize buckets.  Each bucket points to a spot in
7784 ** the global doubly-linked list.  The contents of the bucket are the
7785 ** element pointed to plus the next _ht.count-1 elements in the list.
7786 **
7787 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7788 ** by a linear search of the global list.  For small tables, the 
7789 ** Hash.ht table is never allocated because if there are few elements
7790 ** in the table, it is faster to do a linear search than to manage
7791 ** the hash table.
7792 */
7793 struct Hash {
7794   unsigned int htsize;      /* Number of buckets in the hash table */
7795   unsigned int count;       /* Number of entries in this table */
7796   HashElem *first;          /* The first element of the array */
7797   struct _ht {              /* the hash table */
7798     int count;                 /* Number of entries with this hash */
7799     HashElem *chain;           /* Pointer to first entry with this hash */
7800   } *ht;
7801 };
7802
7803 /* Each element in the hash table is an instance of the following 
7804 ** structure.  All elements are stored on a single doubly-linked list.
7805 **
7806 ** Again, this structure is intended to be opaque, but it can't really
7807 ** be opaque because it is used by macros.
7808 */
7809 struct HashElem {
7810   HashElem *next, *prev;       /* Next and previous elements in the table */
7811   void *data;                  /* Data associated with this element */
7812   const char *pKey; int nKey;  /* Key associated with this element */
7813 };
7814
7815 /*
7816 ** Access routines.  To delete, insert a NULL pointer.
7817 */
7818 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7819 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7820 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7821 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7822
7823 /*
7824 ** Macros for looping over all elements of a hash table.  The idiom is
7825 ** like this:
7826 **
7827 **   Hash h;
7828 **   HashElem *p;
7829 **   ...
7830 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7831 **     SomeStructure *pData = sqliteHashData(p);
7832 **     // do something with pData
7833 **   }
7834 */
7835 #define sqliteHashFirst(H)  ((H)->first)
7836 #define sqliteHashNext(E)   ((E)->next)
7837 #define sqliteHashData(E)   ((E)->data)
7838 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7839 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7840
7841 /*
7842 ** Number of entries in a hash table
7843 */
7844 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7845
7846 #endif /* _SQLITE_HASH_H_ */
7847
7848 /************** End of hash.h ************************************************/
7849 /************** Continuing where we left off in sqliteInt.h ******************/
7850 /************** Include parse.h in the middle of sqliteInt.h *****************/
7851 /************** Begin file parse.h *******************************************/
7852 #define TK_SEMI                            1
7853 #define TK_EXPLAIN                         2
7854 #define TK_QUERY                           3
7855 #define TK_PLAN                            4
7856 #define TK_BEGIN                           5
7857 #define TK_TRANSACTION                     6
7858 #define TK_DEFERRED                        7
7859 #define TK_IMMEDIATE                       8
7860 #define TK_EXCLUSIVE                       9
7861 #define TK_COMMIT                         10
7862 #define TK_END                            11
7863 #define TK_ROLLBACK                       12
7864 #define TK_SAVEPOINT                      13
7865 #define TK_RELEASE                        14
7866 #define TK_TO                             15
7867 #define TK_TABLE                          16
7868 #define TK_CREATE                         17
7869 #define TK_IF                             18
7870 #define TK_NOT                            19
7871 #define TK_EXISTS                         20
7872 #define TK_TEMP                           21
7873 #define TK_LP                             22
7874 #define TK_RP                             23
7875 #define TK_AS                             24
7876 #define TK_COMMA                          25
7877 #define TK_ID                             26
7878 #define TK_INDEXED                        27
7879 #define TK_ABORT                          28
7880 #define TK_ACTION                         29
7881 #define TK_AFTER                          30
7882 #define TK_ANALYZE                        31
7883 #define TK_ASC                            32
7884 #define TK_ATTACH                         33
7885 #define TK_BEFORE                         34
7886 #define TK_BY                             35
7887 #define TK_CASCADE                        36
7888 #define TK_CAST                           37
7889 #define TK_COLUMNKW                       38
7890 #define TK_CONFLICT                       39
7891 #define TK_DATABASE                       40
7892 #define TK_DESC                           41
7893 #define TK_DETACH                         42
7894 #define TK_EACH                           43
7895 #define TK_FAIL                           44
7896 #define TK_FOR                            45
7897 #define TK_IGNORE                         46
7898 #define TK_INITIALLY                      47
7899 #define TK_INSTEAD                        48
7900 #define TK_LIKE_KW                        49
7901 #define TK_MATCH                          50
7902 #define TK_NO                             51
7903 #define TK_KEY                            52
7904 #define TK_OF                             53
7905 #define TK_OFFSET                         54
7906 #define TK_PRAGMA                         55
7907 #define TK_RAISE                          56
7908 #define TK_REPLACE                        57
7909 #define TK_RESTRICT                       58
7910 #define TK_ROW                            59
7911 #define TK_TRIGGER                        60
7912 #define TK_VACUUM                         61
7913 #define TK_VIEW                           62
7914 #define TK_VIRTUAL                        63
7915 #define TK_REINDEX                        64
7916 #define TK_RENAME                         65
7917 #define TK_CTIME_KW                       66
7918 #define TK_ANY                            67
7919 #define TK_OR                             68
7920 #define TK_AND                            69
7921 #define TK_IS                             70
7922 #define TK_BETWEEN                        71
7923 #define TK_IN                             72
7924 #define TK_ISNULL                         73
7925 #define TK_NOTNULL                        74
7926 #define TK_NE                             75
7927 #define TK_EQ                             76
7928 #define TK_GT                             77
7929 #define TK_LE                             78
7930 #define TK_LT                             79
7931 #define TK_GE                             80
7932 #define TK_ESCAPE                         81
7933 #define TK_BITAND                         82
7934 #define TK_BITOR                          83
7935 #define TK_LSHIFT                         84
7936 #define TK_RSHIFT                         85
7937 #define TK_PLUS                           86
7938 #define TK_MINUS                          87
7939 #define TK_STAR                           88
7940 #define TK_SLASH                          89
7941 #define TK_REM                            90
7942 #define TK_CONCAT                         91
7943 #define TK_COLLATE                        92
7944 #define TK_BITNOT                         93
7945 #define TK_STRING                         94
7946 #define TK_JOIN_KW                        95
7947 #define TK_CONSTRAINT                     96
7948 #define TK_DEFAULT                        97
7949 #define TK_NULL                           98
7950 #define TK_PRIMARY                        99
7951 #define TK_UNIQUE                         100
7952 #define TK_CHECK                          101
7953 #define TK_REFERENCES                     102
7954 #define TK_AUTOINCR                       103
7955 #define TK_ON                             104
7956 #define TK_INSERT                         105
7957 #define TK_DELETE                         106
7958 #define TK_UPDATE                         107
7959 #define TK_SET                            108
7960 #define TK_DEFERRABLE                     109
7961 #define TK_FOREIGN                        110
7962 #define TK_DROP                           111
7963 #define TK_UNION                          112
7964 #define TK_ALL                            113
7965 #define TK_EXCEPT                         114
7966 #define TK_INTERSECT                      115
7967 #define TK_SELECT                         116
7968 #define TK_DISTINCT                       117
7969 #define TK_DOT                            118
7970 #define TK_FROM                           119
7971 #define TK_JOIN                           120
7972 #define TK_USING                          121
7973 #define TK_ORDER                          122
7974 #define TK_GROUP                          123
7975 #define TK_HAVING                         124
7976 #define TK_LIMIT                          125
7977 #define TK_WHERE                          126
7978 #define TK_INTO                           127
7979 #define TK_VALUES                         128
7980 #define TK_INTEGER                        129
7981 #define TK_FLOAT                          130
7982 #define TK_BLOB                           131
7983 #define TK_REGISTER                       132
7984 #define TK_VARIABLE                       133
7985 #define TK_CASE                           134
7986 #define TK_WHEN                           135
7987 #define TK_THEN                           136
7988 #define TK_ELSE                           137
7989 #define TK_INDEX                          138
7990 #define TK_ALTER                          139
7991 #define TK_ADD                            140
7992 #define TK_TO_TEXT                        141
7993 #define TK_TO_BLOB                        142
7994 #define TK_TO_NUMERIC                     143
7995 #define TK_TO_INT                         144
7996 #define TK_TO_REAL                        145
7997 #define TK_ISNOT                          146
7998 #define TK_END_OF_FILE                    147
7999 #define TK_ILLEGAL                        148
8000 #define TK_SPACE                          149
8001 #define TK_UNCLOSED_STRING                150
8002 #define TK_FUNCTION                       151
8003 #define TK_COLUMN                         152
8004 #define TK_AGG_FUNCTION                   153
8005 #define TK_AGG_COLUMN                     154
8006 #define TK_CONST_FUNC                     155
8007 #define TK_UMINUS                         156
8008 #define TK_UPLUS                          157
8009
8010 /************** End of parse.h ***********************************************/
8011 /************** Continuing where we left off in sqliteInt.h ******************/
8012 #include <stdio.h>
8013 #include <stdlib.h>
8014 #include <string.h>
8015 #include <assert.h>
8016 #include <stddef.h>
8017
8018 /*
8019 ** If compiling for a processor that lacks floating point support,
8020 ** substitute integer for floating-point
8021 */
8022 #ifdef SQLITE_OMIT_FLOATING_POINT
8023 # define double sqlite_int64
8024 # define float sqlite_int64
8025 # define LONGDOUBLE_TYPE sqlite_int64
8026 # ifndef SQLITE_BIG_DBL
8027 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8028 # endif
8029 # define SQLITE_OMIT_DATETIME_FUNCS 1
8030 # define SQLITE_OMIT_TRACE 1
8031 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8032 # undef SQLITE_HAVE_ISNAN
8033 #endif
8034 #ifndef SQLITE_BIG_DBL
8035 # define SQLITE_BIG_DBL (1e99)
8036 #endif
8037
8038 /*
8039 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8040 ** afterward. Having this macro allows us to cause the C compiler 
8041 ** to omit code used by TEMP tables without messy #ifndef statements.
8042 */
8043 #ifdef SQLITE_OMIT_TEMPDB
8044 #define OMIT_TEMPDB 1
8045 #else
8046 #define OMIT_TEMPDB 0
8047 #endif
8048
8049 /*
8050 ** The "file format" number is an integer that is incremented whenever
8051 ** the VDBE-level file format changes.  The following macros define the
8052 ** the default file format for new databases and the maximum file format
8053 ** that the library can read.
8054 */
8055 #define SQLITE_MAX_FILE_FORMAT 4
8056 #ifndef SQLITE_DEFAULT_FILE_FORMAT
8057 # define SQLITE_DEFAULT_FILE_FORMAT 4
8058 #endif
8059
8060 /*
8061 ** Determine whether triggers are recursive by default.  This can be
8062 ** changed at run-time using a pragma.
8063 */
8064 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8065 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8066 #endif
8067
8068 /*
8069 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8070 ** on the command-line
8071 */
8072 #ifndef SQLITE_TEMP_STORE
8073 # define SQLITE_TEMP_STORE 1
8074 #endif
8075
8076 /*
8077 ** GCC does not define the offsetof() macro so we'll have to do it
8078 ** ourselves.
8079 */
8080 #ifndef offsetof
8081 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8082 #endif
8083
8084 /*
8085 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
8086 ** not, there are still machines out there that use EBCDIC.)
8087 */
8088 #if 'A' == '\301'
8089 # define SQLITE_EBCDIC 1
8090 #else
8091 # define SQLITE_ASCII 1
8092 #endif
8093
8094 /*
8095 ** Integers of known sizes.  These typedefs might change for architectures
8096 ** where the sizes very.  Preprocessor macros are available so that the
8097 ** types can be conveniently redefined at compile-type.  Like this:
8098 **
8099 **         cc '-DUINTPTR_TYPE=long long int' ...
8100 */
8101 #ifndef UINT32_TYPE
8102 # ifdef HAVE_UINT32_T
8103 #  define UINT32_TYPE uint32_t
8104 # else
8105 #  define UINT32_TYPE unsigned int
8106 # endif
8107 #endif
8108 #ifndef UINT16_TYPE
8109 # ifdef HAVE_UINT16_T
8110 #  define UINT16_TYPE uint16_t
8111 # else
8112 #  define UINT16_TYPE unsigned short int
8113 # endif
8114 #endif
8115 #ifndef INT16_TYPE
8116 # ifdef HAVE_INT16_T
8117 #  define INT16_TYPE int16_t
8118 # else
8119 #  define INT16_TYPE short int
8120 # endif
8121 #endif
8122 #ifndef UINT8_TYPE
8123 # ifdef HAVE_UINT8_T
8124 #  define UINT8_TYPE uint8_t
8125 # else
8126 #  define UINT8_TYPE unsigned char
8127 # endif
8128 #endif
8129 #ifndef INT8_TYPE
8130 # ifdef HAVE_INT8_T
8131 #  define INT8_TYPE int8_t
8132 # else
8133 #  define INT8_TYPE signed char
8134 # endif
8135 #endif
8136 #ifndef LONGDOUBLE_TYPE
8137 # define LONGDOUBLE_TYPE long double
8138 #endif
8139 typedef sqlite_int64 i64;          /* 8-byte signed integer */
8140 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
8141 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
8142 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
8143 typedef INT16_TYPE i16;            /* 2-byte signed integer */
8144 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
8145 typedef INT8_TYPE i8;              /* 1-byte signed integer */
8146
8147 /*
8148 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8149 ** that can be stored in a u32 without loss of data.  The value
8150 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
8151 ** have to specify the value in the less intuitive manner shown:
8152 */
8153 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
8154
8155 /*
8156 ** The datatype used to store estimates of the number of rows in a
8157 ** table or index.  This is an unsigned integer type.  For 99.9% of
8158 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
8159 ** can be used at compile-time if desired.
8160 */
8161 #ifdef SQLITE_64BIT_STATS
8162  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
8163 #else
8164  typedef u32 tRowcnt;    /* 32-bit is the default */
8165 #endif
8166
8167 /*
8168 ** Macros to determine whether the machine is big or little endian,
8169 ** evaluated at runtime.
8170 */
8171 #ifdef SQLITE_AMALGAMATION
8172 SQLITE_PRIVATE const int sqlite3one = 1;
8173 #else
8174 SQLITE_PRIVATE const int sqlite3one;
8175 #endif
8176 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
8177                              || defined(__x86_64) || defined(__x86_64__)
8178 # define SQLITE_BIGENDIAN    0
8179 # define SQLITE_LITTLEENDIAN 1
8180 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
8181 #else
8182 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
8183 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8184 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8185 #endif
8186
8187 /*
8188 ** Constants for the largest and smallest possible 64-bit signed integers.
8189 ** These macros are designed to work correctly on both 32-bit and 64-bit
8190 ** compilers.
8191 */
8192 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
8193 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8194
8195 /* 
8196 ** Round up a number to the next larger multiple of 8.  This is used
8197 ** to force 8-byte alignment on 64-bit architectures.
8198 */
8199 #define ROUND8(x)     (((x)+7)&~7)
8200
8201 /*
8202 ** Round down to the nearest multiple of 8
8203 */
8204 #define ROUNDDOWN8(x) ((x)&~7)
8205
8206 /*
8207 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
8208 ** macro is used only within assert() to verify that the code gets
8209 ** all alignment restrictions correct.
8210 **
8211 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8212 ** underlying malloc() implemention might return us 4-byte aligned
8213 ** pointers.  In that case, only verify 4-byte alignment.
8214 */
8215 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8216 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
8217 #else
8218 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
8219 #endif
8220
8221
8222 /*
8223 ** An instance of the following structure is used to store the busy-handler
8224 ** callback for a given sqlite handle. 
8225 **
8226 ** The sqlite.busyHandler member of the sqlite struct contains the busy
8227 ** callback for the database handle. Each pager opened via the sqlite
8228 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8229 ** callback is currently invoked only from within pager.c.
8230 */
8231 typedef struct BusyHandler BusyHandler;
8232 struct BusyHandler {
8233   int (*xFunc)(void *,int);  /* The busy callback */
8234   void *pArg;                /* First arg to busy callback */
8235   int nBusy;                 /* Incremented with each busy call */
8236 };
8237
8238 /*
8239 ** Name of the master database table.  The master database table
8240 ** is a special table that holds the names and attributes of all
8241 ** user tables and indices.
8242 */
8243 #define MASTER_NAME       "sqlite_master"
8244 #define TEMP_MASTER_NAME  "sqlite_temp_master"
8245
8246 /*
8247 ** The root-page of the master database table.
8248 */
8249 #define MASTER_ROOT       1
8250
8251 /*
8252 ** The name of the schema table.
8253 */
8254 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8255
8256 /*
8257 ** A convenience macro that returns the number of elements in
8258 ** an array.
8259 */
8260 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
8261
8262 /*
8263 ** Determine if the argument is a power of two
8264 */
8265 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
8266
8267 /*
8268 ** The following value as a destructor means to use sqlite3DbFree().
8269 ** The sqlite3DbFree() routine requires two parameters instead of the 
8270 ** one parameter that destructors normally want.  So we have to introduce 
8271 ** this magic value that the code knows to handle differently.  Any 
8272 ** pointer will work here as long as it is distinct from SQLITE_STATIC
8273 ** and SQLITE_TRANSIENT.
8274 */
8275 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
8276
8277 /*
8278 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8279 ** not support Writable Static Data (WSD) such as global and static variables.
8280 ** All variables must either be on the stack or dynamically allocated from
8281 ** the heap.  When WSD is unsupported, the variable declarations scattered
8282 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
8283 ** macro is used for this purpose.  And instead of referencing the variable
8284 ** directly, we use its constant as a key to lookup the run-time allocated
8285 ** buffer that holds real variable.  The constant is also the initializer
8286 ** for the run-time allocated buffer.
8287 **
8288 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8289 ** macros become no-ops and have zero performance impact.
8290 */
8291 #ifdef SQLITE_OMIT_WSD
8292   #define SQLITE_WSD const
8293   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8294   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8295 SQLITE_API   int sqlite3_wsd_init(int N, int J);
8296 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
8297 #else
8298   #define SQLITE_WSD 
8299   #define GLOBAL(t,v) v
8300   #define sqlite3GlobalConfig sqlite3Config
8301 #endif
8302
8303 /*
8304 ** The following macros are used to suppress compiler warnings and to
8305 ** make it clear to human readers when a function parameter is deliberately 
8306 ** left unused within the body of a function. This usually happens when
8307 ** a function is called via a function pointer. For example the 
8308 ** implementation of an SQL aggregate step callback may not use the
8309 ** parameter indicating the number of arguments passed to the aggregate,
8310 ** if it knows that this is enforced elsewhere.
8311 **
8312 ** When a function parameter is not used at all within the body of a function,
8313 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8314 ** However, these macros may also be used to suppress warnings related to
8315 ** parameters that may or may not be used depending on compilation options.
8316 ** For example those parameters only used in assert() statements. In these
8317 ** cases the parameters are named as per the usual conventions.
8318 */
8319 #define UNUSED_PARAMETER(x) (void)(x)
8320 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8321
8322 /*
8323 ** Forward references to structures
8324 */
8325 typedef struct AggInfo AggInfo;
8326 typedef struct AuthContext AuthContext;
8327 typedef struct AutoincInfo AutoincInfo;
8328 typedef struct Bitvec Bitvec;
8329 typedef struct CollSeq CollSeq;
8330 typedef struct Column Column;
8331 typedef struct Db Db;
8332 typedef struct Schema Schema;
8333 typedef struct Expr Expr;
8334 typedef struct ExprList ExprList;
8335 typedef struct ExprSpan ExprSpan;
8336 typedef struct FKey FKey;
8337 typedef struct FuncDestructor FuncDestructor;
8338 typedef struct FuncDef FuncDef;
8339 typedef struct FuncDefHash FuncDefHash;
8340 typedef struct IdList IdList;
8341 typedef struct Index Index;
8342 typedef struct IndexSample IndexSample;
8343 typedef struct KeyClass KeyClass;
8344 typedef struct KeyInfo KeyInfo;
8345 typedef struct Lookaside Lookaside;
8346 typedef struct LookasideSlot LookasideSlot;
8347 typedef struct Module Module;
8348 typedef struct NameContext NameContext;
8349 typedef struct Parse Parse;
8350 typedef struct RowSet RowSet;
8351 typedef struct Savepoint Savepoint;
8352 typedef struct Select Select;
8353 typedef struct SelectDest SelectDest;
8354 typedef struct SrcList SrcList;
8355 typedef struct StrAccum StrAccum;
8356 typedef struct Table Table;
8357 typedef struct TableLock TableLock;
8358 typedef struct Token Token;
8359 typedef struct Trigger Trigger;
8360 typedef struct TriggerPrg TriggerPrg;
8361 typedef struct TriggerStep TriggerStep;
8362 typedef struct UnpackedRecord UnpackedRecord;
8363 typedef struct VTable VTable;
8364 typedef struct VtabCtx VtabCtx;
8365 typedef struct Walker Walker;
8366 typedef struct WherePlan WherePlan;
8367 typedef struct WhereInfo WhereInfo;
8368 typedef struct WhereLevel WhereLevel;
8369
8370 /*
8371 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
8372 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8373 ** pointer types (i.e. FuncDef) defined above.
8374 */
8375 /************** Include btree.h in the middle of sqliteInt.h *****************/
8376 /************** Begin file btree.h *******************************************/
8377 /*
8378 ** 2001 September 15
8379 **
8380 ** The author disclaims copyright to this source code.  In place of
8381 ** a legal notice, here is a blessing:
8382 **
8383 **    May you do good and not evil.
8384 **    May you find forgiveness for yourself and forgive others.
8385 **    May you share freely, never taking more than you give.
8386 **
8387 *************************************************************************
8388 ** This header file defines the interface that the sqlite B-Tree file
8389 ** subsystem.  See comments in the source code for a detailed description
8390 ** of what each interface routine does.
8391 */
8392 #ifndef _BTREE_H_
8393 #define _BTREE_H_
8394
8395 /* TODO: This definition is just included so other modules compile. It
8396 ** needs to be revisited.
8397 */
8398 #define SQLITE_N_BTREE_META 10
8399
8400 /*
8401 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8402 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8403 */
8404 #ifndef SQLITE_DEFAULT_AUTOVACUUM
8405   #define SQLITE_DEFAULT_AUTOVACUUM 0
8406 #endif
8407
8408 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8409 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8410 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8411
8412 /*
8413 ** Forward declarations of structure
8414 */
8415 typedef struct Btree Btree;
8416 typedef struct BtCursor BtCursor;
8417 typedef struct BtShared BtShared;
8418
8419
8420 SQLITE_PRIVATE int sqlite3BtreeOpen(
8421   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
8422   const char *zFilename,   /* Name of database file to open */
8423   sqlite3 *db,             /* Associated database connection */
8424   Btree **ppBtree,         /* Return open Btree* here */
8425   int flags,               /* Flags */
8426   int vfsFlags             /* Flags passed through to VFS open */
8427 );
8428
8429 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8430 ** following values.
8431 **
8432 ** NOTE:  These values must match the corresponding PAGER_ values in
8433 ** pager.h.
8434 */
8435 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8436 #define BTREE_MEMORY        2  /* This is an in-memory DB */
8437 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
8438 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
8439
8440 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8441 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8442 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
8443 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8444 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8445 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8446 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8447 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8448 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8449 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8450 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
8451 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
8452 #endif
8453 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8454 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8455 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8456 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8457 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8458 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8459 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
8460 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8461 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8462 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8463 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8464 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8465 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8466 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8467 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8468 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8469
8470 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8471 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8472 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8473
8474 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8475
8476 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8477 ** of the flags shown below.
8478 **
8479 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8480 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8481 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8482 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8483 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8484 ** indices.)
8485 */
8486 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8487 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8488
8489 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8490 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8491 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8492
8493 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8494 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8495
8496 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
8497
8498 /*
8499 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8500 ** should be one of the following values. The integer values are assigned 
8501 ** to constants so that the offset of the corresponding field in an
8502 ** SQLite database header may be found using the following formula:
8503 **
8504 **   offset = 36 + (idx * 4)
8505 **
8506 ** For example, the free-page-count field is located at byte offset 36 of
8507 ** the database file header. The incr-vacuum-flag field is located at
8508 ** byte offset 64 (== 36+4*7).
8509 */
8510 #define BTREE_FREE_PAGE_COUNT     0
8511 #define BTREE_SCHEMA_VERSION      1
8512 #define BTREE_FILE_FORMAT         2
8513 #define BTREE_DEFAULT_CACHE_SIZE  3
8514 #define BTREE_LARGEST_ROOT_PAGE   4
8515 #define BTREE_TEXT_ENCODING       5
8516 #define BTREE_USER_VERSION        6
8517 #define BTREE_INCR_VACUUM         7
8518
8519 /*
8520 ** Values that may be OR'd together to form the second argument of an
8521 ** sqlite3BtreeCursorHints() call.
8522 */
8523 #define BTREE_BULKLOAD 0x00000001
8524
8525 SQLITE_PRIVATE int sqlite3BtreeCursor(
8526   Btree*,                              /* BTree containing table to open */
8527   int iTable,                          /* Index of root page */
8528   int wrFlag,                          /* 1 for writing.  0 for read-only */
8529   struct KeyInfo*,                     /* First argument to compare function */
8530   BtCursor *pCursor                    /* Space to write cursor structure */
8531 );
8532 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8533 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8534
8535 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8536 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8537   BtCursor*,
8538   UnpackedRecord *pUnKey,
8539   i64 intKey,
8540   int bias,
8541   int *pRes
8542 );
8543 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8544 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8545 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8546                                   const void *pData, int nData,
8547                                   int nZero, int bias, int seekResult);
8548 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8549 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8550 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8551 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8552 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8553 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8554 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8555 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8556 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8557 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8558 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8559 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8560 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8561
8562 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8563 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8564
8565 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8566 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8567 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8568 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8569 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
8570
8571 #ifndef NDEBUG
8572 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8573 #endif
8574
8575 #ifndef SQLITE_OMIT_BTREECOUNT
8576 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8577 #endif
8578
8579 #ifdef SQLITE_TEST
8580 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8581 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8582 #endif
8583
8584 #ifndef SQLITE_OMIT_WAL
8585 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8586 #endif
8587
8588 /*
8589 ** If we are not using shared cache, then there is no need to
8590 ** use mutexes to access the BtShared structures.  So make the
8591 ** Enter and Leave procedures no-ops.
8592 */
8593 #ifndef SQLITE_OMIT_SHARED_CACHE
8594 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
8595 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
8596 #else
8597 # define sqlite3BtreeEnter(X) 
8598 # define sqlite3BtreeEnterAll(X)
8599 #endif
8600
8601 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8602 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
8603 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
8604 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
8605 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
8606 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
8607 #ifndef NDEBUG
8608   /* These routines are used inside assert() statements only. */
8609 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
8610 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8611 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8612 #endif
8613 #else
8614
8615 # define sqlite3BtreeSharable(X) 0
8616 # define sqlite3BtreeLeave(X)
8617 # define sqlite3BtreeEnterCursor(X)
8618 # define sqlite3BtreeLeaveCursor(X)
8619 # define sqlite3BtreeLeaveAll(X)
8620
8621 # define sqlite3BtreeHoldsMutex(X) 1
8622 # define sqlite3BtreeHoldsAllMutexes(X) 1
8623 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
8624 #endif
8625
8626
8627 #endif /* _BTREE_H_ */
8628
8629 /************** End of btree.h ***********************************************/
8630 /************** Continuing where we left off in sqliteInt.h ******************/
8631 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
8632 /************** Begin file vdbe.h ********************************************/
8633 /*
8634 ** 2001 September 15
8635 **
8636 ** The author disclaims copyright to this source code.  In place of
8637 ** a legal notice, here is a blessing:
8638 **
8639 **    May you do good and not evil.
8640 **    May you find forgiveness for yourself and forgive others.
8641 **    May you share freely, never taking more than you give.
8642 **
8643 *************************************************************************
8644 ** Header file for the Virtual DataBase Engine (VDBE)
8645 **
8646 ** This header defines the interface to the virtual database engine
8647 ** or VDBE.  The VDBE implements an abstract machine that runs a
8648 ** simple program to access and modify the underlying database.
8649 */
8650 #ifndef _SQLITE_VDBE_H_
8651 #define _SQLITE_VDBE_H_
8652 /* #include <stdio.h> */
8653
8654 /*
8655 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
8656 ** in the source file sqliteVdbe.c are allowed to see the insides
8657 ** of this structure.
8658 */
8659 typedef struct Vdbe Vdbe;
8660
8661 /*
8662 ** The names of the following types declared in vdbeInt.h are required
8663 ** for the VdbeOp definition.
8664 */
8665 typedef struct VdbeFunc VdbeFunc;
8666 typedef struct Mem Mem;
8667 typedef struct SubProgram SubProgram;
8668
8669 /*
8670 ** A single instruction of the virtual machine has an opcode
8671 ** and as many as three operands.  The instruction is recorded
8672 ** as an instance of the following structure:
8673 */
8674 struct VdbeOp {
8675   u8 opcode;          /* What operation to perform */
8676   signed char p4type; /* One of the P4_xxx constants for p4 */
8677   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8678   u8 p5;              /* Fifth parameter is an unsigned character */
8679   int p1;             /* First operand */
8680   int p2;             /* Second parameter (often the jump destination) */
8681   int p3;             /* The third parameter */
8682   union {             /* fourth parameter */
8683     int i;                 /* Integer value if p4type==P4_INT32 */
8684     void *p;               /* Generic pointer */
8685     char *z;               /* Pointer to data for string (char array) types */
8686     i64 *pI64;             /* Used when p4type is P4_INT64 */
8687     double *pReal;         /* Used when p4type is P4_REAL */
8688     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8689     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8690     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8691     Mem *pMem;             /* Used when p4type is P4_MEM */
8692     VTable *pVtab;         /* Used when p4type is P4_VTAB */
8693     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8694     int *ai;               /* Used when p4type is P4_INTARRAY */
8695     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8696     int (*xAdvance)(BtCursor *, int *);
8697   } p4;
8698 #ifdef SQLITE_DEBUG
8699   char *zComment;          /* Comment to improve readability */
8700 #endif
8701 #ifdef VDBE_PROFILE
8702   int cnt;                 /* Number of times this instruction was executed */
8703   u64 cycles;              /* Total time spent executing this instruction */
8704 #endif
8705 };
8706 typedef struct VdbeOp VdbeOp;
8707
8708
8709 /*
8710 ** A sub-routine used to implement a trigger program.
8711 */
8712 struct SubProgram {
8713   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8714   int nOp;                      /* Elements in aOp[] */
8715   int nMem;                     /* Number of memory cells required */
8716   int nCsr;                     /* Number of cursors required */
8717   int nOnce;                    /* Number of OP_Once instructions */
8718   void *token;                  /* id that may be used to recursive triggers */
8719   SubProgram *pNext;            /* Next sub-program already visited */
8720 };
8721
8722 /*
8723 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8724 ** it takes up less space.
8725 */
8726 struct VdbeOpList {
8727   u8 opcode;          /* What operation to perform */
8728   signed char p1;     /* First operand */
8729   signed char p2;     /* Second parameter (often the jump destination) */
8730   signed char p3;     /* Third parameter */
8731 };
8732 typedef struct VdbeOpList VdbeOpList;
8733
8734 /*
8735 ** Allowed values of VdbeOp.p4type
8736 */
8737 #define P4_NOTUSED    0   /* The P4 parameter is not used */
8738 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8739 #define P4_STATIC   (-2)  /* Pointer to a static string */
8740 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8741 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8742 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8743 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8744 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8745 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8746 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8747 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8748 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8749 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8750 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8751 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8752 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8753 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8754
8755 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8756 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
8757 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8758 ** gets freed when the Vdbe is finalized so it still should be obtained
8759 ** from a single sqliteMalloc().  But no copy is made and the calling
8760 ** function should *not* try to free the KeyInfo.
8761 */
8762 #define P4_KEYINFO_HANDOFF (-16)
8763 #define P4_KEYINFO_STATIC  (-17)
8764
8765 /*
8766 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
8767 ** number of columns of data returned by the statement.
8768 */
8769 #define COLNAME_NAME     0
8770 #define COLNAME_DECLTYPE 1
8771 #define COLNAME_DATABASE 2
8772 #define COLNAME_TABLE    3
8773 #define COLNAME_COLUMN   4
8774 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8775 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8776 #else
8777 # ifdef SQLITE_OMIT_DECLTYPE
8778 #   define COLNAME_N      1      /* Store only the name */
8779 # else
8780 #   define COLNAME_N      2      /* Store the name and decltype */
8781 # endif
8782 #endif
8783
8784 /*
8785 ** The following macro converts a relative address in the p2 field
8786 ** of a VdbeOp structure into a negative number so that 
8787 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8788 ** the macro again restores the address.
8789 */
8790 #define ADDR(X)  (-1-(X))
8791
8792 /*
8793 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8794 ** header file that defines a number for each opcode used by the VDBE.
8795 */
8796 /************** Include opcodes.h in the middle of vdbe.h ********************/
8797 /************** Begin file opcodes.h *****************************************/
8798 /* Automatically generated.  Do not edit */
8799 /* See the mkopcodeh.awk script for details */
8800 #define OP_Goto                                 1
8801 #define OP_Gosub                                2
8802 #define OP_Return                               3
8803 #define OP_Yield                                4
8804 #define OP_HaltIfNull                           5
8805 #define OP_Halt                                 6
8806 #define OP_Integer                              7
8807 #define OP_Int64                                8
8808 #define OP_Real                               130   /* same as TK_FLOAT    */
8809 #define OP_String8                             94   /* same as TK_STRING   */
8810 #define OP_String                               9
8811 #define OP_Null                                10
8812 #define OP_Blob                                11
8813 #define OP_Variable                            12
8814 #define OP_Move                                13
8815 #define OP_Copy                                14
8816 #define OP_SCopy                               15
8817 #define OP_ResultRow                           16
8818 #define OP_Concat                              91   /* same as TK_CONCAT   */
8819 #define OP_Add                                 86   /* same as TK_PLUS     */
8820 #define OP_Subtract                            87   /* same as TK_MINUS    */
8821 #define OP_Multiply                            88   /* same as TK_STAR     */
8822 #define OP_Divide                              89   /* same as TK_SLASH    */
8823 #define OP_Remainder                           90   /* same as TK_REM      */
8824 #define OP_CollSeq                             17
8825 #define OP_Function                            18
8826 #define OP_BitAnd                              82   /* same as TK_BITAND   */
8827 #define OP_BitOr                               83   /* same as TK_BITOR    */
8828 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8829 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8830 #define OP_AddImm                              20
8831 #define OP_MustBeInt                           21
8832 #define OP_RealAffinity                        22
8833 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8834 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8835 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8836 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8837 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8838 #define OP_Eq                                  76   /* same as TK_EQ       */
8839 #define OP_Ne                                  75   /* same as TK_NE       */
8840 #define OP_Lt                                  79   /* same as TK_LT       */
8841 #define OP_Le                                  78   /* same as TK_LE       */
8842 #define OP_Gt                                  77   /* same as TK_GT       */
8843 #define OP_Ge                                  80   /* same as TK_GE       */
8844 #define OP_Permutation                         23
8845 #define OP_Compare                             24
8846 #define OP_Jump                                25
8847 #define OP_And                                 69   /* same as TK_AND      */
8848 #define OP_Or                                  68   /* same as TK_OR       */
8849 #define OP_Not                                 19   /* same as TK_NOT      */
8850 #define OP_BitNot                              93   /* same as TK_BITNOT   */
8851 #define OP_Once                                26
8852 #define OP_If                                  27
8853 #define OP_IfNot                               28
8854 #define OP_IsNull                              73   /* same as TK_ISNULL   */
8855 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
8856 #define OP_Column                              29
8857 #define OP_Affinity                            30
8858 #define OP_MakeRecord                          31
8859 #define OP_Count                               32
8860 #define OP_Savepoint                           33
8861 #define OP_AutoCommit                          34
8862 #define OP_Transaction                         35
8863 #define OP_ReadCookie                          36
8864 #define OP_SetCookie                           37
8865 #define OP_VerifyCookie                        38
8866 #define OP_OpenRead                            39
8867 #define OP_OpenWrite                           40
8868 #define OP_OpenAutoindex                       41
8869 #define OP_OpenEphemeral                       42
8870 #define OP_SorterOpen                          43
8871 #define OP_OpenPseudo                          44
8872 #define OP_Close                               45
8873 #define OP_SeekLt                              46
8874 #define OP_SeekLe                              47
8875 #define OP_SeekGe                              48
8876 #define OP_SeekGt                              49
8877 #define OP_Seek                                50
8878 #define OP_NotFound                            51
8879 #define OP_Found                               52
8880 #define OP_IsUnique                            53
8881 #define OP_NotExists                           54
8882 #define OP_Sequence                            55
8883 #define OP_NewRowid                            56
8884 #define OP_Insert                              57
8885 #define OP_InsertInt                           58
8886 #define OP_Delete                              59
8887 #define OP_ResetCount                          60
8888 #define OP_SorterCompare                       61
8889 #define OP_SorterData                          62
8890 #define OP_RowKey                              63
8891 #define OP_RowData                             64
8892 #define OP_Rowid                               65
8893 #define OP_NullRow                             66
8894 #define OP_Last                                67
8895 #define OP_SorterSort                          70
8896 #define OP_Sort                                71
8897 #define OP_Rewind                              72
8898 #define OP_SorterNext                          81
8899 #define OP_Prev                                92
8900 #define OP_Next                                95
8901 #define OP_SorterInsert                        96
8902 #define OP_IdxInsert                           97
8903 #define OP_IdxDelete                           98
8904 #define OP_IdxRowid                            99
8905 #define OP_IdxLT                              100
8906 #define OP_IdxGE                              101
8907 #define OP_Destroy                            102
8908 #define OP_Clear                              103
8909 #define OP_CreateIndex                        104
8910 #define OP_CreateTable                        105
8911 #define OP_ParseSchema                        106
8912 #define OP_LoadAnalysis                       107
8913 #define OP_DropTable                          108
8914 #define OP_DropIndex                          109
8915 #define OP_DropTrigger                        110
8916 #define OP_IntegrityCk                        111
8917 #define OP_RowSetAdd                          112
8918 #define OP_RowSetRead                         113
8919 #define OP_RowSetTest                         114
8920 #define OP_Program                            115
8921 #define OP_Param                              116
8922 #define OP_FkCounter                          117
8923 #define OP_FkIfZero                           118
8924 #define OP_MemMax                             119
8925 #define OP_IfPos                              120
8926 #define OP_IfNeg                              121
8927 #define OP_IfZero                             122
8928 #define OP_AggStep                            123
8929 #define OP_AggFinal                           124
8930 #define OP_Checkpoint                         125
8931 #define OP_JournalMode                        126
8932 #define OP_Vacuum                             127
8933 #define OP_IncrVacuum                         128
8934 #define OP_Expire                             129
8935 #define OP_TableLock                          131
8936 #define OP_VBegin                             132
8937 #define OP_VCreate                            133
8938 #define OP_VDestroy                           134
8939 #define OP_VOpen                              135
8940 #define OP_VFilter                            136
8941 #define OP_VColumn                            137
8942 #define OP_VNext                              138
8943 #define OP_VRename                            139
8944 #define OP_VUpdate                            140
8945 #define OP_Pagecount                          146
8946 #define OP_MaxPgcnt                           147
8947 #define OP_Trace                              148
8948 #define OP_Noop                               149
8949 #define OP_Explain                            150
8950
8951
8952 /* Properties such as "out2" or "jump" that are specified in
8953 ** comments following the "case" for each opcode in the vdbe.c
8954 ** are encoded into bitvectors as follows:
8955 */
8956 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8957 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8958 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8959 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8960 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8961 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8962 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8963 #define OPFLG_INITIALIZER {\
8964 /*   0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
8965 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24,\
8966 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8967 /*  24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
8968 /*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
8969 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
8970 /*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
8971 /*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8972 /*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
8973 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8974 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8975 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
8976 /*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8977 /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8978 /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
8979 /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
8980 /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8981 /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
8982 /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
8983
8984 /************** End of opcodes.h *********************************************/
8985 /************** Continuing where we left off in vdbe.h ***********************/
8986
8987 /*
8988 ** Prototypes for the VDBE interface.  See comments on the implementation
8989 ** for a description of what each of these routines does.
8990 */
8991 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8992 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8993 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8994 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8995 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8996 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8997 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8998 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8999 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
9000 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
9001 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
9002 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
9003 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
9004 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
9005 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
9006 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
9007 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
9008 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
9009 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
9010 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
9011 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
9012 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
9013 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
9014 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
9015 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
9016 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
9017 #ifdef SQLITE_DEBUG
9018 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
9019 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
9020 #endif
9021 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
9022 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
9023 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
9024 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
9025 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
9026 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
9027 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
9028 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
9029 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
9030 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
9031 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
9032 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
9033 #ifndef SQLITE_OMIT_TRACE
9034 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
9035 #endif
9036
9037 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
9038 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
9039 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
9040
9041 #ifndef SQLITE_OMIT_TRIGGER
9042 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
9043 #endif
9044
9045
9046 #ifndef NDEBUG
9047 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
9048 # define VdbeComment(X)  sqlite3VdbeComment X
9049 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
9050 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
9051 #else
9052 # define VdbeComment(X)
9053 # define VdbeNoopComment(X)
9054 #endif
9055
9056 #endif
9057
9058 /************** End of vdbe.h ************************************************/
9059 /************** Continuing where we left off in sqliteInt.h ******************/
9060 /************** Include pager.h in the middle of sqliteInt.h *****************/
9061 /************** Begin file pager.h *******************************************/
9062 /*
9063 ** 2001 September 15
9064 **
9065 ** The author disclaims copyright to this source code.  In place of
9066 ** a legal notice, here is a blessing:
9067 **
9068 **    May you do good and not evil.
9069 **    May you find forgiveness for yourself and forgive others.
9070 **    May you share freely, never taking more than you give.
9071 **
9072 *************************************************************************
9073 ** This header file defines the interface that the sqlite page cache
9074 ** subsystem.  The page cache subsystem reads and writes a file a page
9075 ** at a time and provides a journal for rollback.
9076 */
9077
9078 #ifndef _PAGER_H_
9079 #define _PAGER_H_
9080
9081 /*
9082 ** Default maximum size for persistent journal files. A negative 
9083 ** value means no limit. This value may be overridden using the 
9084 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
9085 */
9086 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
9087   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
9088 #endif
9089
9090 /*
9091 ** The type used to represent a page number.  The first page in a file
9092 ** is called page 1.  0 is used to represent "not a page".
9093 */
9094 typedef u32 Pgno;
9095
9096 /*
9097 ** Each open file is managed by a separate instance of the "Pager" structure.
9098 */
9099 typedef struct Pager Pager;
9100
9101 /*
9102 ** Handle type for pages.
9103 */
9104 typedef struct PgHdr DbPage;
9105
9106 /*
9107 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
9108 ** reserved for working around a windows/posix incompatibility). It is
9109 ** used in the journal to signify that the remainder of the journal file 
9110 ** is devoted to storing a master journal name - there are no more pages to
9111 ** roll back. See comments for function writeMasterJournal() in pager.c 
9112 ** for details.
9113 */
9114 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
9115
9116 /*
9117 ** Allowed values for the flags parameter to sqlite3PagerOpen().
9118 **
9119 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
9120 */
9121 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
9122 #define PAGER_MEMORY        0x0002    /* In-memory database */
9123
9124 /*
9125 ** Valid values for the second argument to sqlite3PagerLockingMode().
9126 */
9127 #define PAGER_LOCKINGMODE_QUERY      -1
9128 #define PAGER_LOCKINGMODE_NORMAL      0
9129 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
9130
9131 /*
9132 ** Numeric constants that encode the journalmode.  
9133 */
9134 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
9135 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
9136 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
9137 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
9138 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
9139 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
9140 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
9141
9142 /*
9143 ** The remainder of this file contains the declarations of the functions
9144 ** that make up the Pager sub-system API. See source code comments for 
9145 ** a detailed description of each routine.
9146 */
9147
9148 /* Open and close a Pager connection. */ 
9149 SQLITE_PRIVATE int sqlite3PagerOpen(
9150   sqlite3_vfs*,
9151   Pager **ppPager,
9152   const char*,
9153   int,
9154   int,
9155   int,
9156   void(*)(DbPage*)
9157 );
9158 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9159 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9160
9161 /* Functions used to configure a Pager object. */
9162 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9163 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9164 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9165 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9166 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9167 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
9168 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9169 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9170 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9171 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9172 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9173 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9174
9175 /* Functions used to obtain and release page references. */ 
9176 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9177 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9178 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9179 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9180 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9181
9182 /* Operations on page references. */
9183 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9184 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9185 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9186 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9187 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
9188 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
9189
9190 /* Functions used to manage pager transactions and savepoints. */
9191 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9192 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9193 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9194 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9195 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
9196 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9197 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9198 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9199 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9200 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9201
9202 #ifndef SQLITE_OMIT_WAL
9203 SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9204 SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
9205 SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
9206 SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9207 SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
9208 #endif
9209
9210 #ifdef SQLITE_ENABLE_ZIPVFS
9211 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
9212 #endif
9213
9214 /* Functions used to query pager state and configuration. */
9215 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9216 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9217 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9218 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9219 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9220 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9221 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9222 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9223 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9224 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9225 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9226 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9227 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
9228
9229 /* Functions used to truncate the database file. */
9230 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9231
9232 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9233 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9234 #endif
9235
9236 /* Functions to support testing and debugging. */
9237 #if !defined(NDEBUG) || defined(SQLITE_TEST)
9238 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
9239 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
9240 #endif
9241 #ifdef SQLITE_TEST
9242 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
9243 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
9244   void disable_simulated_io_errors(void);
9245   void enable_simulated_io_errors(void);
9246 #else
9247 # define disable_simulated_io_errors()
9248 # define enable_simulated_io_errors()
9249 #endif
9250
9251 #endif /* _PAGER_H_ */
9252
9253 /************** End of pager.h ***********************************************/
9254 /************** Continuing where we left off in sqliteInt.h ******************/
9255 /************** Include pcache.h in the middle of sqliteInt.h ****************/
9256 /************** Begin file pcache.h ******************************************/
9257 /*
9258 ** 2008 August 05
9259 **
9260 ** The author disclaims copyright to this source code.  In place of
9261 ** a legal notice, here is a blessing:
9262 **
9263 **    May you do good and not evil.
9264 **    May you find forgiveness for yourself and forgive others.
9265 **    May you share freely, never taking more than you give.
9266 **
9267 *************************************************************************
9268 ** This header file defines the interface that the sqlite page cache
9269 ** subsystem. 
9270 */
9271
9272 #ifndef _PCACHE_H_
9273
9274 typedef struct PgHdr PgHdr;
9275 typedef struct PCache PCache;
9276
9277 /*
9278 ** Every page in the cache is controlled by an instance of the following
9279 ** structure.
9280 */
9281 struct PgHdr {
9282   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
9283   void *pData;                   /* Page data */
9284   void *pExtra;                  /* Extra content */
9285   PgHdr *pDirty;                 /* Transient list of dirty pages */
9286   Pager *pPager;                 /* The pager this page is part of */
9287   Pgno pgno;                     /* Page number for this page */
9288 #ifdef SQLITE_CHECK_PAGES
9289   u32 pageHash;                  /* Hash of page content */
9290 #endif
9291   u16 flags;                     /* PGHDR flags defined below */
9292
9293   /**********************************************************************
9294   ** Elements above are public.  All that follows is private to pcache.c
9295   ** and should not be accessed by other modules.
9296   */
9297   i16 nRef;                      /* Number of users of this page */
9298   PCache *pCache;                /* Cache that owns this page */
9299
9300   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
9301   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
9302 };
9303
9304 /* Bit values for PgHdr.flags */
9305 #define PGHDR_DIRTY             0x002  /* Page has changed */
9306 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
9307                                        ** writing this page to the database */
9308 #define PGHDR_NEED_READ         0x008  /* Content is unread */
9309 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
9310 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
9311
9312 /* Initialize and shutdown the page cache subsystem */
9313 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9314 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9315
9316 /* Page cache buffer management:
9317 ** These routines implement SQLITE_CONFIG_PAGECACHE.
9318 */
9319 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9320
9321 /* Create a new pager cache.
9322 ** Under memory stress, invoke xStress to try to make pages clean.
9323 ** Only clean and unpinned pages can be reclaimed.
9324 */
9325 SQLITE_PRIVATE void sqlite3PcacheOpen(
9326   int szPage,                    /* Size of every page */
9327   int szExtra,                   /* Extra space associated with each page */
9328   int bPurgeable,                /* True if pages are on backing store */
9329   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9330   void *pStress,                 /* Argument to xStress */
9331   PCache *pToInit                /* Preallocated space for the PCache */
9332 );
9333
9334 /* Modify the page-size after the cache has been created. */
9335 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
9336
9337 /* Return the size in bytes of a PCache object.  Used to preallocate
9338 ** storage space.
9339 */
9340 SQLITE_PRIVATE int sqlite3PcacheSize(void);
9341
9342 /* One release per successful fetch.  Page is pinned until released.
9343 ** Reference counted. 
9344 */
9345 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
9346 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9347
9348 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
9349 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
9350 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
9351 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
9352
9353 /* Change a page number.  Used by incr-vacuum. */
9354 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9355
9356 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
9357 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9358
9359 /* Get a list of all dirty pages in the cache, sorted by page number */
9360 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
9361
9362 /* Reset and close the cache object */
9363 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
9364
9365 /* Clear flags from pages of the page cache */
9366 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
9367
9368 /* Discard the contents of the cache */
9369 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
9370
9371 /* Return the total number of outstanding page references */
9372 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
9373
9374 /* Increment the reference count of an existing page */
9375 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
9376
9377 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
9378
9379 /* Return the total number of pages stored in the cache */
9380 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
9381
9382 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
9383 /* Iterate through all dirty pages currently stored in the cache. This
9384 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
9385 ** library is built.
9386 */
9387 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
9388 #endif
9389
9390 /* Set and get the suggested cache-size for the specified pager-cache.
9391 **
9392 ** If no global maximum is configured, then the system attempts to limit
9393 ** the total number of pages cached by purgeable pager-caches to the sum
9394 ** of the suggested cache-sizes.
9395 */
9396 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
9397 #ifdef SQLITE_TEST
9398 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
9399 #endif
9400
9401 /* Free up as much memory as possible from the page cache */
9402 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
9403
9404 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
9405 /* Try to return memory used by the pcache module to the main memory heap */
9406 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
9407 #endif
9408
9409 #ifdef SQLITE_TEST
9410 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
9411 #endif
9412
9413 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
9414
9415 #endif /* _PCACHE_H_ */
9416
9417 /************** End of pcache.h **********************************************/
9418 /************** Continuing where we left off in sqliteInt.h ******************/
9419
9420 /************** Include os.h in the middle of sqliteInt.h ********************/
9421 /************** Begin file os.h **********************************************/
9422 /*
9423 ** 2001 September 16
9424 **
9425 ** The author disclaims copyright to this source code.  In place of
9426 ** a legal notice, here is a blessing:
9427 **
9428 **    May you do good and not evil.
9429 **    May you find forgiveness for yourself and forgive others.
9430 **    May you share freely, never taking more than you give.
9431 **
9432 ******************************************************************************
9433 **
9434 ** This header file (together with is companion C source-code file
9435 ** "os.c") attempt to abstract the underlying operating system so that
9436 ** the SQLite library will work on both POSIX and windows systems.
9437 **
9438 ** This header file is #include-ed by sqliteInt.h and thus ends up
9439 ** being included by every source file.
9440 */
9441 #ifndef _SQLITE_OS_H_
9442 #define _SQLITE_OS_H_
9443
9444 /*
9445 ** Figure out if we are dealing with Unix, Windows, or some other
9446 ** operating system.  After the following block of preprocess macros,
9447 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER 
9448 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
9449 ** three will be 0.
9450 */
9451 #if defined(SQLITE_OS_OTHER)
9452 # if SQLITE_OS_OTHER==1
9453 #   undef SQLITE_OS_UNIX
9454 #   define SQLITE_OS_UNIX 0
9455 #   undef SQLITE_OS_WIN
9456 #   define SQLITE_OS_WIN 0
9457 # else
9458 #   undef SQLITE_OS_OTHER
9459 # endif
9460 #endif
9461 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9462 # define SQLITE_OS_OTHER 0
9463 # ifndef SQLITE_OS_WIN
9464 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9465 #     define SQLITE_OS_WIN 1
9466 #     define SQLITE_OS_UNIX 0
9467 #   else
9468 #     define SQLITE_OS_WIN 0
9469 #     define SQLITE_OS_UNIX 1
9470 #  endif
9471 # else
9472 #  define SQLITE_OS_UNIX 0
9473 # endif
9474 #else
9475 # ifndef SQLITE_OS_WIN
9476 #  define SQLITE_OS_WIN 0
9477 # endif
9478 #endif
9479
9480 #if SQLITE_OS_WIN
9481 # include <windows.h>
9482 #endif
9483
9484 /*
9485 ** Determine if we are dealing with Windows NT.
9486 **
9487 ** We ought to be able to determine if we are compiling for win98 or winNT
9488 ** using the _WIN32_WINNT macro as follows:
9489 **
9490 ** #if defined(_WIN32_WINNT)
9491 ** # define SQLITE_OS_WINNT 1
9492 ** #else
9493 ** # define SQLITE_OS_WINNT 0
9494 ** #endif
9495 **
9496 ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
9497 ** so the above test does not work.  We'll just assume that everything is
9498 ** winNT unless the programmer explicitly says otherwise by setting
9499 ** SQLITE_OS_WINNT to 0.
9500 */
9501 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
9502 # define SQLITE_OS_WINNT 1
9503 #endif
9504
9505 /*
9506 ** Determine if we are dealing with WindowsCE - which has a much
9507 ** reduced API.
9508 */
9509 #if defined(_WIN32_WCE)
9510 # define SQLITE_OS_WINCE 1
9511 #else
9512 # define SQLITE_OS_WINCE 0
9513 #endif
9514
9515 /*
9516 ** Determine if we are dealing with WinRT, which provides only a subset of
9517 ** the full Win32 API.
9518 */
9519 #if !defined(SQLITE_OS_WINRT)
9520 # define SQLITE_OS_WINRT 0
9521 #endif
9522
9523 /*
9524 ** When compiled for WinCE or WinRT, there is no concept of the current
9525 ** directory.
9526  */
9527 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
9528 # define SQLITE_CURDIR 1
9529 #endif
9530
9531 /* If the SET_FULLSYNC macro is not defined above, then make it
9532 ** a no-op
9533 */
9534 #ifndef SET_FULLSYNC
9535 # define SET_FULLSYNC(x,y)
9536 #endif
9537
9538 /*
9539 ** The default size of a disk sector
9540 */
9541 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
9542 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
9543 #endif
9544
9545 /*
9546 ** Temporary files are named starting with this prefix followed by 16 random
9547 ** alphanumeric characters, and no file extension. They are stored in the
9548 ** OS's standard temporary file directory, and are deleted prior to exit.
9549 ** If sqlite is being embedded in another program, you may wish to change the
9550 ** prefix to reflect your program's name, so that if your program exits
9551 ** prematurely, old temporary files can be easily identified. This can be done
9552 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9553 **
9554 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
9555 ** Mcafee started using SQLite in their anti-virus product and it
9556 ** started putting files with the "sqlite" name in the c:/temp folder.
9557 ** This annoyed many windows users.  Those users would then do a 
9558 ** Google search for "sqlite", find the telephone numbers of the
9559 ** developers and call to wake them up at night and complain.
9560 ** For this reason, the default name prefix is changed to be "sqlite" 
9561 ** spelled backwards.  So the temp files are still identified, but
9562 ** anybody smart enough to figure out the code is also likely smart
9563 ** enough to know that calling the developer will not help get rid
9564 ** of the file.
9565 */
9566 #ifndef SQLITE_TEMP_FILE_PREFIX
9567 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9568 #endif
9569
9570 /*
9571 ** The following values may be passed as the second argument to
9572 ** sqlite3OsLock(). The various locks exhibit the following semantics:
9573 **
9574 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9575 ** RESERVED:  A single process may hold a RESERVED lock on a file at
9576 **            any time. Other processes may hold and obtain new SHARED locks.
9577 ** PENDING:   A single process may hold a PENDING lock on a file at
9578 **            any one time. Existing SHARED locks may persist, but no new
9579 **            SHARED locks may be obtained by other processes.
9580 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9581 **
9582 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9583 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9584 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9585 ** sqlite3OsLock().
9586 */
9587 #define NO_LOCK         0
9588 #define SHARED_LOCK     1
9589 #define RESERVED_LOCK   2
9590 #define PENDING_LOCK    3
9591 #define EXCLUSIVE_LOCK  4
9592
9593 /*
9594 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
9595 **
9596 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9597 ** those functions are not available.  So we use only LockFile() and
9598 ** UnlockFile().
9599 **
9600 ** LockFile() prevents not just writing but also reading by other processes.
9601 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
9602 ** byte out of a specific range of bytes. The lock byte is obtained at 
9603 ** random so two separate readers can probably access the file at the 
9604 ** same time, unless they are unlucky and choose the same lock byte.
9605 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9606 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9607 ** a single byte of the file that is designated as the reserved lock byte.
9608 ** A PENDING_LOCK is obtained by locking a designated byte different from
9609 ** the RESERVED_LOCK byte.
9610 **
9611 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9612 ** which means we can use reader/writer locks.  When reader/writer locks
9613 ** are used, the lock is placed on the same range of bytes that is used
9614 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9615 ** will support two or more Win95 readers or two or more WinNT readers.
9616 ** But a single Win95 reader will lock out all WinNT readers and a single
9617 ** WinNT reader will lock out all other Win95 readers.
9618 **
9619 ** The following #defines specify the range of bytes used for locking.
9620 ** SHARED_SIZE is the number of bytes available in the pool from which
9621 ** a random byte is selected for a shared lock.  The pool of bytes for
9622 ** shared locks begins at SHARED_FIRST. 
9623 **
9624 ** The same locking strategy and
9625 ** byte ranges are used for Unix.  This leaves open the possiblity of having
9626 ** clients on win95, winNT, and unix all talking to the same shared file
9627 ** and all locking correctly.  To do so would require that samba (or whatever
9628 ** tool is being used for file sharing) implements locks correctly between
9629 ** windows and unix.  I'm guessing that isn't likely to happen, but by
9630 ** using the same locking range we are at least open to the possibility.
9631 **
9632 ** Locking in windows is manditory.  For this reason, we cannot store
9633 ** actual data in the bytes used for locking.  The pager never allocates
9634 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
9635 ** that all locks will fit on a single page even at the minimum page size.
9636 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9637 ** is set high so that we don't have to allocate an unused page except
9638 ** for very large databases.  But one should test the page skipping logic 
9639 ** by setting PENDING_BYTE low and running the entire regression suite.
9640 **
9641 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9642 ** file format.  Depending on how it is changed, you might not notice
9643 ** the incompatibility right away, even running a full regression test.
9644 ** The default location of PENDING_BYTE is the first byte past the
9645 ** 1GB boundary.
9646 **
9647 */
9648 #ifdef SQLITE_OMIT_WSD
9649 # define PENDING_BYTE     (0x40000000)
9650 #else
9651 # define PENDING_BYTE      sqlite3PendingByte
9652 #endif
9653 #define RESERVED_BYTE     (PENDING_BYTE+1)
9654 #define SHARED_FIRST      (PENDING_BYTE+2)
9655 #define SHARED_SIZE       510
9656
9657 /*
9658 ** Wrapper around OS specific sqlite3_os_init() function.
9659 */
9660 SQLITE_PRIVATE int sqlite3OsInit(void);
9661
9662 /* 
9663 ** Functions for accessing sqlite3_file methods 
9664 */
9665 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9666 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9667 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9668 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9669 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9670 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9671 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9672 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9673 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9674 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9675 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
9676 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9677 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9678 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9679 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9680 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9681 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9682 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9683
9684
9685 /* 
9686 ** Functions for accessing sqlite3_vfs methods 
9687 */
9688 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9689 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9690 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9691 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9692 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9693 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9694 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9695 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9696 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9697 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
9698 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9699 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9700 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9701
9702 /*
9703 ** Convenience functions for opening and closing files using 
9704 ** sqlite3_malloc() to obtain space for the file-handle structure.
9705 */
9706 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9707 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9708
9709 #endif /* _SQLITE_OS_H_ */
9710
9711 /************** End of os.h **************************************************/
9712 /************** Continuing where we left off in sqliteInt.h ******************/
9713 /************** Include mutex.h in the middle of sqliteInt.h *****************/
9714 /************** Begin file mutex.h *******************************************/
9715 /*
9716 ** 2007 August 28
9717 **
9718 ** The author disclaims copyright to this source code.  In place of
9719 ** a legal notice, here is a blessing:
9720 **
9721 **    May you do good and not evil.
9722 **    May you find forgiveness for yourself and forgive others.
9723 **    May you share freely, never taking more than you give.
9724 **
9725 *************************************************************************
9726 **
9727 ** This file contains the common header for all mutex implementations.
9728 ** The sqliteInt.h header #includes this file so that it is available
9729 ** to all source files.  We break it out in an effort to keep the code
9730 ** better organized.
9731 **
9732 ** NOTE:  source files should *not* #include this header file directly.
9733 ** Source files should #include the sqliteInt.h file and let that file
9734 ** include this one indirectly.
9735 */
9736
9737
9738 /*
9739 ** Figure out what version of the code to use.  The choices are
9740 **
9741 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9742 **                             mutexes implemention cannot be overridden
9743 **                             at start-time.
9744 **
9745 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
9746 **                             mutual exclusion is provided.  But this
9747 **                             implementation can be overridden at
9748 **                             start-time.
9749 **
9750 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9751 **
9752 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
9753 */
9754 #if !SQLITE_THREADSAFE
9755 # define SQLITE_MUTEX_OMIT
9756 #endif
9757 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9758 #  if SQLITE_OS_UNIX
9759 #    define SQLITE_MUTEX_PTHREADS
9760 #  elif SQLITE_OS_WIN
9761 #    define SQLITE_MUTEX_W32
9762 #  else
9763 #    define SQLITE_MUTEX_NOOP
9764 #  endif
9765 #endif
9766
9767 #ifdef SQLITE_MUTEX_OMIT
9768 /*
9769 ** If this is a no-op implementation, implement everything as macros.
9770 */
9771 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9772 #define sqlite3_mutex_free(X)
9773 #define sqlite3_mutex_enter(X)    
9774 #define sqlite3_mutex_try(X)      SQLITE_OK
9775 #define sqlite3_mutex_leave(X)    
9776 #define sqlite3_mutex_held(X)     ((void)(X),1)
9777 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
9778 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9779 #define sqlite3MutexInit()        SQLITE_OK
9780 #define sqlite3MutexEnd()
9781 #define MUTEX_LOGIC(X)
9782 #else
9783 #define MUTEX_LOGIC(X)            X
9784 #endif /* defined(SQLITE_MUTEX_OMIT) */
9785
9786 /************** End of mutex.h ***********************************************/
9787 /************** Continuing where we left off in sqliteInt.h ******************/
9788
9789
9790 /*
9791 ** Each database file to be accessed by the system is an instance
9792 ** of the following structure.  There are normally two of these structures
9793 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9794 ** aDb[1] is the database file used to hold temporary tables.  Additional
9795 ** databases may be attached.
9796 */
9797 struct Db {
9798   char *zName;         /* Name of this database */
9799   Btree *pBt;          /* The B*Tree structure for this database file */
9800   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9801   u8 safety_level;     /* How aggressive at syncing data to disk */
9802   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9803 };
9804
9805 /*
9806 ** An instance of the following structure stores a database schema.
9807 **
9808 ** Most Schema objects are associated with a Btree.  The exception is
9809 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9810 ** In shared cache mode, a single Schema object can be shared by multiple
9811 ** Btrees that refer to the same underlying BtShared object.
9812 ** 
9813 ** Schema objects are automatically deallocated when the last Btree that
9814 ** references them is destroyed.   The TEMP Schema is manually freed by
9815 ** sqlite3_close().
9816 *
9817 ** A thread must be holding a mutex on the corresponding Btree in order
9818 ** to access Schema content.  This implies that the thread must also be
9819 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9820 ** For a TEMP Schema, only the connection mutex is required.
9821 */
9822 struct Schema {
9823   int schema_cookie;   /* Database schema version number for this file */
9824   int iGeneration;     /* Generation counter.  Incremented with each change */
9825   Hash tblHash;        /* All tables indexed by name */
9826   Hash idxHash;        /* All (named) indices indexed by name */
9827   Hash trigHash;       /* All triggers indexed by name */
9828   Hash fkeyHash;       /* All foreign keys by referenced table name */
9829   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9830   u8 file_format;      /* Schema format version for this file */
9831   u8 enc;              /* Text encoding used by this database */
9832   u16 flags;           /* Flags associated with this schema */
9833   int cache_size;      /* Number of pages to use in the cache */
9834 };
9835
9836 /*
9837 ** These macros can be used to test, set, or clear bits in the 
9838 ** Db.pSchema->flags field.
9839 */
9840 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9841 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9842 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9843 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9844
9845 /*
9846 ** Allowed values for the DB.pSchema->flags field.
9847 **
9848 ** The DB_SchemaLoaded flag is set after the database schema has been
9849 ** read into internal hash tables.
9850 **
9851 ** DB_UnresetViews means that one or more views have column names that
9852 ** have been filled out.  If the schema changes, these column names might
9853 ** changes and so the view will need to be reset.
9854 */
9855 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9856 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9857 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9858
9859 /*
9860 ** The number of different kinds of things that can be limited
9861 ** using the sqlite3_limit() interface.
9862 */
9863 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9864
9865 /*
9866 ** Lookaside malloc is a set of fixed-size buffers that can be used
9867 ** to satisfy small transient memory allocation requests for objects
9868 ** associated with a particular database connection.  The use of
9869 ** lookaside malloc provides a significant performance enhancement
9870 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9871 ** SQL statements.
9872 **
9873 ** The Lookaside structure holds configuration information about the
9874 ** lookaside malloc subsystem.  Each available memory allocation in
9875 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9876 ** objects.
9877 **
9878 ** Lookaside allocations are only allowed for objects that are associated
9879 ** with a particular database connection.  Hence, schema information cannot
9880 ** be stored in lookaside because in shared cache mode the schema information
9881 ** is shared by multiple database connections.  Therefore, while parsing
9882 ** schema information, the Lookaside.bEnabled flag is cleared so that
9883 ** lookaside allocations are not used to construct the schema objects.
9884 */
9885 struct Lookaside {
9886   u16 sz;                 /* Size of each buffer in bytes */
9887   u8 bEnabled;            /* False to disable new lookaside allocations */
9888   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9889   int nOut;               /* Number of buffers currently checked out */
9890   int mxOut;              /* Highwater mark for nOut */
9891   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9892   LookasideSlot *pFree;   /* List of available buffers */
9893   void *pStart;           /* First byte of available memory space */
9894   void *pEnd;             /* First byte past end of available space */
9895 };
9896 struct LookasideSlot {
9897   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9898 };
9899
9900 /*
9901 ** A hash table for function definitions.
9902 **
9903 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9904 ** Collisions are on the FuncDef.pHash chain.
9905 */
9906 struct FuncDefHash {
9907   FuncDef *a[23];       /* Hash table for functions */
9908 };
9909
9910 /*
9911 ** Each database connection is an instance of the following structure.
9912 */
9913 struct sqlite3 {
9914   sqlite3_vfs *pVfs;            /* OS Interface */
9915   struct Vdbe *pVdbe;           /* List of active virtual machines */
9916   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9917   sqlite3_mutex *mutex;         /* Connection mutex */
9918   Db *aDb;                      /* All backends */
9919   int nDb;                      /* Number of backends currently in use */
9920   int flags;                    /* Miscellaneous flags. See below */
9921   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9922   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
9923   int errCode;                  /* Most recent error code (SQLITE_*) */
9924   int errMask;                  /* & result codes with this before returning */
9925   u16 dbOptFlags;               /* Flags to enable/disable optimizations */
9926   u8 autoCommit;                /* The auto-commit flag. */
9927   u8 temp_store;                /* 1: file 2: memory 0: default */
9928   u8 mallocFailed;              /* True if we have seen a malloc failure */
9929   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9930   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9931   u8 suppressErr;               /* Do not issue error messages if true */
9932   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
9933   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9934   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9935   u32 magic;                    /* Magic number for detect library misuse */
9936   int nChange;                  /* Value returned by sqlite3_changes() */
9937   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9938   int aLimit[SQLITE_N_LIMIT];   /* Limits */
9939   struct sqlite3InitInfo {      /* Information used during initialization */
9940     int newTnum;                /* Rootpage of table being initialized */
9941     u8 iDb;                     /* Which db file is being initialized */
9942     u8 busy;                    /* TRUE if currently initializing */
9943     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9944   } init;
9945   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9946   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9947   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9948   int nExtension;               /* Number of loaded extensions */
9949   void **aExtension;            /* Array of shared library handles */
9950   void (*xTrace)(void*,const char*);        /* Trace function */
9951   void *pTraceArg;                          /* Argument to the trace function */
9952   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9953   void *pProfileArg;                        /* Argument to profile function */
9954   void *pCommitArg;                 /* Argument to xCommitCallback() */   
9955   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9956   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
9957   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9958   void *pUpdateArg;
9959   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9960 #ifndef SQLITE_OMIT_WAL
9961   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9962   void *pWalArg;
9963 #endif
9964   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9965   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9966   void *pCollNeededArg;
9967   sqlite3_value *pErr;          /* Most recent error message */
9968   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9969   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9970   union {
9971     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9972     double notUsed1;            /* Spacer */
9973   } u1;
9974   Lookaside lookaside;          /* Lookaside malloc configuration */
9975 #ifndef SQLITE_OMIT_AUTHORIZATION
9976   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9977                                 /* Access authorization function */
9978   void *pAuthArg;               /* 1st argument to the access auth function */
9979 #endif
9980 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9981   int (*xProgress)(void *);     /* The progress callback */
9982   void *pProgressArg;           /* Argument to the progress callback */
9983   int nProgressOps;             /* Number of opcodes for progress callback */
9984 #endif
9985 #ifndef SQLITE_OMIT_VIRTUALTABLE
9986   int nVTrans;                  /* Allocated size of aVTrans */
9987   Hash aModule;                 /* populated by sqlite3_create_module() */
9988   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
9989   VTable **aVTrans;             /* Virtual tables with open transactions */
9990   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9991 #endif
9992   FuncDefHash aFunc;            /* Hash table of connection functions */
9993   Hash aCollSeq;                /* All collating sequences */
9994   BusyHandler busyHandler;      /* Busy callback */
9995   Db aDbStatic[2];              /* Static space for the 2 default backends */
9996   Savepoint *pSavepoint;        /* List of active savepoints */
9997   int busyTimeout;              /* Busy handler timeout, in msec */
9998   int nSavepoint;               /* Number of non-transaction savepoints */
9999   int nStatement;               /* Number of nested statement-transactions  */
10000   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
10001   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
10002
10003 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10004   /* The following variables are all protected by the STATIC_MASTER 
10005   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
10006   **
10007   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
10008   ** unlock so that it can proceed.
10009   **
10010   ** When X.pBlockingConnection==Y, that means that something that X tried
10011   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
10012   ** held by Y.
10013   */
10014   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
10015   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
10016   void *pUnlockArg;                     /* Argument to xUnlockNotify */
10017   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
10018   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
10019 #endif
10020 };
10021
10022 /*
10023 ** A macro to discover the encoding of a database.
10024 */
10025 #define ENC(db) ((db)->aDb[0].pSchema->enc)
10026
10027 /*
10028 ** Possible values for the sqlite3.flags.
10029 */
10030 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
10031 #define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
10032 #define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
10033 #define SQLITE_ShortColNames  0x00000008  /* Show short columns names */
10034 #define SQLITE_CountRows      0x00000010  /* Count rows changed by INSERT, */
10035                                           /*   DELETE, or UPDATE and return */
10036                                           /*   the count using a callback. */
10037 #define SQLITE_NullCallback   0x00000020  /* Invoke the callback once if the */
10038                                           /*   result set is empty */
10039 #define SQLITE_SqlTrace       0x00000040  /* Debug print SQL as it executes */
10040 #define SQLITE_VdbeListing    0x00000080  /* Debug listings of VDBE programs */
10041 #define SQLITE_WriteSchema    0x00000100  /* OK to update SQLITE_MASTER */
10042 #define SQLITE_VdbeAddopTrace 0x00000200  /* Trace sqlite3VdbeAddOp() calls */
10043 #define SQLITE_IgnoreChecks   0x00000400  /* Do not enforce check constraints */
10044 #define SQLITE_ReadUncommitted 0x0000800  /* For shared-cache mode */
10045 #define SQLITE_LegacyFileFmt  0x00001000  /* Create new databases in format 1 */
10046 #define SQLITE_FullFSync      0x00002000  /* Use full fsync on the backend */
10047 #define SQLITE_CkptFullFSync  0x00004000  /* Use full fsync for checkpoint */
10048 #define SQLITE_RecoveryMode   0x00008000  /* Ignore schema errors */
10049 #define SQLITE_ReverseOrder   0x00010000  /* Reverse unordered SELECTs */
10050 #define SQLITE_RecTriggers    0x00020000  /* Enable recursive triggers */
10051 #define SQLITE_ForeignKeys    0x00040000  /* Enforce foreign key constraints  */
10052 #define SQLITE_AutoIndex      0x00080000  /* Enable automatic indexes */
10053 #define SQLITE_PreferBuiltin  0x00100000  /* Preference to built-in funcs */
10054 #define SQLITE_LoadExtension  0x00200000  /* Enable load_extension */
10055 #define SQLITE_EnableTrigger  0x00400000  /* True to enable triggers */
10056
10057 /*
10058 ** Bits of the sqlite3.dbOptFlags field that are used by the
10059 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
10060 ** selectively disable various optimizations.
10061 */
10062 #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
10063 #define SQLITE_ColumnCache    0x0002   /* Column cache */
10064 #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
10065 #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
10066 #define SQLITE_IdxRealAsInt   0x0010   /* Store REAL as INT in indices */
10067 #define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
10068 #define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
10069 #define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
10070 #define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
10071 #define SQLITE_Transitive     0x0200   /* Transitive constraints */
10072 #define SQLITE_AllOpts        0xffff   /* All optimizations */
10073
10074 /*
10075 ** Macros for testing whether or not optimizations are enabled or disabled.
10076 */
10077 #ifndef SQLITE_OMIT_BUILTIN_TEST
10078 #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
10079 #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
10080 #else
10081 #define OptimizationDisabled(db, mask)  0
10082 #define OptimizationEnabled(db, mask)   1
10083 #endif
10084
10085 /*
10086 ** Possible values for the sqlite.magic field.
10087 ** The numbers are obtained at random and have no special meaning, other
10088 ** than being distinct from one another.
10089 */
10090 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
10091 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
10092 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
10093 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
10094 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
10095 #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
10096
10097 /*
10098 ** Each SQL function is defined by an instance of the following
10099 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
10100 ** hash table.  When multiple functions have the same name, the hash table
10101 ** points to a linked list of these structures.
10102 */
10103 struct FuncDef {
10104   i16 nArg;            /* Number of arguments.  -1 means unlimited */
10105   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
10106   u8 flags;            /* Some combination of SQLITE_FUNC_* */
10107   void *pUserData;     /* User data parameter */
10108   FuncDef *pNext;      /* Next function with same name */
10109   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10110   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10111   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
10112   char *zName;         /* SQL name of the function. */
10113   FuncDef *pHash;      /* Next with a different name but the same hash */
10114   FuncDestructor *pDestructor;   /* Reference counted destructor function */
10115 };
10116
10117 /*
10118 ** This structure encapsulates a user-function destructor callback (as
10119 ** configured using create_function_v2()) and a reference counter. When
10120 ** create_function_v2() is called to create a function with a destructor,
10121 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
10122 ** the number of FuncDef objects created (either 1 or 3, depending on whether
10123 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10124 ** member of each of the new FuncDef objects is set to point to the allocated
10125 ** FuncDestructor.
10126 **
10127 ** Thereafter, when one of the FuncDef objects is deleted, the reference
10128 ** count on this object is decremented. When it reaches 0, the destructor
10129 ** is invoked and the FuncDestructor structure freed.
10130 */
10131 struct FuncDestructor {
10132   int nRef;
10133   void (*xDestroy)(void *);
10134   void *pUserData;
10135 };
10136
10137 /*
10138 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
10139 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
10140 ** are assert() statements in the code to verify this.
10141 */
10142 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
10143 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
10144 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
10145 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
10146 #define SQLITE_FUNC_COUNT    0x10 /* Built-in count(*) aggregate */
10147 #define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */
10148 #define SQLITE_FUNC_LENGTH   0x40 /* Built-in length() function */
10149 #define SQLITE_FUNC_TYPEOF   0x80 /* Built-in typeof() function */
10150
10151 /*
10152 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10153 ** used to create the initializers for the FuncDef structures.
10154 **
10155 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
10156 **     Used to create a scalar function definition of a function zName 
10157 **     implemented by C function xFunc that accepts nArg arguments. The
10158 **     value passed as iArg is cast to a (void*) and made available
10159 **     as the user-data (sqlite3_user_data()) for the function. If 
10160 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10161 **
10162 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10163 **     Used to create an aggregate function definition implemented by
10164 **     the C functions xStep and xFinal. The first four parameters
10165 **     are interpreted in the same way as the first 4 parameters to
10166 **     FUNCTION().
10167 **
10168 **   LIKEFUNC(zName, nArg, pArg, flags)
10169 **     Used to create a scalar function definition of a function zName 
10170 **     that accepts nArg arguments and is implemented by a call to C 
10171 **     function likeFunc. Argument pArg is cast to a (void *) and made
10172 **     available as the function user-data (sqlite3_user_data()). The
10173 **     FuncDef.flags variable is set to the value passed as the flags
10174 **     parameter.
10175 */
10176 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10177   {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \
10178    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10179 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10180   {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
10181    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10182 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10183   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
10184    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10185 #define LIKEFUNC(zName, nArg, arg, flags) \
10186   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10187 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10188   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
10189    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10190
10191 /*
10192 ** All current savepoints are stored in a linked list starting at
10193 ** sqlite3.pSavepoint. The first element in the list is the most recently
10194 ** opened savepoint. Savepoints are added to the list by the vdbe
10195 ** OP_Savepoint instruction.
10196 */
10197 struct Savepoint {
10198   char *zName;                        /* Savepoint name (nul-terminated) */
10199   i64 nDeferredCons;                  /* Number of deferred fk violations */
10200   Savepoint *pNext;                   /* Parent savepoint (if any) */
10201 };
10202
10203 /*
10204 ** The following are used as the second parameter to sqlite3Savepoint(),
10205 ** and as the P1 argument to the OP_Savepoint instruction.
10206 */
10207 #define SAVEPOINT_BEGIN      0
10208 #define SAVEPOINT_RELEASE    1
10209 #define SAVEPOINT_ROLLBACK   2
10210
10211
10212 /*
10213 ** Each SQLite module (virtual table definition) is defined by an
10214 ** instance of the following structure, stored in the sqlite3.aModule
10215 ** hash table.
10216 */
10217 struct Module {
10218   const sqlite3_module *pModule;       /* Callback pointers */
10219   const char *zName;                   /* Name passed to create_module() */
10220   void *pAux;                          /* pAux passed to create_module() */
10221   void (*xDestroy)(void *);            /* Module destructor function */
10222 };
10223
10224 /*
10225 ** information about each column of an SQL table is held in an instance
10226 ** of this structure.
10227 */
10228 struct Column {
10229   char *zName;     /* Name of this column */
10230   Expr *pDflt;     /* Default value of this column */
10231   char *zDflt;     /* Original text of the default value */
10232   char *zType;     /* Data type for this column */
10233   char *zColl;     /* Collating sequence.  If NULL, use the default */
10234   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
10235   char affinity;   /* One of the SQLITE_AFF_... values */
10236   u16 colFlags;    /* Boolean properties.  See COLFLAG_ defines below */
10237 };
10238
10239 /* Allowed values for Column.colFlags:
10240 */
10241 #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
10242 #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
10243
10244 /*
10245 ** A "Collating Sequence" is defined by an instance of the following
10246 ** structure. Conceptually, a collating sequence consists of a name and
10247 ** a comparison routine that defines the order of that sequence.
10248 **
10249 ** If CollSeq.xCmp is NULL, it means that the
10250 ** collating sequence is undefined.  Indices built on an undefined
10251 ** collating sequence may not be read or written.
10252 */
10253 struct CollSeq {
10254   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
10255   u8 enc;               /* Text encoding handled by xCmp() */
10256   void *pUser;          /* First argument to xCmp() */
10257   int (*xCmp)(void*,int, const void*, int, const void*);
10258   void (*xDel)(void*);  /* Destructor for pUser */
10259 };
10260
10261 /*
10262 ** A sort order can be either ASC or DESC.
10263 */
10264 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
10265 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
10266
10267 /*
10268 ** Column affinity types.
10269 **
10270 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10271 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
10272 ** the speed a little by numbering the values consecutively.  
10273 **
10274 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
10275 ** when multiple affinity types are concatenated into a string and
10276 ** used as the P4 operand, they will be more readable.
10277 **
10278 ** Note also that the numeric types are grouped together so that testing
10279 ** for a numeric type is a single comparison.
10280 */
10281 #define SQLITE_AFF_TEXT     'a'
10282 #define SQLITE_AFF_NONE     'b'
10283 #define SQLITE_AFF_NUMERIC  'c'
10284 #define SQLITE_AFF_INTEGER  'd'
10285 #define SQLITE_AFF_REAL     'e'
10286
10287 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
10288
10289 /*
10290 ** The SQLITE_AFF_MASK values masks off the significant bits of an
10291 ** affinity value. 
10292 */
10293 #define SQLITE_AFF_MASK     0x67
10294
10295 /*
10296 ** Additional bit values that can be ORed with an affinity without
10297 ** changing the affinity.
10298 */
10299 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
10300 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
10301 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
10302
10303 /*
10304 ** An object of this type is created for each virtual table present in
10305 ** the database schema. 
10306 **
10307 ** If the database schema is shared, then there is one instance of this
10308 ** structure for each database connection (sqlite3*) that uses the shared
10309 ** schema. This is because each database connection requires its own unique
10310 ** instance of the sqlite3_vtab* handle used to access the virtual table 
10311 ** implementation. sqlite3_vtab* handles can not be shared between 
10312 ** database connections, even when the rest of the in-memory database 
10313 ** schema is shared, as the implementation often stores the database
10314 ** connection handle passed to it via the xConnect() or xCreate() method
10315 ** during initialization internally. This database connection handle may
10316 ** then be used by the virtual table implementation to access real tables 
10317 ** within the database. So that they appear as part of the callers 
10318 ** transaction, these accesses need to be made via the same database 
10319 ** connection as that used to execute SQL operations on the virtual table.
10320 **
10321 ** All VTable objects that correspond to a single table in a shared
10322 ** database schema are initially stored in a linked-list pointed to by
10323 ** the Table.pVTable member variable of the corresponding Table object.
10324 ** When an sqlite3_prepare() operation is required to access the virtual
10325 ** table, it searches the list for the VTable that corresponds to the
10326 ** database connection doing the preparing so as to use the correct
10327 ** sqlite3_vtab* handle in the compiled query.
10328 **
10329 ** When an in-memory Table object is deleted (for example when the
10330 ** schema is being reloaded for some reason), the VTable objects are not 
10331 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
10332 ** immediately. Instead, they are moved from the Table.pVTable list to
10333 ** another linked list headed by the sqlite3.pDisconnect member of the
10334 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
10335 ** next time a statement is prepared using said sqlite3*. This is done
10336 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10337 ** Refer to comments above function sqlite3VtabUnlockList() for an
10338 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10339 ** list without holding the corresponding sqlite3.mutex mutex.
10340 **
10341 ** The memory for objects of this type is always allocated by 
10342 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
10343 ** the first argument.
10344 */
10345 struct VTable {
10346   sqlite3 *db;              /* Database connection associated with this table */
10347   Module *pMod;             /* Pointer to module implementation */
10348   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
10349   int nRef;                 /* Number of pointers to this structure */
10350   u8 bConstraint;           /* True if constraints are supported */
10351   int iSavepoint;           /* Depth of the SAVEPOINT stack */
10352   VTable *pNext;            /* Next in linked list (see above) */
10353 };
10354
10355 /*
10356 ** Each SQL table is represented in memory by an instance of the
10357 ** following structure.
10358 **
10359 ** Table.zName is the name of the table.  The case of the original
10360 ** CREATE TABLE statement is stored, but case is not significant for
10361 ** comparisons.
10362 **
10363 ** Table.nCol is the number of columns in this table.  Table.aCol is a
10364 ** pointer to an array of Column structures, one for each column.
10365 **
10366 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10367 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
10368 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10369 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
10370 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
10371 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
10372 ** the table has any PRIMARY KEY, INTEGER or otherwise.
10373 **
10374 ** Table.tnum is the page number for the root BTree page of the table in the
10375 ** database file.  If Table.iDb is the index of the database table backend
10376 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
10377 ** holds temporary tables and indices.  If TF_Ephemeral is set
10378 ** then the table is stored in a file that is automatically deleted
10379 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
10380 ** refers VDBE cursor number that holds the table open, not to the root
10381 ** page number.  Transient tables are used to hold the results of a
10382 ** sub-query that appears instead of a real table name in the FROM clause 
10383 ** of a SELECT statement.
10384 */
10385 struct Table {
10386   char *zName;         /* Name of the table or view */
10387   Column *aCol;        /* Information about each column */
10388   Index *pIndex;       /* List of SQL indexes on this table. */
10389   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10390   FKey *pFKey;         /* Linked list of all foreign keys in this table */
10391   char *zColAff;       /* String defining the affinity of each column */
10392 #ifndef SQLITE_OMIT_CHECK
10393   ExprList *pCheck;    /* All CHECK constraints */
10394 #endif
10395   tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
10396   int tnum;            /* Root BTree node for this table (see note above) */
10397   i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
10398   i16 nCol;            /* Number of columns in this table */
10399   u16 nRef;            /* Number of pointers to this Table */
10400   u8 tabFlags;         /* Mask of TF_* values */
10401   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10402 #ifndef SQLITE_OMIT_ALTERTABLE
10403   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10404 #endif
10405 #ifndef SQLITE_OMIT_VIRTUALTABLE
10406   int nModuleArg;      /* Number of arguments to the module */
10407   char **azModuleArg;  /* Text of all module args. [0] is module name */
10408   VTable *pVTable;     /* List of VTable objects. */
10409 #endif
10410   Trigger *pTrigger;   /* List of triggers stored in pSchema */
10411   Schema *pSchema;     /* Schema that contains this table */
10412   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10413 };
10414
10415 /*
10416 ** Allowed values for Tabe.tabFlags.
10417 */
10418 #define TF_Readonly        0x01    /* Read-only system table */
10419 #define TF_Ephemeral       0x02    /* An ephemeral table */
10420 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10421 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10422 #define TF_Virtual         0x10    /* Is a virtual table */
10423
10424
10425 /*
10426 ** Test to see whether or not a table is a virtual table.  This is
10427 ** done as a macro so that it will be optimized out when virtual
10428 ** table support is omitted from the build.
10429 */
10430 #ifndef SQLITE_OMIT_VIRTUALTABLE
10431 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10432 #  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
10433 #else
10434 #  define IsVirtual(X)      0
10435 #  define IsHiddenColumn(X) 0
10436 #endif
10437
10438 /*
10439 ** Each foreign key constraint is an instance of the following structure.
10440 **
10441 ** A foreign key is associated with two tables.  The "from" table is
10442 ** the table that contains the REFERENCES clause that creates the foreign
10443 ** key.  The "to" table is the table that is named in the REFERENCES clause.
10444 ** Consider this example:
10445 **
10446 **     CREATE TABLE ex1(
10447 **       a INTEGER PRIMARY KEY,
10448 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10449 **     );
10450 **
10451 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10452 **
10453 ** Each REFERENCES clause generates an instance of the following structure
10454 ** which is attached to the from-table.  The to-table need not exist when
10455 ** the from-table is created.  The existence of the to-table is not checked.
10456 */
10457 struct FKey {
10458   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
10459   FKey *pNextFrom;  /* Next foreign key in pFrom */
10460   char *zTo;        /* Name of table that the key points to (aka: Parent) */
10461   FKey *pNextTo;    /* Next foreign key on table named zTo */
10462   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
10463   int nCol;         /* Number of columns in this key */
10464   /* EV: R-30323-21917 */
10465   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
10466   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
10467   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
10468   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
10469     int iFrom;         /* Index of column in pFrom */
10470     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
10471   } aCol[1];        /* One entry for each of nCol column s */
10472 };
10473
10474 /*
10475 ** SQLite supports many different ways to resolve a constraint
10476 ** error.  ROLLBACK processing means that a constraint violation
10477 ** causes the operation in process to fail and for the current transaction
10478 ** to be rolled back.  ABORT processing means the operation in process
10479 ** fails and any prior changes from that one operation are backed out,
10480 ** but the transaction is not rolled back.  FAIL processing means that
10481 ** the operation in progress stops and returns an error code.  But prior
10482 ** changes due to the same operation are not backed out and no rollback
10483 ** occurs.  IGNORE means that the particular row that caused the constraint
10484 ** error is not inserted or updated.  Processing continues and no error
10485 ** is returned.  REPLACE means that preexisting database rows that caused
10486 ** a UNIQUE constraint violation are removed so that the new insert or
10487 ** update can proceed.  Processing continues and no error is reported.
10488 **
10489 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10490 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10491 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10492 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10493 ** referenced table row is propagated into the row that holds the
10494 ** foreign key.
10495 ** 
10496 ** The following symbolic values are used to record which type
10497 ** of action to take.
10498 */
10499 #define OE_None     0   /* There is no constraint to check */
10500 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10501 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
10502 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
10503 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10504 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10505
10506 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10507 #define OE_SetNull  7   /* Set the foreign key value to NULL */
10508 #define OE_SetDflt  8   /* Set the foreign key value to its default */
10509 #define OE_Cascade  9   /* Cascade the changes */
10510
10511 #define OE_Default  99  /* Do whatever the default action is */
10512
10513
10514 /*
10515 ** An instance of the following structure is passed as the first
10516 ** argument to sqlite3VdbeKeyCompare and is used to control the 
10517 ** comparison of the two index keys.
10518 */
10519 struct KeyInfo {
10520   sqlite3 *db;        /* The database connection */
10521   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
10522   u16 nField;         /* Number of entries in aColl[] */
10523   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10524   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10525 };
10526
10527 /*
10528 ** An instance of the following structure holds information about a
10529 ** single index record that has already been parsed out into individual
10530 ** values.
10531 **
10532 ** A record is an object that contains one or more fields of data.
10533 ** Records are used to store the content of a table row and to store
10534 ** the key of an index.  A blob encoding of a record is created by
10535 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10536 ** OP_Column opcode.
10537 **
10538 ** This structure holds a record that has already been disassembled
10539 ** into its constituent fields.
10540 */
10541 struct UnpackedRecord {
10542   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10543   u16 nField;         /* Number of entries in apMem[] */
10544   u8 flags;           /* Boolean settings.  UNPACKED_... below */
10545   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10546   Mem *aMem;          /* Values */
10547 };
10548
10549 /*
10550 ** Allowed values of UnpackedRecord.flags
10551 */
10552 #define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
10553 #define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
10554 #define UNPACKED_PREFIX_SEARCH 0x04  /* Ignore final (rowid) field */
10555
10556 /*
10557 ** Each SQL index is represented in memory by an
10558 ** instance of the following structure.
10559 **
10560 ** The columns of the table that are to be indexed are described
10561 ** by the aiColumn[] field of this structure.  For example, suppose
10562 ** we have the following table and index:
10563 **
10564 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10565 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
10566 **
10567 ** In the Table structure describing Ex1, nCol==3 because there are
10568 ** three columns in the table.  In the Index structure describing
10569 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10570 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
10571 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10572 ** The second column to be indexed (c1) has an index of 0 in
10573 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10574 **
10575 ** The Index.onError field determines whether or not the indexed columns
10576 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
10577 ** it means this is not a unique index.  Otherwise it is a unique index
10578 ** and the value of Index.onError indicate the which conflict resolution 
10579 ** algorithm to employ whenever an attempt is made to insert a non-unique
10580 ** element.
10581 */
10582 struct Index {
10583   char *zName;             /* Name of this index */
10584   int *aiColumn;           /* Which columns are used by this index.  1st is 0 */
10585   tRowcnt *aiRowEst;       /* From ANALYZE: Est. rows selected by each column */
10586   Table *pTable;           /* The SQL table being indexed */
10587   char *zColAff;           /* String defining the affinity of each column */
10588   Index *pNext;            /* The next index associated with the same table */
10589   Schema *pSchema;         /* Schema containing this index */
10590   u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
10591   char **azColl;           /* Array of collation sequence names for index */
10592   int tnum;                /* DB Page containing root of this index */
10593   u16 nColumn;             /* Number of columns in table used by this index */
10594   u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10595   unsigned autoIndex:2;    /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
10596   unsigned bUnordered:1;   /* Use this index for == or IN queries only */
10597 #ifdef SQLITE_ENABLE_STAT3
10598   int nSample;             /* Number of elements in aSample[] */
10599   tRowcnt avgEq;           /* Average nEq value for key values not in aSample */
10600   IndexSample *aSample;    /* Samples of the left-most key */
10601 #endif
10602 };
10603
10604 /*
10605 ** Each sample stored in the sqlite_stat3 table is represented in memory 
10606 ** using a structure of this type.  See documentation at the top of the
10607 ** analyze.c source file for additional information.
10608 */
10609 struct IndexSample {
10610   union {
10611     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10612     double r;       /* Value if eType is SQLITE_FLOAT */
10613     i64 i;          /* Value if eType is SQLITE_INTEGER */
10614   } u;
10615   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10616   int nByte;        /* Size in byte of text or blob. */
10617   tRowcnt nEq;      /* Est. number of rows where the key equals this sample */
10618   tRowcnt nLt;      /* Est. number of rows where key is less than this sample */
10619   tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */
10620 };
10621
10622 /*
10623 ** Each token coming out of the lexer is an instance of
10624 ** this structure.  Tokens are also used as part of an expression.
10625 **
10626 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10627 ** may contain random values.  Do not make any assumptions about Token.dyn
10628 ** and Token.n when Token.z==0.
10629 */
10630 struct Token {
10631   const char *z;     /* Text of the token.  Not NULL-terminated! */
10632   unsigned int n;    /* Number of characters in this token */
10633 };
10634
10635 /*
10636 ** An instance of this structure contains information needed to generate
10637 ** code for a SELECT that contains aggregate functions.
10638 **
10639 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10640 ** pointer to this structure.  The Expr.iColumn field is the index in
10641 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10642 ** code for that node.
10643 **
10644 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10645 ** original Select structure that describes the SELECT statement.  These
10646 ** fields do not need to be freed when deallocating the AggInfo structure.
10647 */
10648 struct AggInfo {
10649   u8 directMode;          /* Direct rendering mode means take data directly
10650                           ** from source tables rather than from accumulators */
10651   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10652                           ** than the source table */
10653   int sortingIdx;         /* Cursor number of the sorting index */
10654   int sortingIdxPTab;     /* Cursor number of pseudo-table */
10655   int nSortingColumn;     /* Number of columns in the sorting index */
10656   ExprList *pGroupBy;     /* The group by clause */
10657   struct AggInfo_col {    /* For each column used in source tables */
10658     Table *pTab;             /* Source table */
10659     int iTable;              /* Cursor number of the source table */
10660     int iColumn;             /* Column number within the source table */
10661     int iSorterColumn;       /* Column number in the sorting index */
10662     int iMem;                /* Memory location that acts as accumulator */
10663     Expr *pExpr;             /* The original expression */
10664   } *aCol;
10665   int nColumn;            /* Number of used entries in aCol[] */
10666   int nAccumulator;       /* Number of columns that show through to the output.
10667                           ** Additional columns are used only as parameters to
10668                           ** aggregate functions */
10669   struct AggInfo_func {   /* For each aggregate function */
10670     Expr *pExpr;             /* Expression encoding the function */
10671     FuncDef *pFunc;          /* The aggregate function implementation */
10672     int iMem;                /* Memory location that acts as accumulator */
10673     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10674   } *aFunc;
10675   int nFunc;              /* Number of entries in aFunc[] */
10676 };
10677
10678 /*
10679 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10680 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
10681 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
10682 ** it uses less memory in the Expr object, which is a big memory user
10683 ** in systems with lots of prepared statements.  And few applications
10684 ** need more than about 10 or 20 variables.  But some extreme users want
10685 ** to have prepared statements with over 32767 variables, and for them
10686 ** the option is available (at compile-time).
10687 */
10688 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
10689 typedef i16 ynVar;
10690 #else
10691 typedef int ynVar;
10692 #endif
10693
10694 /*
10695 ** Each node of an expression in the parse tree is an instance
10696 ** of this structure.
10697 **
10698 ** Expr.op is the opcode. The integer parser token codes are reused
10699 ** as opcodes here. For example, the parser defines TK_GE to be an integer
10700 ** code representing the ">=" operator. This same integer code is reused
10701 ** to represent the greater-than-or-equal-to operator in the expression
10702 ** tree.
10703 **
10704 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
10705 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10706 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
10707 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10708 ** then Expr.token contains the name of the function.
10709 **
10710 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10711 ** binary operator. Either or both may be NULL.
10712 **
10713 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
10714 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10715 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10716 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10717 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
10718 ** valid.
10719 **
10720 ** An expression of the form ID or ID.ID refers to a column in a table.
10721 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10722 ** the integer cursor number of a VDBE cursor pointing to that table and
10723 ** Expr.iColumn is the column number for the specific column.  If the
10724 ** expression is used as a result in an aggregate SELECT, then the
10725 ** value is also stored in the Expr.iAgg column in the aggregate so that
10726 ** it can be accessed after all aggregates are computed.
10727 **
10728 ** If the expression is an unbound variable marker (a question mark 
10729 ** character '?' in the original SQL) then the Expr.iTable holds the index 
10730 ** number for that variable.
10731 **
10732 ** If the expression is a subquery then Expr.iColumn holds an integer
10733 ** register number containing the result of the subquery.  If the
10734 ** subquery gives a constant result, then iTable is -1.  If the subquery
10735 ** gives a different answer at different times during statement processing
10736 ** then iTable is the address of a subroutine that computes the subquery.
10737 **
10738 ** If the Expr is of type OP_Column, and the table it is selecting from
10739 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10740 ** corresponding table definition.
10741 **
10742 ** ALLOCATION NOTES:
10743 **
10744 ** Expr objects can use a lot of memory space in database schema.  To
10745 ** help reduce memory requirements, sometimes an Expr object will be
10746 ** truncated.  And to reduce the number of memory allocations, sometimes
10747 ** two or more Expr objects will be stored in a single memory allocation,
10748 ** together with Expr.zToken strings.
10749 **
10750 ** If the EP_Reduced and EP_TokenOnly flags are set when
10751 ** an Expr object is truncated.  When EP_Reduced is set, then all
10752 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10753 ** are contained within the same memory allocation.  Note, however, that
10754 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10755 ** allocated, regardless of whether or not EP_Reduced is set.
10756 */
10757 struct Expr {
10758   u8 op;                 /* Operation performed by this node */
10759   char affinity;         /* The affinity of the column or 0 if not a column */
10760   u16 flags;             /* Various flags.  EP_* See below */
10761   union {
10762     char *zToken;          /* Token value. Zero terminated and dequoted */
10763     int iValue;            /* Non-negative integer value if EP_IntValue */
10764   } u;
10765
10766   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10767   ** space is allocated for the fields below this point. An attempt to
10768   ** access them will result in a segfault or malfunction. 
10769   *********************************************************************/
10770
10771   Expr *pLeft;           /* Left subnode */
10772   Expr *pRight;          /* Right subnode */
10773   union {
10774     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10775     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10776   } x;
10777
10778   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10779   ** space is allocated for the fields below this point. An attempt to
10780   ** access them will result in a segfault or malfunction.
10781   *********************************************************************/
10782
10783 #if SQLITE_MAX_EXPR_DEPTH>0
10784   int nHeight;           /* Height of the tree headed by this node */
10785 #endif
10786   int iTable;            /* TK_COLUMN: cursor number of table holding column
10787                          ** TK_REGISTER: register number
10788                          ** TK_TRIGGER: 1 -> new, 0 -> old */
10789   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10790                          ** TK_VARIABLE: variable number (always >= 1). */
10791   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10792   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10793   u8 flags2;             /* Second set of flags.  EP2_... */
10794   u8 op2;                /* TK_REGISTER: original value of Expr.op
10795                          ** TK_COLUMN: the value of p5 for OP_Column
10796                          ** TK_AGG_FUNCTION: nesting depth */
10797   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10798   Table *pTab;           /* Table for TK_COLUMN expressions. */
10799 };
10800
10801 /*
10802 ** The following are the meanings of bits in the Expr.flags field.
10803 */
10804 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10805 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10806 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10807 #define EP_Error      0x0008  /* Expression contains one or more errors */
10808 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10809 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10810 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10811 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10812 #define EP_Collate    0x0100  /* Tree contains a TK_COLLATE opeartor */
10813 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
10814 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10815 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10816 #define EP_Hint       0x1000  /* Not used */
10817 #define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10818 #define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10819 #define EP_Static     0x8000  /* Held in memory not obtained from malloc() */
10820
10821 /*
10822 ** The following are the meanings of bits in the Expr.flags2 field.
10823 */
10824 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10825 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10826
10827 /*
10828 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10829 ** flag on an expression structure.  This flag is used for VV&A only.  The
10830 ** routine is implemented as a macro that only works when in debugging mode,
10831 ** so as not to burden production code.
10832 */
10833 #ifdef SQLITE_DEBUG
10834 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10835 #else
10836 # define ExprSetIrreducible(X)
10837 #endif
10838
10839 /*
10840 ** These macros can be used to test, set, or clear bits in the 
10841 ** Expr.flags field.
10842 */
10843 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10844 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10845 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10846 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10847
10848 /*
10849 ** Macros to determine the number of bytes required by a normal Expr 
10850 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
10851 ** and an Expr struct with the EP_TokenOnly flag set.
10852 */
10853 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10854 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10855 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10856
10857 /*
10858 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
10859 ** above sqlite3ExprDup() for details.
10860 */
10861 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10862
10863 /*
10864 ** A list of expressions.  Each expression may optionally have a
10865 ** name.  An expr/name combination can be used in several ways, such
10866 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10867 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10868 ** also be used as the argument to a function, in which case the a.zName
10869 ** field is not used.
10870 **
10871 ** By default the Expr.zSpan field holds a human-readable description of
10872 ** the expression that is used in the generation of error messages and
10873 ** column labels.  In this case, Expr.zSpan is typically the text of a
10874 ** column expression as it exists in a SELECT statement.  However, if
10875 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
10876 ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
10877 ** form is used for name resolution with nested FROM clauses.
10878 */
10879 struct ExprList {
10880   int nExpr;             /* Number of expressions on the list */
10881   int iECursor;          /* VDBE Cursor associated with this ExprList */
10882   struct ExprList_item { /* For each expression in the list */
10883     Expr *pExpr;            /* The list of expressions */
10884     char *zName;            /* Token associated with this expression */
10885     char *zSpan;            /* Original text of the expression */
10886     u8 sortOrder;           /* 1 for DESC or 0 for ASC */
10887     unsigned done :1;       /* A flag to indicate when processing is finished */
10888     unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
10889     u16 iOrderByCol;        /* For ORDER BY, column number in result set */
10890     u16 iAlias;             /* Index into Parse.aAlias[] for zName */
10891   } *a;                  /* Alloc a power of two greater or equal to nExpr */
10892 };
10893
10894 /*
10895 ** An instance of this structure is used by the parser to record both
10896 ** the parse tree for an expression and the span of input text for an
10897 ** expression.
10898 */
10899 struct ExprSpan {
10900   Expr *pExpr;          /* The expression parse tree */
10901   const char *zStart;   /* First character of input text */
10902   const char *zEnd;     /* One character past the end of input text */
10903 };
10904
10905 /*
10906 ** An instance of this structure can hold a simple list of identifiers,
10907 ** such as the list "a,b,c" in the following statements:
10908 **
10909 **      INSERT INTO t(a,b,c) VALUES ...;
10910 **      CREATE INDEX idx ON t(a,b,c);
10911 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10912 **
10913 ** The IdList.a.idx field is used when the IdList represents the list of
10914 ** column names after a table name in an INSERT statement.  In the statement
10915 **
10916 **     INSERT INTO t(a,b,c) ...
10917 **
10918 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10919 */
10920 struct IdList {
10921   struct IdList_item {
10922     char *zName;      /* Name of the identifier */
10923     int idx;          /* Index in some Table.aCol[] of a column named zName */
10924   } *a;
10925   int nId;         /* Number of identifiers on the list */
10926 };
10927
10928 /*
10929 ** The bitmask datatype defined below is used for various optimizations.
10930 **
10931 ** Changing this from a 64-bit to a 32-bit type limits the number of
10932 ** tables in a join to 32 instead of 64.  But it also reduces the size
10933 ** of the library by 738 bytes on ix86.
10934 */
10935 typedef u64 Bitmask;
10936
10937 /*
10938 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10939 */
10940 #define BMS  ((int)(sizeof(Bitmask)*8))
10941
10942 /*
10943 ** The following structure describes the FROM clause of a SELECT statement.
10944 ** Each table or subquery in the FROM clause is a separate element of
10945 ** the SrcList.a[] array.
10946 **
10947 ** With the addition of multiple database support, the following structure
10948 ** can also be used to describe a particular table such as the table that
10949 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10950 ** such a table must be a simple name: ID.  But in SQLite, the table can
10951 ** now be identified by a database name, a dot, then the table name: ID.ID.
10952 **
10953 ** The jointype starts out showing the join type between the current table
10954 ** and the next table on the list.  The parser builds the list this way.
10955 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10956 ** jointype expresses the join between the table and the previous table.
10957 **
10958 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10959 ** contains more than 63 columns and the 64-th or later column is used.
10960 */
10961 struct SrcList {
10962   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10963   i16 nAlloc;      /* Number of entries allocated in a[] below */
10964   struct SrcList_item {
10965     Schema *pSchema;  /* Schema to which this item is fixed */
10966     char *zDatabase;  /* Name of database holding this table */
10967     char *zName;      /* Name of the table */
10968     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10969     Table *pTab;      /* An SQL table corresponding to zName */
10970     Select *pSelect;  /* A SELECT statement used in place of a table name */
10971     int addrFillSub;  /* Address of subroutine to manifest a subquery */
10972     int regReturn;    /* Register holding return address of addrFillSub */
10973     u8 jointype;      /* Type of join between this able and the previous */
10974     unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
10975     unsigned isCorrelated :1;  /* True if sub-query is correlated */
10976     unsigned viaCoroutine :1;  /* Implemented as a co-routine */
10977 #ifndef SQLITE_OMIT_EXPLAIN
10978     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10979 #endif
10980     int iCursor;      /* The VDBE cursor number used to access this table */
10981     Expr *pOn;        /* The ON clause of a join */
10982     IdList *pUsing;   /* The USING clause of a join */
10983     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10984     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10985     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10986   } a[1];             /* One entry for each identifier on the list */
10987 };
10988
10989 /*
10990 ** Permitted values of the SrcList.a.jointype field
10991 */
10992 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10993 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10994 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10995 #define JT_LEFT      0x0008    /* Left outer join */
10996 #define JT_RIGHT     0x0010    /* Right outer join */
10997 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10998 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10999
11000
11001 /*
11002 ** A WherePlan object holds information that describes a lookup
11003 ** strategy.
11004 **
11005 ** This object is intended to be opaque outside of the where.c module.
11006 ** It is included here only so that that compiler will know how big it
11007 ** is.  None of the fields in this object should be used outside of
11008 ** the where.c module.
11009 **
11010 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
11011 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
11012 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
11013 ** case that more than one of these conditions is true.
11014 */
11015 struct WherePlan {
11016   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
11017   u16 nEq;                       /* Number of == constraints */
11018   u16 nOBSat;                    /* Number of ORDER BY terms satisfied */
11019   double nRow;                   /* Estimated number of rows (for EQP) */
11020   union {
11021     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
11022     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
11023     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
11024   } u;
11025 };
11026
11027 /*
11028 ** For each nested loop in a WHERE clause implementation, the WhereInfo
11029 ** structure contains a single instance of this structure.  This structure
11030 ** is intended to be private to the where.c module and should not be
11031 ** access or modified by other modules.
11032 **
11033 ** The pIdxInfo field is used to help pick the best index on a
11034 ** virtual table.  The pIdxInfo pointer contains indexing
11035 ** information for the i-th table in the FROM clause before reordering.
11036 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
11037 ** All other information in the i-th WhereLevel object for the i-th table
11038 ** after FROM clause ordering.
11039 */
11040 struct WhereLevel {
11041   WherePlan plan;       /* query plan for this element of the FROM clause */
11042   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
11043   int iTabCur;          /* The VDBE cursor used to access the table */
11044   int iIdxCur;          /* The VDBE cursor used to access pIdx */
11045   int addrBrk;          /* Jump here to break out of the loop */
11046   int addrNxt;          /* Jump here to start the next IN combination */
11047   int addrCont;         /* Jump here to continue with the next loop cycle */
11048   int addrFirst;        /* First instruction of interior of the loop */
11049   u8 iFrom;             /* Which entry in the FROM clause */
11050   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
11051   int p1, p2;           /* Operands of the opcode used to ends the loop */
11052   union {               /* Information that depends on plan.wsFlags */
11053     struct {
11054       int nIn;              /* Number of entries in aInLoop[] */
11055       struct InLoop {
11056         int iCur;              /* The VDBE cursor used by this IN operator */
11057         int addrInTop;         /* Top of the IN loop */
11058         u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
11059       } *aInLoop;           /* Information about each nested IN operator */
11060     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
11061     Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
11062   } u;
11063   double rOptCost;      /* "Optimal" cost for this level */
11064
11065   /* The following field is really not part of the current level.  But
11066   ** we need a place to cache virtual table index information for each
11067   ** virtual table in the FROM clause and the WhereLevel structure is
11068   ** a convenient place since there is one WhereLevel for each FROM clause
11069   ** element.
11070   */
11071   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
11072 };
11073
11074 /*
11075 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11076 ** and the WhereInfo.wctrlFlags member.
11077 */
11078 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
11079 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
11080 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
11081 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
11082 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
11083 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
11084 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
11085 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
11086 #define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
11087
11088 /*
11089 ** The WHERE clause processing routine has two halves.  The
11090 ** first part does the start of the WHERE loop and the second
11091 ** half does the tail of the WHERE loop.  An instance of
11092 ** this structure is returned by the first half and passed
11093 ** into the second half to give some continuity.
11094 */
11095 struct WhereInfo {
11096   Parse *pParse;            /* Parsing and code generating context */
11097   SrcList *pTabList;        /* List of tables in the join */
11098   u16 nOBSat;               /* Number of ORDER BY terms satisfied by indices */
11099   u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
11100   u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
11101   u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
11102   u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
11103   int iTop;                 /* The very beginning of the WHERE loop */
11104   int iContinue;            /* Jump here to continue with next record */
11105   int iBreak;               /* Jump here to break out of the loop */
11106   int nLevel;               /* Number of nested loop */
11107   struct WhereClause *pWC;  /* Decomposition of the WHERE clause */
11108   double savedNQueryLoop;   /* pParse->nQueryLoop outside the WHERE loop */
11109   double nRowOut;           /* Estimated number of output rows */
11110   WhereLevel a[1];          /* Information about each nest loop in WHERE */
11111 };
11112
11113 /* Allowed values for WhereInfo.eDistinct and DistinctCtx.eTnctType */
11114 #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
11115 #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
11116 #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
11117 #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
11118
11119 /*
11120 ** A NameContext defines a context in which to resolve table and column
11121 ** names.  The context consists of a list of tables (the pSrcList) field and
11122 ** a list of named expression (pEList).  The named expression list may
11123 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
11124 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
11125 ** pEList corresponds to the result set of a SELECT and is NULL for
11126 ** other statements.
11127 **
11128 ** NameContexts can be nested.  When resolving names, the inner-most 
11129 ** context is searched first.  If no match is found, the next outer
11130 ** context is checked.  If there is still no match, the next context
11131 ** is checked.  This process continues until either a match is found
11132 ** or all contexts are check.  When a match is found, the nRef member of
11133 ** the context containing the match is incremented. 
11134 **
11135 ** Each subquery gets a new NameContext.  The pNext field points to the
11136 ** NameContext in the parent query.  Thus the process of scanning the
11137 ** NameContext list corresponds to searching through successively outer
11138 ** subqueries looking for a match.
11139 */
11140 struct NameContext {
11141   Parse *pParse;       /* The parser */
11142   SrcList *pSrcList;   /* One or more tables used to resolve names */
11143   ExprList *pEList;    /* Optional list of named expressions */
11144   AggInfo *pAggInfo;   /* Information about aggregates at this level */
11145   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
11146   int nRef;            /* Number of names resolved by this context */
11147   int nErr;            /* Number of errors encountered while resolving names */
11148   u8 ncFlags;          /* Zero or more NC_* flags defined below */
11149 };
11150
11151 /*
11152 ** Allowed values for the NameContext, ncFlags field.
11153 */
11154 #define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
11155 #define NC_HasAgg    0x02    /* One or more aggregate functions seen */
11156 #define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
11157 #define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
11158
11159 /*
11160 ** An instance of the following structure contains all information
11161 ** needed to generate code for a single SELECT statement.
11162 **
11163 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
11164 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
11165 ** limit and nOffset to the value of the offset (or 0 if there is not
11166 ** offset).  But later on, nLimit and nOffset become the memory locations
11167 ** in the VDBE that record the limit and offset counters.
11168 **
11169 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11170 ** These addresses must be stored so that we can go back and fill in
11171 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
11172 ** the number of columns in P2 can be computed at the same time
11173 ** as the OP_OpenEphm instruction is coded because not
11174 ** enough information about the compound query is known at that point.
11175 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11176 ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
11177 ** sequences for the ORDER BY clause.
11178 */
11179 struct Select {
11180   ExprList *pEList;      /* The fields of the result */
11181   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11182   u16 selFlags;          /* Various SF_* values */
11183   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
11184   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
11185   double nSelectRow;     /* Estimated number of result rows */
11186   SrcList *pSrc;         /* The FROM clause */
11187   Expr *pWhere;          /* The WHERE clause */
11188   ExprList *pGroupBy;    /* The GROUP BY clause */
11189   Expr *pHaving;         /* The HAVING clause */
11190   ExprList *pOrderBy;    /* The ORDER BY clause */
11191   Select *pPrior;        /* Prior select in a compound select statement */
11192   Select *pNext;         /* Next select to the left in a compound */
11193   Select *pRightmost;    /* Right-most select in a compound select statement */
11194   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
11195   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
11196 };
11197
11198 /*
11199 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
11200 ** "Select Flag".
11201 */
11202 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
11203 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
11204 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
11205 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
11206 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
11207 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
11208 #define SF_UseSorter       0x0040  /* Sort using a sorter */
11209 #define SF_Values          0x0080  /* Synthesized from VALUES clause */
11210 #define SF_Materialize     0x0100  /* Force materialization of views */
11211 #define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
11212
11213
11214 /*
11215 ** The results of a select can be distributed in several ways.  The
11216 ** "SRT" prefix means "SELECT Result Type".
11217 */
11218 #define SRT_Union        1  /* Store result as keys in an index */
11219 #define SRT_Except       2  /* Remove result from a UNION index */
11220 #define SRT_Exists       3  /* Store 1 if the result is not empty */
11221 #define SRT_Discard      4  /* Do not save the results anywhere */
11222
11223 /* The ORDER BY clause is ignored for all of the above */
11224 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
11225
11226 #define SRT_Output       5  /* Output each row of result */
11227 #define SRT_Mem          6  /* Store result in a memory cell */
11228 #define SRT_Set          7  /* Store results as keys in an index */
11229 #define SRT_Table        8  /* Store result as data with an automatic rowid */
11230 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
11231 #define SRT_Coroutine   10  /* Generate a single row of result */
11232
11233 /*
11234 ** An instance of this object describes where to put of the results of
11235 ** a SELECT statement.
11236 */
11237 struct SelectDest {
11238   u8 eDest;         /* How to dispose of the results.  On of SRT_* above. */
11239   char affSdst;     /* Affinity used when eDest==SRT_Set */
11240   int iSDParm;      /* A parameter used by the eDest disposal method */
11241   int iSdst;        /* Base register where results are written */
11242   int nSdst;        /* Number of registers allocated */
11243 };
11244
11245 /*
11246 ** During code generation of statements that do inserts into AUTOINCREMENT 
11247 ** tables, the following information is attached to the Table.u.autoInc.p
11248 ** pointer of each autoincrement table to record some side information that
11249 ** the code generator needs.  We have to keep per-table autoincrement
11250 ** information in case inserts are down within triggers.  Triggers do not
11251 ** normally coordinate their activities, but we do need to coordinate the
11252 ** loading and saving of autoincrement information.
11253 */
11254 struct AutoincInfo {
11255   AutoincInfo *pNext;   /* Next info block in a list of them all */
11256   Table *pTab;          /* Table this info block refers to */
11257   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
11258   int regCtr;           /* Memory register holding the rowid counter */
11259 };
11260
11261 /*
11262 ** Size of the column cache
11263 */
11264 #ifndef SQLITE_N_COLCACHE
11265 # define SQLITE_N_COLCACHE 10
11266 #endif
11267
11268 /*
11269 ** At least one instance of the following structure is created for each 
11270 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11271 ** statement. All such objects are stored in the linked list headed at
11272 ** Parse.pTriggerPrg and deleted once statement compilation has been
11273 ** completed.
11274 **
11275 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
11276 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11277 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11278 ** The Parse.pTriggerPrg list never contains two entries with the same
11279 ** values for both pTrigger and orconf.
11280 **
11281 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11282 ** accessed (or set to 0 for triggers fired as a result of INSERT 
11283 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11284 ** a mask of new.* columns used by the program.
11285 */
11286 struct TriggerPrg {
11287   Trigger *pTrigger;      /* Trigger this program was coded from */
11288   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
11289   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
11290   int orconf;             /* Default ON CONFLICT policy */
11291   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
11292 };
11293
11294 /*
11295 ** The yDbMask datatype for the bitmask of all attached databases.
11296 */
11297 #if SQLITE_MAX_ATTACHED>30
11298   typedef sqlite3_uint64 yDbMask;
11299 #else
11300   typedef unsigned int yDbMask;
11301 #endif
11302
11303 /*
11304 ** An SQL parser context.  A copy of this structure is passed through
11305 ** the parser and down into all the parser action routine in order to
11306 ** carry around information that is global to the entire parse.
11307 **
11308 ** The structure is divided into two parts.  When the parser and code
11309 ** generate call themselves recursively, the first part of the structure
11310 ** is constant but the second part is reset at the beginning and end of
11311 ** each recursion.
11312 **
11313 ** The nTableLock and aTableLock variables are only used if the shared-cache 
11314 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11315 ** used to store the set of table-locks required by the statement being
11316 ** compiled. Function sqlite3TableLock() is used to add entries to the
11317 ** list.
11318 */
11319 struct Parse {
11320   sqlite3 *db;         /* The main database structure */
11321   char *zErrMsg;       /* An error message */
11322   Vdbe *pVdbe;         /* An engine for executing database bytecode */
11323   int rc;              /* Return code from execution */
11324   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
11325   u8 checkSchema;      /* Causes schema cookie check after an error */
11326   u8 nested;           /* Number of nested calls to the parser/code generator */
11327   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
11328   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
11329   u8 nColCache;        /* Number of entries in aColCache[] */
11330   u8 iColCache;        /* Next entry in aColCache[] to replace */
11331   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
11332   u8 mayAbort;         /* True if statement may throw an ABORT exception */
11333   int aTempReg[8];     /* Holding area for temporary registers */
11334   int nRangeReg;       /* Size of the temporary register block */
11335   int iRangeReg;       /* First register in temporary register block */
11336   int nErr;            /* Number of errors seen */
11337   int nTab;            /* Number of previously allocated VDBE cursors */
11338   int nMem;            /* Number of memory cells used so far */
11339   int nSet;            /* Number of sets used so far */
11340   int nOnce;           /* Number of OP_Once instructions so far */
11341   int ckBase;          /* Base register of data during check constraints */
11342   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11343   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
11344   struct yColCache {
11345     int iTable;           /* Table cursor number */
11346     int iColumn;          /* Table column number */
11347     u8 tempReg;           /* iReg is a temp register that needs to be freed */
11348     int iLevel;           /* Nesting level */
11349     int iReg;             /* Reg with value of this column. 0 means none. */
11350     int lru;              /* Least recently used entry has the smallest value */
11351   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
11352   yDbMask writeMask;   /* Start a write transaction on these databases */
11353   yDbMask cookieMask;  /* Bitmask of schema verified databases */
11354   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
11355   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
11356   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
11357   int regRoot;         /* Register holding root page number for new objects */
11358   int nMaxArg;         /* Max args passed to user function by sub-program */
11359   Token constraintName;/* Name of the constraint currently being parsed */
11360 #ifndef SQLITE_OMIT_SHARED_CACHE
11361   int nTableLock;        /* Number of locks in aTableLock */
11362   TableLock *aTableLock; /* Required table locks for shared-cache mode */
11363 #endif
11364   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
11365
11366   /* Information used while coding trigger programs. */
11367   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
11368   Table *pTriggerTab;  /* Table triggers are being coded for */
11369   double nQueryLoop;   /* Estimated number of iterations of a query */
11370   u32 oldmask;         /* Mask of old.* columns referenced */
11371   u32 newmask;         /* Mask of new.* columns referenced */
11372   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
11373   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
11374   u8 disableTriggers;  /* True to disable triggers */
11375
11376   /* Above is constant between recursions.  Below is reset before and after
11377   ** each recursion */
11378
11379   int nVar;                 /* Number of '?' variables seen in the SQL so far */
11380   int nzVar;                /* Number of available slots in azVar[] */
11381   u8 explain;               /* True if the EXPLAIN flag is found on the query */
11382 #ifndef SQLITE_OMIT_VIRTUALTABLE
11383   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
11384   int nVtabLock;            /* Number of virtual tables to lock */
11385 #endif
11386   int nAlias;               /* Number of aliased result set columns */
11387   int nHeight;              /* Expression tree height of current sub-select */
11388 #ifndef SQLITE_OMIT_EXPLAIN
11389   int iSelectId;            /* ID of current select for EXPLAIN output */
11390   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
11391 #endif
11392   char **azVar;             /* Pointers to names of parameters */
11393   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
11394   int *aAlias;              /* Register used to hold aliased result */
11395   const char *zTail;        /* All SQL text past the last semicolon parsed */
11396   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
11397   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
11398   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11399   Token sNameToken;         /* Token with unqualified schema object name */
11400   Token sLastToken;         /* The last token parsed */
11401 #ifndef SQLITE_OMIT_VIRTUALTABLE
11402   Token sArg;               /* Complete text of a module argument */
11403   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
11404 #endif
11405   Table *pZombieTab;        /* List of Table objects to delete after code gen */
11406   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
11407 };
11408
11409 /*
11410 ** Return true if currently inside an sqlite3_declare_vtab() call.
11411 */
11412 #ifdef SQLITE_OMIT_VIRTUALTABLE
11413   #define IN_DECLARE_VTAB 0
11414 #else
11415   #define IN_DECLARE_VTAB (pParse->declareVtab)
11416 #endif
11417
11418 /*
11419 ** An instance of the following structure can be declared on a stack and used
11420 ** to save the Parse.zAuthContext value so that it can be restored later.
11421 */
11422 struct AuthContext {
11423   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11424   Parse *pParse;              /* The Parse structure */
11425 };
11426
11427 /*
11428 ** Bitfield flags for P5 value in various opcodes.
11429 */
11430 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11431 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11432 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11433 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11434 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
11435 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
11436 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
11437 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
11438 #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
11439 #define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */
11440 #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
11441
11442 /*
11443  * Each trigger present in the database schema is stored as an instance of
11444  * struct Trigger. 
11445  *
11446  * Pointers to instances of struct Trigger are stored in two ways.
11447  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
11448  *    database). This allows Trigger structures to be retrieved by name.
11449  * 2. All triggers associated with a single table form a linked list, using the
11450  *    pNext member of struct Trigger. A pointer to the first element of the
11451  *    linked list is stored as the "pTrigger" member of the associated
11452  *    struct Table.
11453  *
11454  * The "step_list" member points to the first element of a linked list
11455  * containing the SQL statements specified as the trigger program.
11456  */
11457 struct Trigger {
11458   char *zName;            /* The name of the trigger                        */
11459   char *table;            /* The table or view to which the trigger applies */
11460   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
11461   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11462   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
11463   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
11464                              the <column-list> is stored here */
11465   Schema *pSchema;        /* Schema containing the trigger */
11466   Schema *pTabSchema;     /* Schema containing the table */
11467   TriggerStep *step_list; /* Link list of trigger program steps             */
11468   Trigger *pNext;         /* Next trigger associated with the table */
11469 };
11470
11471 /*
11472 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
11473 ** determine which. 
11474 **
11475 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
11476 ** In that cases, the constants below can be ORed together.
11477 */
11478 #define TRIGGER_BEFORE  1
11479 #define TRIGGER_AFTER   2
11480
11481 /*
11482  * An instance of struct TriggerStep is used to store a single SQL statement
11483  * that is a part of a trigger-program. 
11484  *
11485  * Instances of struct TriggerStep are stored in a singly linked list (linked
11486  * using the "pNext" member) referenced by the "step_list" member of the 
11487  * associated struct Trigger instance. The first element of the linked list is
11488  * the first step of the trigger-program.
11489  * 
11490  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11491  * "SELECT" statement. The meanings of the other members is determined by the 
11492  * value of "op" as follows:
11493  *
11494  * (op == TK_INSERT)
11495  * orconf    -> stores the ON CONFLICT algorithm
11496  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
11497  *              this stores a pointer to the SELECT statement. Otherwise NULL.
11498  * target    -> A token holding the quoted name of the table to insert into.
11499  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11500  *              this stores values to be inserted. Otherwise NULL.
11501  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
11502  *              statement, then this stores the column-names to be
11503  *              inserted into.
11504  *
11505  * (op == TK_DELETE)
11506  * target    -> A token holding the quoted name of the table to delete from.
11507  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11508  *              Otherwise NULL.
11509  * 
11510  * (op == TK_UPDATE)
11511  * target    -> A token holding the quoted name of the table to update rows of.
11512  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11513  *              Otherwise NULL.
11514  * pExprList -> A list of the columns to update and the expressions to update
11515  *              them to. See sqlite3Update() documentation of "pChanges"
11516  *              argument.
11517  * 
11518  */
11519 struct TriggerStep {
11520   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11521   u8 orconf;           /* OE_Rollback etc. */
11522   Trigger *pTrig;      /* The trigger that this step is a part of */
11523   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11524   Token target;        /* Target table for DELETE, UPDATE, INSERT */
11525   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11526   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11527   IdList *pIdList;     /* Column names for INSERT */
11528   TriggerStep *pNext;  /* Next in the link-list */
11529   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11530 };
11531
11532 /*
11533 ** The following structure contains information used by the sqliteFix...
11534 ** routines as they walk the parse tree to make database references
11535 ** explicit.  
11536 */
11537 typedef struct DbFixer DbFixer;
11538 struct DbFixer {
11539   Parse *pParse;      /* The parsing context.  Error messages written here */
11540   Schema *pSchema;    /* Fix items to this schema */
11541   const char *zDb;    /* Make sure all objects are contained in this database */
11542   const char *zType;  /* Type of the container - used for error messages */
11543   const Token *pName; /* Name of the container - used for error messages */
11544 };
11545
11546 /*
11547 ** An objected used to accumulate the text of a string where we
11548 ** do not necessarily know how big the string will be in the end.
11549 */
11550 struct StrAccum {
11551   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
11552   char *zBase;         /* A base allocation.  Not from malloc. */
11553   char *zText;         /* The string collected so far */
11554   int  nChar;          /* Length of the string so far */
11555   int  nAlloc;         /* Amount of space allocated in zText */
11556   int  mxAlloc;        /* Maximum allowed string length */
11557   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11558   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
11559   u8   tooBig;         /* Becomes true if string size exceeds limits */
11560 };
11561
11562 /*
11563 ** A pointer to this structure is used to communicate information
11564 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11565 */
11566 typedef struct {
11567   sqlite3 *db;        /* The database being initialized */
11568   char **pzErrMsg;    /* Error message stored here */
11569   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11570   int rc;             /* Result code stored here */
11571 } InitData;
11572
11573 /*
11574 ** Structure containing global configuration data for the SQLite library.
11575 **
11576 ** This structure also contains some state information.
11577 */
11578 struct Sqlite3Config {
11579   int bMemstat;                     /* True to enable memory status */
11580   int bCoreMutex;                   /* True to enable core mutexing */
11581   int bFullMutex;                   /* True to enable full mutexing */
11582   int bOpenUri;                     /* True to interpret filenames as URIs */
11583   int bUseCis;                      /* Use covering indices for full-scans */
11584   int mxStrlen;                     /* Maximum string length */
11585   int szLookaside;                  /* Default lookaside buffer size */
11586   int nLookaside;                   /* Default lookaside buffer count */
11587   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
11588   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
11589   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
11590   void *pHeap;                      /* Heap storage space */
11591   int nHeap;                        /* Size of pHeap[] */
11592   int mnReq, mxReq;                 /* Min and max heap requests sizes */
11593   void *pScratch;                   /* Scratch memory */
11594   int szScratch;                    /* Size of each scratch buffer */
11595   int nScratch;                     /* Number of scratch buffers */
11596   void *pPage;                      /* Page cache memory */
11597   int szPage;                       /* Size of each page in pPage[] */
11598   int nPage;                        /* Number of pages in pPage[] */
11599   int mxParserStack;                /* maximum depth of the parser stack */
11600   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11601   /* The above might be initialized to non-zero.  The following need to always
11602   ** initially be zero, however. */
11603   int isInit;                       /* True after initialization has finished */
11604   int inProgress;                   /* True while initialization in progress */
11605   int isMutexInit;                  /* True after mutexes are initialized */
11606   int isMallocInit;                 /* True after malloc is initialized */
11607   int isPCacheInit;                 /* True after malloc is initialized */
11608   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
11609   int nRefInitMutex;                /* Number of users of pInitMutex */
11610   void (*xLog)(void*,int,const char*); /* Function for logging */
11611   void *pLogArg;                       /* First argument to xLog() */
11612   int bLocaltimeFault;              /* True to fail localtime() calls */
11613 #ifdef SQLITE_ENABLE_SQLLOG
11614   void(*xSqllog)(void*,sqlite3*,const char*, int);
11615   void *pSqllogArg;
11616 #endif
11617 };
11618
11619 /*
11620 ** Context pointer passed down through the tree-walk.
11621 */
11622 struct Walker {
11623   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11624   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11625   Parse *pParse;                            /* Parser context.  */
11626   int walkerDepth;                          /* Number of subqueries */
11627   union {                                   /* Extra data for callback */
11628     NameContext *pNC;                          /* Naming context */
11629     int i;                                     /* Integer value */
11630     SrcList *pSrcList;                         /* FROM clause */
11631     struct SrcCount *pSrcCount;                /* Counting column references */
11632   } u;
11633 };
11634
11635 /* Forward declarations */
11636 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11637 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11638 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11639 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11640 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11641
11642 /*
11643 ** Return code from the parse-tree walking primitives and their
11644 ** callbacks.
11645 */
11646 #define WRC_Continue    0   /* Continue down into children */
11647 #define WRC_Prune       1   /* Omit children but continue walking siblings */
11648 #define WRC_Abort       2   /* Abandon the tree walk */
11649
11650 /*
11651 ** Assuming zIn points to the first byte of a UTF-8 character,
11652 ** advance zIn to point to the first byte of the next UTF-8 character.
11653 */
11654 #define SQLITE_SKIP_UTF8(zIn) {                        \
11655   if( (*(zIn++))>=0xc0 ){                              \
11656     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11657   }                                                    \
11658 }
11659
11660 /*
11661 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
11662 ** the same name but without the _BKPT suffix.  These macros invoke
11663 ** routines that report the line-number on which the error originated
11664 ** using sqlite3_log().  The routines also provide a convenient place
11665 ** to set a debugger breakpoint.
11666 */
11667 SQLITE_PRIVATE int sqlite3CorruptError(int);
11668 SQLITE_PRIVATE int sqlite3MisuseError(int);
11669 SQLITE_PRIVATE int sqlite3CantopenError(int);
11670 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11671 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11672 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11673
11674
11675 /*
11676 ** FTS4 is really an extension for FTS3.  It is enabled using the
11677 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
11678 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11679 */
11680 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11681 # define SQLITE_ENABLE_FTS3
11682 #endif
11683
11684 /*
11685 ** The ctype.h header is needed for non-ASCII systems.  It is also
11686 ** needed by FTS3 when FTS3 is included in the amalgamation.
11687 */
11688 #if !defined(SQLITE_ASCII) || \
11689     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11690 # include <ctype.h>
11691 #endif
11692
11693 /*
11694 ** The following macros mimic the standard library functions toupper(),
11695 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11696 ** sqlite versions only work for ASCII characters, regardless of locale.
11697 */
11698 #ifdef SQLITE_ASCII
11699 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11700 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11701 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11702 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11703 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11704 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11705 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
11706 #else
11707 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
11708 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
11709 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
11710 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
11711 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
11712 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
11713 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
11714 #endif
11715
11716 /*
11717 ** Internal function prototypes
11718 */
11719 #define sqlite3StrICmp sqlite3_stricmp
11720 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11721 #define sqlite3StrNICmp sqlite3_strnicmp
11722
11723 SQLITE_PRIVATE int sqlite3MallocInit(void);
11724 SQLITE_PRIVATE void sqlite3MallocEnd(void);
11725 SQLITE_PRIVATE void *sqlite3Malloc(int);
11726 SQLITE_PRIVATE void *sqlite3MallocZero(int);
11727 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11728 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11729 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11730 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11731 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11732 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11733 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11734 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11735 SQLITE_PRIVATE int sqlite3MallocSize(void*);
11736 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11737 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11738 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11739 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11740 SQLITE_PRIVATE void sqlite3PageFree(void*);
11741 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11742 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11743 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11744
11745 /*
11746 ** On systems with ample stack space and that support alloca(), make
11747 ** use of alloca() to obtain space for large automatic objects.  By default,
11748 ** obtain space from malloc().
11749 **
11750 ** The alloca() routine never returns NULL.  This will cause code paths
11751 ** that deal with sqlite3StackAlloc() failures to be unreachable.
11752 */
11753 #ifdef SQLITE_USE_ALLOCA
11754 # define sqlite3StackAllocRaw(D,N)   alloca(N)
11755 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11756 # define sqlite3StackFree(D,P)       
11757 #else
11758 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
11759 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
11760 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
11761 #endif
11762
11763 #ifdef SQLITE_ENABLE_MEMSYS3
11764 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11765 #endif
11766 #ifdef SQLITE_ENABLE_MEMSYS5
11767 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11768 #endif
11769
11770
11771 #ifndef SQLITE_MUTEX_OMIT
11772 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11773 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11774 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
11775 SQLITE_PRIVATE   int sqlite3MutexInit(void);
11776 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
11777 #endif
11778
11779 SQLITE_PRIVATE int sqlite3StatusValue(int);
11780 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11781 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11782
11783 #ifndef SQLITE_OMIT_FLOATING_POINT
11784 SQLITE_PRIVATE   int sqlite3IsNaN(double);
11785 #else
11786 # define sqlite3IsNaN(X)  0
11787 #endif
11788
11789 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11790 #ifndef SQLITE_OMIT_TRACE
11791 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11792 #endif
11793 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11794 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11795 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11796 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11797 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
11798 #endif
11799 #if defined(SQLITE_TEST)
11800 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
11801 #endif
11802
11803 /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
11804 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
11805 SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
11806 SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
11807 SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
11808 SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
11809 SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
11810 SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
11811 SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
11812 SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
11813 SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
11814 SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
11815 #else
11816 # define sqlite3ExplainBegin(X)
11817 # define sqlite3ExplainSelect(A,B)
11818 # define sqlite3ExplainExpr(A,B)
11819 # define sqlite3ExplainExprList(A,B)
11820 # define sqlite3ExplainFinish(X)
11821 # define sqlite3VdbeExplanation(X) 0
11822 #endif
11823
11824
11825 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11826 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11827 SQLITE_PRIVATE int sqlite3Dequote(char*);
11828 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11829 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11830 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11831 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11832 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11833 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11834 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11835 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
11836 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11837 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11838 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11839 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11840 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11841 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11842 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11843 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11844 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11845 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11846 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11847 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11848 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11849 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11850 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11851 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
11852 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
11853 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
11854 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11855 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11856 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11857 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11858 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11859 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11860 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11861 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11862 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11863 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11864 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11865 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11866 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11867 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11868                     sqlite3_vfs**,char**,char **);
11869 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
11870 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
11871
11872 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11873 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11874 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11875 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11876 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11877 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11878 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11879
11880 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11881 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11882 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11883 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11884 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11885
11886 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11887
11888 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11889 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11890 #else
11891 # define sqlite3ViewGetColumnNames(A,B) 0
11892 #endif
11893
11894 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11895 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
11896 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11897 #ifndef SQLITE_OMIT_AUTOINCREMENT
11898 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
11899 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
11900 #else
11901 # define sqlite3AutoincrementBegin(X)
11902 # define sqlite3AutoincrementEnd(X)
11903 #endif
11904 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
11905 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11906 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
11907 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11908 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11909 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11910 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11911 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11912                                       Token*, Select*, Expr*, IdList*);
11913 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11914 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11915 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11916 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11917 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11918 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11919 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11920                         Token*, int, int);
11921 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11922 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11923 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11924                          Expr*,ExprList*,u16,Expr*,Expr*);
11925 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11926 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11927 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11928 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11929 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11930 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
11931 #endif
11932 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11933 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11934 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
11935 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11936 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
11937 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11938 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11939 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11940 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11941 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11942 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11943 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11944 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11945 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11946 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11947 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11948 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11949 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11950 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11951 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11952 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11953 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11954 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11955 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
11956 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11957 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11958 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11959 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11960 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11961 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11962 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11963 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11964 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11965 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11966 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
11967 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11968 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11969 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11970 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11971 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
11972 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11973 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11974 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11975 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11976 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11977 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11978 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11979 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
11980 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11981 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11982 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11983 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11984 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11985 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11986 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11987 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11988 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11989 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11990 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11991 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11992                                      int*,int,int,int,int,int*);
11993 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11994 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11995 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11996 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11997 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11998 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, int);
11999 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
12000 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
12001 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
12002 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
12003 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
12004 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
12005 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
12006 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
12007 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
12008 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
12009 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
12010 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
12011 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
12012
12013 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
12014 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
12015 #endif
12016
12017 #ifndef SQLITE_OMIT_TRIGGER
12018 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
12019                            Expr*,int, int);
12020 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
12021 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
12022 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
12023 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
12024 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
12025 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
12026                             int, int, int);
12027 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
12028   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
12029 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
12030 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
12031 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
12032                                         ExprList*,Select*,u8);
12033 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
12034 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
12035 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
12036 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
12037 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
12038 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
12039 #else
12040 # define sqlite3TriggersExist(B,C,D,E,F) 0
12041 # define sqlite3DeleteTrigger(A,B)
12042 # define sqlite3DropTriggerPtr(A,B)
12043 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
12044 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
12045 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
12046 # define sqlite3TriggerList(X, Y) 0
12047 # define sqlite3ParseToplevel(p) p
12048 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
12049 #endif
12050
12051 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
12052 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
12053 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
12054 #ifndef SQLITE_OMIT_AUTHORIZATION
12055 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
12056 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
12057 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
12058 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
12059 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
12060 #else
12061 # define sqlite3AuthRead(a,b,c,d)
12062 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
12063 # define sqlite3AuthContextPush(a,b,c)
12064 # define sqlite3AuthContextPop(a)  ((void)(a))
12065 #endif
12066 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
12067 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
12068 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
12069 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
12070 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
12071 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
12072 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
12073 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
12074 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
12075 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
12076 SQLITE_PRIVATE int sqlite3Atoi(const char*);
12077 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
12078 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
12079 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
12080
12081 /*
12082 ** Routines to read and write variable-length integers.  These used to
12083 ** be defined locally, but now we use the varint routines in the util.c
12084 ** file.  Code should use the MACRO forms below, as the Varint32 versions
12085 ** are coded to assume the single byte case is already handled (which 
12086 ** the MACRO form does).
12087 */
12088 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
12089 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
12090 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
12091 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
12092 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
12093
12094 /*
12095 ** The header of a record consists of a sequence variable-length integers.
12096 ** These integers are almost always small and are encoded as a single byte.
12097 ** The following macros take advantage this fact to provide a fast encode
12098 ** and decode of the integers in a record header.  It is faster for the common
12099 ** case where the integer is a single byte.  It is a little slower when the
12100 ** integer is two or more bytes.  But overall it is faster.
12101 **
12102 ** The following expressions are equivalent:
12103 **
12104 **     x = sqlite3GetVarint32( A, &B );
12105 **     x = sqlite3PutVarint32( A, B );
12106 **
12107 **     x = getVarint32( A, B );
12108 **     x = putVarint32( A, B );
12109 **
12110 */
12111 #define getVarint32(A,B)  \
12112   (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
12113 #define putVarint32(A,B)  \
12114   (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
12115   sqlite3PutVarint32((A),(B)))
12116 #define getVarint    sqlite3GetVarint
12117 #define putVarint    sqlite3PutVarint
12118
12119
12120 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
12121 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
12122 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
12123 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
12124 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
12125 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
12126 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
12127 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
12128 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
12129 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
12130 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
12131 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
12132 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
12133 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
12134 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
12135 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
12136 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
12137 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
12138 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
12139 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
12140 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
12141 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
12142 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
12143 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
12144 SQLITE_PRIVATE int sqlite3AbsInt32(int);
12145 #ifdef SQLITE_ENABLE_8_3_NAMES
12146 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
12147 #else
12148 # define sqlite3FileSuffix3(X,Y)
12149 #endif
12150 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
12151
12152 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
12153 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
12154 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
12155                         void(*)(void*));
12156 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
12157 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
12158 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
12159 #ifdef SQLITE_ENABLE_STAT3
12160 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
12161 #endif
12162 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
12163 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
12164 #ifndef SQLITE_AMALGAMATION
12165 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
12166 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
12167 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
12168 SQLITE_PRIVATE const Token sqlite3IntTokens[];
12169 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
12170 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12171 #ifndef SQLITE_OMIT_WSD
12172 SQLITE_PRIVATE int sqlite3PendingByte;
12173 #endif
12174 #endif
12175 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
12176 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
12177 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
12178 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
12179 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
12180 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
12181 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
12182 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
12183 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
12184 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
12185 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
12186 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
12187 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
12188 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
12189 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
12190 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
12191 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
12192 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
12193 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
12194 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
12195 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
12196 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
12197 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
12198 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
12199 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
12200 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
12201 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
12202 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
12203 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
12204 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
12205 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
12206 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
12207 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
12208   void (*)(sqlite3_context*,int,sqlite3_value **),
12209   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
12210   FuncDestructor *pDestructor
12211 );
12212 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
12213 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
12214
12215 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
12216 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
12217 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
12218 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
12219 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
12220 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
12221 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
12222
12223 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
12224 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
12225
12226 /*
12227 ** The interface to the LEMON-generated parser
12228 */
12229 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
12230 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
12231 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
12232 #ifdef YYTRACKMAXSTACKDEPTH
12233 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
12234 #endif
12235
12236 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
12237 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12238 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
12239 #else
12240 # define sqlite3CloseExtensions(X)
12241 #endif
12242
12243 #ifndef SQLITE_OMIT_SHARED_CACHE
12244 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
12245 #else
12246   #define sqlite3TableLock(v,w,x,y,z)
12247 #endif
12248
12249 #ifdef SQLITE_TEST
12250 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
12251 #endif
12252
12253 #ifdef SQLITE_OMIT_VIRTUALTABLE
12254 #  define sqlite3VtabClear(Y)
12255 #  define sqlite3VtabSync(X,Y) SQLITE_OK
12256 #  define sqlite3VtabRollback(X)
12257 #  define sqlite3VtabCommit(X)
12258 #  define sqlite3VtabInSync(db) 0
12259 #  define sqlite3VtabLock(X) 
12260 #  define sqlite3VtabUnlock(X)
12261 #  define sqlite3VtabUnlockList(X)
12262 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12263 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
12264 #else
12265 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
12266 SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
12267 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
12268 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
12269 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
12270 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
12271 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
12272 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
12273 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
12274 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
12275 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12276 #endif
12277 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12278 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12279 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12280 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12281 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12282 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12283 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12284 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12285 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12286 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12287 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12288 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12289 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12290 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12291 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12292 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12293 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12294 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12295 #ifndef SQLITE_OMIT_WAL
12296 SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12297 SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12298 #endif
12299
12300 /* Declarations for functions in fkey.c. All of these are replaced by
12301 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12302 ** key functionality is available. If OMIT_TRIGGER is defined but
12303 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12304 ** this case foreign keys are parsed, but no other functionality is 
12305 ** provided (enforcement of FK constraints requires the triggers sub-system).
12306 */
12307 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12308 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
12309 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12310 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
12311 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
12312 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
12313 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
12314 #else
12315   #define sqlite3FkActions(a,b,c,d)
12316   #define sqlite3FkCheck(a,b,c,d)
12317   #define sqlite3FkDropTable(a,b,c)
12318   #define sqlite3FkOldmask(a,b)      0
12319   #define sqlite3FkRequired(a,b,c,d) 0
12320 #endif
12321 #ifndef SQLITE_OMIT_FOREIGN_KEY
12322 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
12323 SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
12324 #else
12325   #define sqlite3FkDelete(a,b)
12326   #define sqlite3FkLocateIndex(a,b,c,d,e)
12327 #endif
12328
12329
12330 /*
12331 ** Available fault injectors.  Should be numbered beginning with 0.
12332 */
12333 #define SQLITE_FAULTINJECTOR_MALLOC     0
12334 #define SQLITE_FAULTINJECTOR_COUNT      1
12335
12336 /*
12337 ** The interface to the code in fault.c used for identifying "benign"
12338 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
12339 ** is not defined.
12340 */
12341 #ifndef SQLITE_OMIT_BUILTIN_TEST
12342 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
12343 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
12344 #else
12345   #define sqlite3BeginBenignMalloc()
12346   #define sqlite3EndBenignMalloc()
12347 #endif
12348
12349 #define IN_INDEX_ROWID           1
12350 #define IN_INDEX_EPH             2
12351 #define IN_INDEX_INDEX_ASC       3
12352 #define IN_INDEX_INDEX_DESC      4
12353 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
12354
12355 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12356 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
12357 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
12358 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
12359 SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
12360 #else
12361   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
12362   #define sqlite3JournalExists(p) 1
12363 #endif
12364
12365 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
12366 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
12367 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
12368
12369 #if SQLITE_MAX_EXPR_DEPTH>0
12370 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
12371 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
12372 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
12373 #else
12374   #define sqlite3ExprSetHeight(x,y)
12375   #define sqlite3SelectExprHeight(x) 0
12376   #define sqlite3ExprCheckHeight(x,y)
12377 #endif
12378
12379 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
12380 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
12381
12382 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12383 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
12384 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
12385 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
12386 #else
12387   #define sqlite3ConnectionBlocked(x,y)
12388   #define sqlite3ConnectionUnlocked(x)
12389   #define sqlite3ConnectionClosed(x)
12390 #endif
12391
12392 #ifdef SQLITE_DEBUG
12393 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
12394 #endif
12395
12396 /*
12397 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
12398 ** sqlite3IoTrace is a pointer to a printf-like routine used to
12399 ** print I/O tracing messages. 
12400 */
12401 #ifdef SQLITE_ENABLE_IOTRACE
12402 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
12403 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
12404 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
12405 #else
12406 # define IOTRACE(A)
12407 # define sqlite3VdbeIOTraceSql(X)
12408 #endif
12409
12410 /*
12411 ** These routines are available for the mem2.c debugging memory allocator
12412 ** only.  They are used to verify that different "types" of memory
12413 ** allocations are properly tracked by the system.
12414 **
12415 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
12416 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
12417 ** a single bit set.
12418 **
12419 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
12420 ** argument match the type set by the previous sqlite3MemdebugSetType().
12421 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
12422 **
12423 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
12424 ** argument match the type set by the previous sqlite3MemdebugSetType().
12425 **
12426 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
12427 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
12428 ** it might have been allocated by lookaside, except the allocation was
12429 ** too large or lookaside was already full.  It is important to verify
12430 ** that allocations that might have been satisfied by lookaside are not
12431 ** passed back to non-lookaside free() routines.  Asserts such as the
12432 ** example above are placed on the non-lookaside free() routines to verify
12433 ** this constraint. 
12434 **
12435 ** All of this is no-op for a production build.  It only comes into
12436 ** play when the SQLITE_MEMDEBUG compile-time option is used.
12437 */
12438 #ifdef SQLITE_MEMDEBUG
12439 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
12440 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
12441 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
12442 #else
12443 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
12444 # define sqlite3MemdebugHasType(X,Y)  1
12445 # define sqlite3MemdebugNoType(X,Y)   1
12446 #endif
12447 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
12448 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
12449 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
12450 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
12451 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
12452
12453 #endif /* _SQLITEINT_H_ */
12454
12455 /************** End of sqliteInt.h *******************************************/
12456 /************** Begin file global.c ******************************************/
12457 /*
12458 ** 2008 June 13
12459 **
12460 ** The author disclaims copyright to this source code.  In place of
12461 ** a legal notice, here is a blessing:
12462 **
12463 **    May you do good and not evil.
12464 **    May you find forgiveness for yourself and forgive others.
12465 **    May you share freely, never taking more than you give.
12466 **
12467 *************************************************************************
12468 **
12469 ** This file contains definitions of global variables and contants.
12470 */
12471
12472 /* An array to map all upper-case characters into their corresponding
12473 ** lower-case character. 
12474 **
12475 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
12476 ** handle case conversions for the UTF character set since the tables
12477 ** involved are nearly as big or bigger than SQLite itself.
12478 */
12479 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
12480 #ifdef SQLITE_ASCII
12481       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
12482      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
12483      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
12484      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
12485     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
12486     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
12487     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
12488     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
12489     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
12490     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
12491     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
12492     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
12493     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
12494     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
12495     252,253,254,255
12496 #endif
12497 #ifdef SQLITE_EBCDIC
12498       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
12499      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
12500      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12501      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12502      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12503      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12504      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12505     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12506     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12507     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12508     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12509     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12510     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12511     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12512     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12513     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12514 #endif
12515 };
12516
12517 /*
12518 ** The following 256 byte lookup table is used to support SQLites built-in
12519 ** equivalents to the following standard library functions:
12520 **
12521 **   isspace()                        0x01
12522 **   isalpha()                        0x02
12523 **   isdigit()                        0x04
12524 **   isalnum()                        0x06
12525 **   isxdigit()                       0x08
12526 **   toupper()                        0x20
12527 **   SQLite identifier character      0x40
12528 **
12529 ** Bit 0x20 is set if the mapped character requires translation to upper
12530 ** case. i.e. if the character is a lower-case ASCII character.
12531 ** If x is a lower-case ASCII character, then its upper-case equivalent
12532 ** is (x - 0x20). Therefore toupper() can be implemented as:
12533 **
12534 **   (x & ~(map[x]&0x20))
12535 **
12536 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
12537 ** array. tolower() is used more often than toupper() by SQLite.
12538 **
12539 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
12540 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
12541 ** non-ASCII UTF character. Hence the test for whether or not a character is
12542 ** part of an identifier is 0x46.
12543 **
12544 ** SQLite's versions are identical to the standard versions assuming a
12545 ** locale of "C". They are implemented as macros in sqliteInt.h.
12546 */
12547 #ifdef SQLITE_ASCII
12548 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
12549   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
12550   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
12551   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
12552   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
12553   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
12554   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
12555   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
12556   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
12557
12558   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
12559   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
12560   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
12561   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
12562   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
12563   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
12564   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
12565   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
12566
12567   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
12568   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
12569   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
12570   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
12571   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
12572   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
12573   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
12574   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
12575
12576   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
12577   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
12578   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
12579   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
12580   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
12581   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
12582   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
12583   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
12584 };
12585 #endif
12586
12587 #ifndef SQLITE_USE_URI
12588 # define  SQLITE_USE_URI 0
12589 #endif
12590
12591 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
12592 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
12593 #endif
12594
12595 /*
12596 ** The following singleton contains the global configuration for
12597 ** the SQLite library.
12598 */
12599 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12600    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
12601    1,                         /* bCoreMutex */
12602    SQLITE_THREADSAFE==1,      /* bFullMutex */
12603    SQLITE_USE_URI,            /* bOpenUri */
12604    SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
12605    0x7ffffffe,                /* mxStrlen */
12606    128,                       /* szLookaside */
12607    500,                       /* nLookaside */
12608    {0,0,0,0,0,0,0,0},         /* m */
12609    {0,0,0,0,0,0,0,0,0},       /* mutex */
12610    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
12611    (void*)0,                  /* pHeap */
12612    0,                         /* nHeap */
12613    0, 0,                      /* mnHeap, mxHeap */
12614    (void*)0,                  /* pScratch */
12615    0,                         /* szScratch */
12616    0,                         /* nScratch */
12617    (void*)0,                  /* pPage */
12618    0,                         /* szPage */
12619    0,                         /* nPage */
12620    0,                         /* mxParserStack */
12621    0,                         /* sharedCacheEnabled */
12622    /* All the rest should always be initialized to zero */
12623    0,                         /* isInit */
12624    0,                         /* inProgress */
12625    0,                         /* isMutexInit */
12626    0,                         /* isMallocInit */
12627    0,                         /* isPCacheInit */
12628    0,                         /* pInitMutex */
12629    0,                         /* nRefInitMutex */
12630    0,                         /* xLog */
12631    0,                         /* pLogArg */
12632    0,                         /* bLocaltimeFault */
12633 #ifdef SQLITE_ENABLE_SQLLOG
12634    0,                         /* xSqllog */
12635    0                          /* pSqllogArg */
12636 #endif
12637 };
12638
12639
12640 /*
12641 ** Hash table for global functions - functions common to all
12642 ** database connections.  After initialization, this table is
12643 ** read-only.
12644 */
12645 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12646
12647 /*
12648 ** Constant tokens for values 0 and 1.
12649 */
12650 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12651    { "0", 1 },
12652    { "1", 1 }
12653 };
12654
12655
12656 /*
12657 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
12658 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
12659 ** the database page that contains the pending byte.  It never attempts
12660 ** to read or write that page.  The pending byte page is set assign
12661 ** for use by the VFS layers as space for managing file locks.
12662 **
12663 ** During testing, it is often desirable to move the pending byte to
12664 ** a different position in the file.  This allows code that has to
12665 ** deal with the pending byte to run on files that are much smaller
12666 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
12667 ** move the pending byte.
12668 **
12669 ** IMPORTANT:  Changing the pending byte to any value other than
12670 ** 0x40000000 results in an incompatible database file format!
12671 ** Changing the pending byte during operating results in undefined
12672 ** and dileterious behavior.
12673 */
12674 #ifndef SQLITE_OMIT_WSD
12675 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12676 #endif
12677
12678 /*
12679 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
12680 ** created by mkopcodeh.awk during compilation.  Data is obtained
12681 ** from the comments following the "case OP_xxxx:" statements in
12682 ** the vdbe.c file.  
12683 */
12684 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12685
12686 /************** End of global.c **********************************************/
12687 /************** Begin file ctime.c *******************************************/
12688 /*
12689 ** 2010 February 23
12690 **
12691 ** The author disclaims copyright to this source code.  In place of
12692 ** a legal notice, here is a blessing:
12693 **
12694 **    May you do good and not evil.
12695 **    May you find forgiveness for yourself and forgive others.
12696 **    May you share freely, never taking more than you give.
12697 **
12698 *************************************************************************
12699 **
12700 ** This file implements routines used to report what compile-time options
12701 ** SQLite was built with.
12702 */
12703
12704 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12705
12706
12707 /*
12708 ** An array of names of all compile-time options.  This array should 
12709 ** be sorted A-Z.
12710 **
12711 ** This array looks large, but in a typical installation actually uses
12712 ** only a handful of compile-time options, so most times this array is usually
12713 ** rather short and uses little memory space.
12714 */
12715 static const char * const azCompileOpt[] = {
12716
12717 /* These macros are provided to "stringify" the value of the define
12718 ** for those options in which the value is meaningful. */
12719 #define CTIMEOPT_VAL_(opt) #opt
12720 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12721
12722 #ifdef SQLITE_32BIT_ROWID
12723   "32BIT_ROWID",
12724 #endif
12725 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12726   "4_BYTE_ALIGNED_MALLOC",
12727 #endif
12728 #ifdef SQLITE_CASE_SENSITIVE_LIKE
12729   "CASE_SENSITIVE_LIKE",
12730 #endif
12731 #ifdef SQLITE_CHECK_PAGES
12732   "CHECK_PAGES",
12733 #endif
12734 #ifdef SQLITE_COVERAGE_TEST
12735   "COVERAGE_TEST",
12736 #endif
12737 #ifdef SQLITE_CURDIR
12738   "CURDIR",
12739 #endif
12740 #ifdef SQLITE_DEBUG
12741   "DEBUG",
12742 #endif
12743 #ifdef SQLITE_DEFAULT_LOCKING_MODE
12744   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12745 #endif
12746 #ifdef SQLITE_DISABLE_DIRSYNC
12747   "DISABLE_DIRSYNC",
12748 #endif
12749 #ifdef SQLITE_DISABLE_LFS
12750   "DISABLE_LFS",
12751 #endif
12752 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12753   "ENABLE_ATOMIC_WRITE",
12754 #endif
12755 #ifdef SQLITE_ENABLE_CEROD
12756   "ENABLE_CEROD",
12757 #endif
12758 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12759   "ENABLE_COLUMN_METADATA",
12760 #endif
12761 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12762   "ENABLE_EXPENSIVE_ASSERT",
12763 #endif
12764 #ifdef SQLITE_ENABLE_FTS1
12765   "ENABLE_FTS1",
12766 #endif
12767 #ifdef SQLITE_ENABLE_FTS2
12768   "ENABLE_FTS2",
12769 #endif
12770 #ifdef SQLITE_ENABLE_FTS3
12771   "ENABLE_FTS3",
12772 #endif
12773 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12774   "ENABLE_FTS3_PARENTHESIS",
12775 #endif
12776 #ifdef SQLITE_ENABLE_FTS4
12777   "ENABLE_FTS4",
12778 #endif
12779 #ifdef SQLITE_ENABLE_ICU
12780   "ENABLE_ICU",
12781 #endif
12782 #ifdef SQLITE_ENABLE_IOTRACE
12783   "ENABLE_IOTRACE",
12784 #endif
12785 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
12786   "ENABLE_LOAD_EXTENSION",
12787 #endif
12788 #ifdef SQLITE_ENABLE_LOCKING_STYLE
12789   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12790 #endif
12791 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12792   "ENABLE_MEMORY_MANAGEMENT",
12793 #endif
12794 #ifdef SQLITE_ENABLE_MEMSYS3
12795   "ENABLE_MEMSYS3",
12796 #endif
12797 #ifdef SQLITE_ENABLE_MEMSYS5
12798   "ENABLE_MEMSYS5",
12799 #endif
12800 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12801   "ENABLE_OVERSIZE_CELL_CHECK",
12802 #endif
12803 #ifdef SQLITE_ENABLE_RTREE
12804   "ENABLE_RTREE",
12805 #endif
12806 #ifdef SQLITE_ENABLE_STAT3
12807   "ENABLE_STAT3",
12808 #endif
12809 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12810   "ENABLE_UNLOCK_NOTIFY",
12811 #endif
12812 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12813   "ENABLE_UPDATE_DELETE_LIMIT",
12814 #endif
12815 #ifdef SQLITE_HAS_CODEC
12816   "HAS_CODEC",
12817 #endif
12818 #ifdef SQLITE_HAVE_ISNAN
12819   "HAVE_ISNAN",
12820 #endif
12821 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12822   "HOMEGROWN_RECURSIVE_MUTEX",
12823 #endif
12824 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12825   "IGNORE_AFP_LOCK_ERRORS",
12826 #endif
12827 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12828   "IGNORE_FLOCK_LOCK_ERRORS",
12829 #endif
12830 #ifdef SQLITE_INT64_TYPE
12831   "INT64_TYPE",
12832 #endif
12833 #ifdef SQLITE_LOCK_TRACE
12834   "LOCK_TRACE",
12835 #endif
12836 #ifdef SQLITE_MAX_SCHEMA_RETRY
12837   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
12838 #endif
12839 #ifdef SQLITE_MEMDEBUG
12840   "MEMDEBUG",
12841 #endif
12842 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12843   "MIXED_ENDIAN_64BIT_FLOAT",
12844 #endif
12845 #ifdef SQLITE_NO_SYNC
12846   "NO_SYNC",
12847 #endif
12848 #ifdef SQLITE_OMIT_ALTERTABLE
12849   "OMIT_ALTERTABLE",
12850 #endif
12851 #ifdef SQLITE_OMIT_ANALYZE
12852   "OMIT_ANALYZE",
12853 #endif
12854 #ifdef SQLITE_OMIT_ATTACH
12855   "OMIT_ATTACH",
12856 #endif
12857 #ifdef SQLITE_OMIT_AUTHORIZATION
12858   "OMIT_AUTHORIZATION",
12859 #endif
12860 #ifdef SQLITE_OMIT_AUTOINCREMENT
12861   "OMIT_AUTOINCREMENT",
12862 #endif
12863 #ifdef SQLITE_OMIT_AUTOINIT
12864   "OMIT_AUTOINIT",
12865 #endif
12866 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
12867   "OMIT_AUTOMATIC_INDEX",
12868 #endif
12869 #ifdef SQLITE_OMIT_AUTORESET
12870   "OMIT_AUTORESET",
12871 #endif
12872 #ifdef SQLITE_OMIT_AUTOVACUUM
12873   "OMIT_AUTOVACUUM",
12874 #endif
12875 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
12876   "OMIT_BETWEEN_OPTIMIZATION",
12877 #endif
12878 #ifdef SQLITE_OMIT_BLOB_LITERAL
12879   "OMIT_BLOB_LITERAL",
12880 #endif
12881 #ifdef SQLITE_OMIT_BTREECOUNT
12882   "OMIT_BTREECOUNT",
12883 #endif
12884 #ifdef SQLITE_OMIT_BUILTIN_TEST
12885   "OMIT_BUILTIN_TEST",
12886 #endif
12887 #ifdef SQLITE_OMIT_CAST
12888   "OMIT_CAST",
12889 #endif
12890 #ifdef SQLITE_OMIT_CHECK
12891   "OMIT_CHECK",
12892 #endif
12893 /* // redundant
12894 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12895 **   "OMIT_COMPILEOPTION_DIAGS",
12896 ** #endif
12897 */
12898 #ifdef SQLITE_OMIT_COMPLETE
12899   "OMIT_COMPLETE",
12900 #endif
12901 #ifdef SQLITE_OMIT_COMPOUND_SELECT
12902   "OMIT_COMPOUND_SELECT",
12903 #endif
12904 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12905   "OMIT_DATETIME_FUNCS",
12906 #endif
12907 #ifdef SQLITE_OMIT_DECLTYPE
12908   "OMIT_DECLTYPE",
12909 #endif
12910 #ifdef SQLITE_OMIT_DEPRECATED
12911   "OMIT_DEPRECATED",
12912 #endif
12913 #ifdef SQLITE_OMIT_DISKIO
12914   "OMIT_DISKIO",
12915 #endif
12916 #ifdef SQLITE_OMIT_EXPLAIN
12917   "OMIT_EXPLAIN",
12918 #endif
12919 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
12920   "OMIT_FLAG_PRAGMAS",
12921 #endif
12922 #ifdef SQLITE_OMIT_FLOATING_POINT
12923   "OMIT_FLOATING_POINT",
12924 #endif
12925 #ifdef SQLITE_OMIT_FOREIGN_KEY
12926   "OMIT_FOREIGN_KEY",
12927 #endif
12928 #ifdef SQLITE_OMIT_GET_TABLE
12929   "OMIT_GET_TABLE",
12930 #endif
12931 #ifdef SQLITE_OMIT_INCRBLOB
12932   "OMIT_INCRBLOB",
12933 #endif
12934 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
12935   "OMIT_INTEGRITY_CHECK",
12936 #endif
12937 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12938   "OMIT_LIKE_OPTIMIZATION",
12939 #endif
12940 #ifdef SQLITE_OMIT_LOAD_EXTENSION
12941   "OMIT_LOAD_EXTENSION",
12942 #endif
12943 #ifdef SQLITE_OMIT_LOCALTIME
12944   "OMIT_LOCALTIME",
12945 #endif
12946 #ifdef SQLITE_OMIT_LOOKASIDE
12947   "OMIT_LOOKASIDE",
12948 #endif
12949 #ifdef SQLITE_OMIT_MEMORYDB
12950   "OMIT_MEMORYDB",
12951 #endif
12952 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
12953   "OMIT_OR_OPTIMIZATION",
12954 #endif
12955 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
12956   "OMIT_PAGER_PRAGMAS",
12957 #endif
12958 #ifdef SQLITE_OMIT_PRAGMA
12959   "OMIT_PRAGMA",
12960 #endif
12961 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12962   "OMIT_PROGRESS_CALLBACK",
12963 #endif
12964 #ifdef SQLITE_OMIT_QUICKBALANCE
12965   "OMIT_QUICKBALANCE",
12966 #endif
12967 #ifdef SQLITE_OMIT_REINDEX
12968   "OMIT_REINDEX",
12969 #endif
12970 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12971   "OMIT_SCHEMA_PRAGMAS",
12972 #endif
12973 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12974   "OMIT_SCHEMA_VERSION_PRAGMAS",
12975 #endif
12976 #ifdef SQLITE_OMIT_SHARED_CACHE
12977   "OMIT_SHARED_CACHE",
12978 #endif
12979 #ifdef SQLITE_OMIT_SUBQUERY
12980   "OMIT_SUBQUERY",
12981 #endif
12982 #ifdef SQLITE_OMIT_TCL_VARIABLE
12983   "OMIT_TCL_VARIABLE",
12984 #endif
12985 #ifdef SQLITE_OMIT_TEMPDB
12986   "OMIT_TEMPDB",
12987 #endif
12988 #ifdef SQLITE_OMIT_TRACE
12989   "OMIT_TRACE",
12990 #endif
12991 #ifdef SQLITE_OMIT_TRIGGER
12992   "OMIT_TRIGGER",
12993 #endif
12994 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12995   "OMIT_TRUNCATE_OPTIMIZATION",
12996 #endif
12997 #ifdef SQLITE_OMIT_UTF16
12998   "OMIT_UTF16",
12999 #endif
13000 #ifdef SQLITE_OMIT_VACUUM
13001   "OMIT_VACUUM",
13002 #endif
13003 #ifdef SQLITE_OMIT_VIEW
13004   "OMIT_VIEW",
13005 #endif
13006 #ifdef SQLITE_OMIT_VIRTUALTABLE
13007   "OMIT_VIRTUALTABLE",
13008 #endif
13009 #ifdef SQLITE_OMIT_WAL
13010   "OMIT_WAL",
13011 #endif
13012 #ifdef SQLITE_OMIT_WSD
13013   "OMIT_WSD",
13014 #endif
13015 #ifdef SQLITE_OMIT_XFER_OPT
13016   "OMIT_XFER_OPT",
13017 #endif
13018 #ifdef SQLITE_PERFORMANCE_TRACE
13019   "PERFORMANCE_TRACE",
13020 #endif
13021 #ifdef SQLITE_PROXY_DEBUG
13022   "PROXY_DEBUG",
13023 #endif
13024 #ifdef SQLITE_RTREE_INT_ONLY
13025   "RTREE_INT_ONLY",
13026 #endif
13027 #ifdef SQLITE_SECURE_DELETE
13028   "SECURE_DELETE",
13029 #endif
13030 #ifdef SQLITE_SMALL_STACK
13031   "SMALL_STACK",
13032 #endif
13033 #ifdef SQLITE_SOUNDEX
13034   "SOUNDEX",
13035 #endif
13036 #ifdef SQLITE_TCL
13037   "TCL",
13038 #endif
13039 #ifdef SQLITE_TEMP_STORE
13040   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
13041 #endif
13042 #ifdef SQLITE_TEST
13043   "TEST",
13044 #endif
13045 #ifdef SQLITE_THREADSAFE
13046   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
13047 #endif
13048 #ifdef SQLITE_USE_ALLOCA
13049   "USE_ALLOCA",
13050 #endif
13051 #ifdef SQLITE_ZERO_MALLOC
13052   "ZERO_MALLOC"
13053 #endif
13054 };
13055
13056 /*
13057 ** Given the name of a compile-time option, return true if that option
13058 ** was used and false if not.
13059 **
13060 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
13061 ** is not required for a match.
13062 */
13063 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
13064   int i, n;
13065   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
13066   n = sqlite3Strlen30(zOptName);
13067
13068   /* Since ArraySize(azCompileOpt) is normally in single digits, a
13069   ** linear search is adequate.  No need for a binary search. */
13070   for(i=0; i<ArraySize(azCompileOpt); i++){
13071     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
13072        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
13073   }
13074   return 0;
13075 }
13076
13077 /*
13078 ** Return the N-th compile-time option string.  If N is out of range,
13079 ** return a NULL pointer.
13080 */
13081 SQLITE_API const char *sqlite3_compileoption_get(int N){
13082   if( N>=0 && N<ArraySize(azCompileOpt) ){
13083     return azCompileOpt[N];
13084   }
13085   return 0;
13086 }
13087
13088 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
13089
13090 /************** End of ctime.c ***********************************************/
13091 /************** Begin file status.c ******************************************/
13092 /*
13093 ** 2008 June 18
13094 **
13095 ** The author disclaims copyright to this source code.  In place of
13096 ** a legal notice, here is a blessing:
13097 **
13098 **    May you do good and not evil.
13099 **    May you find forgiveness for yourself and forgive others.
13100 **    May you share freely, never taking more than you give.
13101 **
13102 *************************************************************************
13103 **
13104 ** This module implements the sqlite3_status() interface and related
13105 ** functionality.
13106 */
13107 /************** Include vdbeInt.h in the middle of status.c ******************/
13108 /************** Begin file vdbeInt.h *****************************************/
13109 /*
13110 ** 2003 September 6
13111 **
13112 ** The author disclaims copyright to this source code.  In place of
13113 ** a legal notice, here is a blessing:
13114 **
13115 **    May you do good and not evil.
13116 **    May you find forgiveness for yourself and forgive others.
13117 **    May you share freely, never taking more than you give.
13118 **
13119 *************************************************************************
13120 ** This is the header file for information that is private to the
13121 ** VDBE.  This information used to all be at the top of the single
13122 ** source code file "vdbe.c".  When that file became too big (over
13123 ** 6000 lines long) it was split up into several smaller files and
13124 ** this header information was factored out.
13125 */
13126 #ifndef _VDBEINT_H_
13127 #define _VDBEINT_H_
13128
13129 /*
13130 ** SQL is translated into a sequence of instructions to be
13131 ** executed by a virtual machine.  Each instruction is an instance
13132 ** of the following structure.
13133 */
13134 typedef struct VdbeOp Op;
13135
13136 /*
13137 ** Boolean values
13138 */
13139 typedef unsigned char Bool;
13140
13141 /* Opaque type used by code in vdbesort.c */
13142 typedef struct VdbeSorter VdbeSorter;
13143
13144 /* Opaque type used by the explainer */
13145 typedef struct Explain Explain;
13146
13147 /*
13148 ** A cursor is a pointer into a single BTree within a database file.
13149 ** The cursor can seek to a BTree entry with a particular key, or
13150 ** loop over all entries of the Btree.  You can also insert new BTree
13151 ** entries or retrieve the key or data from the entry that the cursor
13152 ** is currently pointing to.
13153 ** 
13154 ** Every cursor that the virtual machine has open is represented by an
13155 ** instance of the following structure.
13156 */
13157 struct VdbeCursor {
13158   BtCursor *pCursor;    /* The cursor structure of the backend */
13159   Btree *pBt;           /* Separate file holding temporary table */
13160   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
13161   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
13162   int pseudoTableReg;   /* Register holding pseudotable content. */
13163   int nField;           /* Number of fields in the header */
13164   Bool zeroed;          /* True if zeroed out and ready for reuse */
13165   Bool rowidIsValid;    /* True if lastRowid is valid */
13166   Bool atFirst;         /* True if pointing to first entry */
13167   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
13168   Bool nullRow;         /* True if pointing to a row with no data */
13169   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
13170   Bool isTable;         /* True if a table requiring integer keys */
13171   Bool isIndex;         /* True if an index containing keys only - no data */
13172   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
13173   Bool isSorter;        /* True if a new-style sorter */
13174   Bool multiPseudo;     /* Multi-register pseudo-cursor */
13175   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
13176   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
13177   i64 seqCount;         /* Sequence counter */
13178   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
13179   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
13180   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
13181
13182   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
13183   ** OP_IsUnique opcode on this cursor. */
13184   int seekResult;
13185
13186   /* Cached information about the header for the data record that the
13187   ** cursor is currently pointing to.  Only valid if cacheStatus matches
13188   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
13189   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
13190   ** the cache is out of date.
13191   **
13192   ** aRow might point to (ephemeral) data for the current row, or it might
13193   ** be NULL.
13194   */
13195   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
13196   int payloadSize;      /* Total number of bytes in the record */
13197   u32 *aType;           /* Type values for all entries in the record */
13198   u32 *aOffset;         /* Cached offsets to the start of each columns data */
13199   u8 *aRow;             /* Data for the current row, if all on one page */
13200 };
13201 typedef struct VdbeCursor VdbeCursor;
13202
13203 /*
13204 ** When a sub-program is executed (OP_Program), a structure of this type
13205 ** is allocated to store the current value of the program counter, as
13206 ** well as the current memory cell array and various other frame specific
13207 ** values stored in the Vdbe struct. When the sub-program is finished, 
13208 ** these values are copied back to the Vdbe from the VdbeFrame structure,
13209 ** restoring the state of the VM to as it was before the sub-program
13210 ** began executing.
13211 **
13212 ** The memory for a VdbeFrame object is allocated and managed by a memory
13213 ** cell in the parent (calling) frame. When the memory cell is deleted or
13214 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
13215 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
13216 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
13217 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
13218 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
13219 ** child frame are released.
13220 **
13221 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
13222 ** set to NULL if the currently executing frame is the main program.
13223 */
13224 typedef struct VdbeFrame VdbeFrame;
13225 struct VdbeFrame {
13226   Vdbe *v;                /* VM this frame belongs to */
13227   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
13228   Op *aOp;                /* Program instructions for parent frame */
13229   Mem *aMem;              /* Array of memory cells for parent frame */
13230   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
13231   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
13232   void *token;            /* Copy of SubProgram.token */
13233   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
13234   int nCursor;            /* Number of entries in apCsr */
13235   int pc;                 /* Program Counter in parent (calling) frame */
13236   int nOp;                /* Size of aOp array */
13237   int nMem;               /* Number of entries in aMem */
13238   int nOnceFlag;          /* Number of entries in aOnceFlag */
13239   int nChildMem;          /* Number of memory cells for child frame */
13240   int nChildCsr;          /* Number of cursors for child frame */
13241   int nChange;            /* Statement changes (Vdbe.nChanges)     */
13242 };
13243
13244 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
13245
13246 /*
13247 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
13248 */
13249 #define CACHE_STALE 0
13250
13251 /*
13252 ** Internally, the vdbe manipulates nearly all SQL values as Mem
13253 ** structures. Each Mem struct may cache multiple representations (string,
13254 ** integer etc.) of the same value.
13255 */
13256 struct Mem {
13257   sqlite3 *db;        /* The associated database connection */
13258   char *z;            /* String or BLOB value */
13259   double r;           /* Real value */
13260   union {
13261     i64 i;              /* Integer value used when MEM_Int is set in flags */
13262     int nZero;          /* Used when bit MEM_Zero is set in flags */
13263     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
13264     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
13265     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
13266   } u;
13267   int n;              /* Number of characters in string value, excluding '\0' */
13268   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
13269   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
13270   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
13271 #ifdef SQLITE_DEBUG
13272   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
13273   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
13274 #endif
13275   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
13276   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
13277 };
13278
13279 /* One or more of the following flags are set to indicate the validOK
13280 ** representations of the value stored in the Mem struct.
13281 **
13282 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
13283 ** No other flags may be set in this case.
13284 **
13285 ** If the MEM_Str flag is set then Mem.z points at a string representation.
13286 ** Usually this is encoded in the same unicode encoding as the main
13287 ** database (see below for exceptions). If the MEM_Term flag is also
13288 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
13289 ** flags may coexist with the MEM_Str flag.
13290 */
13291 #define MEM_Null      0x0001   /* Value is NULL */
13292 #define MEM_Str       0x0002   /* Value is a string */
13293 #define MEM_Int       0x0004   /* Value is an integer */
13294 #define MEM_Real      0x0008   /* Value is a real number */
13295 #define MEM_Blob      0x0010   /* Value is a BLOB */
13296 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
13297 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
13298 #define MEM_Invalid   0x0080   /* Value is undefined */
13299 #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
13300 #define MEM_TypeMask  0x01ff   /* Mask of type bits */
13301
13302
13303 /* Whenever Mem contains a valid string or blob representation, one of
13304 ** the following flags must be set to determine the memory management
13305 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
13306 ** string is \000 or \u0000 terminated
13307 */
13308 #define MEM_Term      0x0200   /* String rep is nul terminated */
13309 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
13310 #define MEM_Static    0x0800   /* Mem.z points to a static string */
13311 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
13312 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
13313 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
13314 #ifdef SQLITE_OMIT_INCRBLOB
13315   #undef MEM_Zero
13316   #define MEM_Zero 0x0000
13317 #endif
13318
13319 /*
13320 ** Clear any existing type flags from a Mem and replace them with f
13321 */
13322 #define MemSetTypeFlag(p, f) \
13323    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
13324
13325 /*
13326 ** Return true if a memory cell is not marked as invalid.  This macro
13327 ** is for use inside assert() statements only.
13328 */
13329 #ifdef SQLITE_DEBUG
13330 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
13331 #endif
13332
13333
13334 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
13335 ** additional information about auxiliary information bound to arguments
13336 ** of the function.  This is used to implement the sqlite3_get_auxdata()
13337 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
13338 ** that can be associated with a constant argument to a function.  This
13339 ** allows functions such as "regexp" to compile their constant regular
13340 ** expression argument once and reused the compiled code for multiple
13341 ** invocations.
13342 */
13343 struct VdbeFunc {
13344   FuncDef *pFunc;               /* The definition of the function */
13345   int nAux;                     /* Number of entries allocated for apAux[] */
13346   struct AuxData {
13347     void *pAux;                   /* Aux data for the i-th argument */
13348     void (*xDelete)(void *);      /* Destructor for the aux data */
13349   } apAux[1];                   /* One slot for each function argument */
13350 };
13351
13352 /*
13353 ** The "context" argument for a installable function.  A pointer to an
13354 ** instance of this structure is the first argument to the routines used
13355 ** implement the SQL functions.
13356 **
13357 ** There is a typedef for this structure in sqlite.h.  So all routines,
13358 ** even the public interface to SQLite, can use a pointer to this structure.
13359 ** But this file is the only place where the internal details of this
13360 ** structure are known.
13361 **
13362 ** This structure is defined inside of vdbeInt.h because it uses substructures
13363 ** (Mem) which are only defined there.
13364 */
13365 struct sqlite3_context {
13366   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
13367   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
13368   Mem s;                /* The return value is stored here */
13369   Mem *pMem;            /* Memory cell used to store aggregate context */
13370   CollSeq *pColl;       /* Collating sequence */
13371   int isError;          /* Error code returned by the function. */
13372   int skipFlag;         /* Skip skip accumulator loading if true */
13373 };
13374
13375 /*
13376 ** An Explain object accumulates indented output which is helpful
13377 ** in describing recursive data structures.
13378 */
13379 struct Explain {
13380   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
13381   StrAccum str;      /* The string being accumulated */
13382   int nIndent;       /* Number of elements in aIndent */
13383   u16 aIndent[100];  /* Levels of indentation */
13384   char zBase[100];   /* Initial space */
13385 };
13386
13387 /* A bitfield type for use inside of structures.  Always follow with :N where
13388 ** N is the number of bits.
13389 */
13390 typedef unsigned bft;  /* Bit Field Type */
13391
13392 /*
13393 ** An instance of the virtual machine.  This structure contains the complete
13394 ** state of the virtual machine.
13395 **
13396 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
13397 ** is really a pointer to an instance of this structure.
13398 **
13399 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
13400 ** any virtual table method invocations made by the vdbe program. It is
13401 ** set to 2 for xDestroy method calls and 1 for all other methods. This
13402 ** variable is used for two purposes: to allow xDestroy methods to execute
13403 ** "DROP TABLE" statements and to prevent some nasty side effects of
13404 ** malloc failure when SQLite is invoked recursively by a virtual table 
13405 ** method function.
13406 */
13407 struct Vdbe {
13408   sqlite3 *db;            /* The database connection that owns this statement */
13409   Op *aOp;                /* Space to hold the virtual machine's program */
13410   Mem *aMem;              /* The memory locations */
13411   Mem **apArg;            /* Arguments to currently executing user function */
13412   Mem *aColName;          /* Column names to return */
13413   Mem *pResultSet;        /* Pointer to an array of results */
13414   int nMem;               /* Number of memory locations currently allocated */
13415   int nOp;                /* Number of instructions in the program */
13416   int nOpAlloc;           /* Number of slots allocated for aOp[] */
13417   int nLabel;             /* Number of labels used */
13418   int *aLabel;            /* Space to hold the labels */
13419   u16 nResColumn;         /* Number of columns in one row of the result set */
13420   int nCursor;            /* Number of slots in apCsr[] */
13421   u32 magic;              /* Magic number for sanity checking */
13422   char *zErrMsg;          /* Error message written here */
13423   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
13424   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
13425   Mem *aVar;              /* Values for the OP_Variable opcode. */
13426   char **azVar;           /* Name of variables */
13427   ynVar nVar;             /* Number of entries in aVar[] */
13428   ynVar nzVar;            /* Number of entries in azVar[] */
13429   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
13430   int pc;                 /* The program counter */
13431   int rc;                 /* Value to return */
13432   u8 errorAction;         /* Recovery action to do in case of an error */
13433   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
13434   bft explain:2;          /* True if EXPLAIN present on SQL command */
13435   bft inVtabMethod:2;     /* See comments above */
13436   bft changeCntOn:1;      /* True to update the change-counter */
13437   bft expired:1;          /* True if the VM needs to be recompiled */
13438   bft runOnlyOnce:1;      /* Automatically expire on reset */
13439   bft usesStmtJournal:1;  /* True if uses a statement journal */
13440   bft readOnly:1;         /* True for read-only statements */
13441   bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
13442   bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
13443   int nChange;            /* Number of db changes made since last reset */
13444   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
13445   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
13446   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
13447   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
13448 #ifndef SQLITE_OMIT_TRACE
13449   i64 startTime;          /* Time when query started - used for profiling */
13450 #endif
13451   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
13452   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
13453   char *zSql;             /* Text of the SQL statement that generated this */
13454   void *pFree;            /* Free this when deleting the vdbe */
13455 #ifdef SQLITE_DEBUG
13456   FILE *trace;            /* Write an execution trace here, if not NULL */
13457 #endif
13458 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
13459   Explain *pExplain;      /* The explainer */
13460   char *zExplain;         /* Explanation of data structures */
13461 #endif
13462   VdbeFrame *pFrame;      /* Parent frame */
13463   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
13464   int nFrame;             /* Number of frames in pFrame list */
13465   u32 expmask;            /* Binding to these vars invalidates VM */
13466   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
13467   int nOnceFlag;          /* Size of array aOnceFlag[] */
13468   u8 *aOnceFlag;          /* Flags for OP_Once */
13469 };
13470
13471 /*
13472 ** The following are allowed values for Vdbe.magic
13473 */
13474 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
13475 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
13476 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
13477 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
13478
13479 /*
13480 ** Function prototypes
13481 */
13482 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
13483 void sqliteVdbePopStack(Vdbe*,int);
13484 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
13485 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
13486 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
13487 #endif
13488 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
13489 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
13490 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
13491 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
13492 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
13493
13494 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
13495 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
13496 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
13497 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13498 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
13499 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
13500 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
13501 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
13502 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
13503 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
13504 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
13505 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
13506 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
13507 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
13508 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
13509 #ifdef SQLITE_OMIT_FLOATING_POINT
13510 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
13511 #else
13512 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
13513 #endif
13514 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
13515 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
13516 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
13517 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
13518 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
13519 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
13520 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
13521 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
13522 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
13523 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
13524 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
13525 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
13526 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
13527 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
13528 #define VdbeMemRelease(X)  \
13529   if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
13530     sqlite3VdbeMemReleaseExternal(X);
13531 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
13532 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
13533 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
13534 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
13535 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
13536 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
13537 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
13538 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
13539
13540 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
13541 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
13542 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
13543 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
13544 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
13545 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
13546 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
13547
13548 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
13549 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
13550 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
13551 #else
13552 # define sqlite3VdbeEnter(X)
13553 # define sqlite3VdbeLeave(X)
13554 #endif
13555
13556 #ifdef SQLITE_DEBUG
13557 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
13558 #endif
13559
13560 #ifndef SQLITE_OMIT_FOREIGN_KEY
13561 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
13562 #else
13563 # define sqlite3VdbeCheckFk(p,i) 0
13564 #endif
13565
13566 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
13567 #ifdef SQLITE_DEBUG
13568 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
13569 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
13570 #endif
13571 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
13572
13573 #ifndef SQLITE_OMIT_INCRBLOB
13574 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
13575   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
13576 #else
13577   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
13578   #define ExpandBlob(P) SQLITE_OK
13579 #endif
13580
13581 #endif /* !defined(_VDBEINT_H_) */
13582
13583 /************** End of vdbeInt.h *********************************************/
13584 /************** Continuing where we left off in status.c *********************/
13585
13586 /*
13587 ** Variables in which to record status information.
13588 */
13589 typedef struct sqlite3StatType sqlite3StatType;
13590 static SQLITE_WSD struct sqlite3StatType {
13591   int nowValue[10];         /* Current value */
13592   int mxValue[10];          /* Maximum value */
13593 } sqlite3Stat = { {0,}, {0,} };
13594
13595
13596 /* The "wsdStat" macro will resolve to the status information
13597 ** state vector.  If writable static data is unsupported on the target,
13598 ** we have to locate the state vector at run-time.  In the more common
13599 ** case where writable static data is supported, wsdStat can refer directly
13600 ** to the "sqlite3Stat" state vector declared above.
13601 */
13602 #ifdef SQLITE_OMIT_WSD
13603 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13604 # define wsdStat x[0]
13605 #else
13606 # define wsdStatInit
13607 # define wsdStat sqlite3Stat
13608 #endif
13609
13610 /*
13611 ** Return the current value of a status parameter.
13612 */
13613 SQLITE_PRIVATE int sqlite3StatusValue(int op){
13614   wsdStatInit;
13615   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13616   return wsdStat.nowValue[op];
13617 }
13618
13619 /*
13620 ** Add N to the value of a status record.  It is assumed that the
13621 ** caller holds appropriate locks.
13622 */
13623 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13624   wsdStatInit;
13625   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13626   wsdStat.nowValue[op] += N;
13627   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13628     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13629   }
13630 }
13631
13632 /*
13633 ** Set the value of a status to X.
13634 */
13635 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13636   wsdStatInit;
13637   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13638   wsdStat.nowValue[op] = X;
13639   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13640     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13641   }
13642 }
13643
13644 /*
13645 ** Query status information.
13646 **
13647 ** This implementation assumes that reading or writing an aligned
13648 ** 32-bit integer is an atomic operation.  If that assumption is not true,
13649 ** then this routine is not threadsafe.
13650 */
13651 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13652   wsdStatInit;
13653   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13654     return SQLITE_MISUSE_BKPT;
13655   }
13656   *pCurrent = wsdStat.nowValue[op];
13657   *pHighwater = wsdStat.mxValue[op];
13658   if( resetFlag ){
13659     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13660   }
13661   return SQLITE_OK;
13662 }
13663
13664 /*
13665 ** Query status information for a single database connection
13666 */
13667 SQLITE_API int sqlite3_db_status(
13668   sqlite3 *db,          /* The database connection whose status is desired */
13669   int op,               /* Status verb */
13670   int *pCurrent,        /* Write current value here */
13671   int *pHighwater,      /* Write high-water mark here */
13672   int resetFlag         /* Reset high-water mark if true */
13673 ){
13674   int rc = SQLITE_OK;   /* Return code */
13675   sqlite3_mutex_enter(db->mutex);
13676   switch( op ){
13677     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13678       *pCurrent = db->lookaside.nOut;
13679       *pHighwater = db->lookaside.mxOut;
13680       if( resetFlag ){
13681         db->lookaside.mxOut = db->lookaside.nOut;
13682       }
13683       break;
13684     }
13685
13686     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13687     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13688     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13689       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13690       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13691       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13692       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13693       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13694       *pCurrent = 0;
13695       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13696       if( resetFlag ){
13697         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13698       }
13699       break;
13700     }
13701
13702     /* 
13703     ** Return an approximation for the amount of memory currently used
13704     ** by all pagers associated with the given database connection.  The
13705     ** highwater mark is meaningless and is returned as zero.
13706     */
13707     case SQLITE_DBSTATUS_CACHE_USED: {
13708       int totalUsed = 0;
13709       int i;
13710       sqlite3BtreeEnterAll(db);
13711       for(i=0; i<db->nDb; i++){
13712         Btree *pBt = db->aDb[i].pBt;
13713         if( pBt ){
13714           Pager *pPager = sqlite3BtreePager(pBt);
13715           totalUsed += sqlite3PagerMemUsed(pPager);
13716         }
13717       }
13718       sqlite3BtreeLeaveAll(db);
13719       *pCurrent = totalUsed;
13720       *pHighwater = 0;
13721       break;
13722     }
13723
13724     /*
13725     ** *pCurrent gets an accurate estimate of the amount of memory used
13726     ** to store the schema for all databases (main, temp, and any ATTACHed
13727     ** databases.  *pHighwater is set to zero.
13728     */
13729     case SQLITE_DBSTATUS_SCHEMA_USED: {
13730       int i;                      /* Used to iterate through schemas */
13731       int nByte = 0;              /* Used to accumulate return value */
13732
13733       sqlite3BtreeEnterAll(db);
13734       db->pnBytesFreed = &nByte;
13735       for(i=0; i<db->nDb; i++){
13736         Schema *pSchema = db->aDb[i].pSchema;
13737         if( ALWAYS(pSchema!=0) ){
13738           HashElem *p;
13739
13740           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13741               pSchema->tblHash.count 
13742             + pSchema->trigHash.count
13743             + pSchema->idxHash.count
13744             + pSchema->fkeyHash.count
13745           );
13746           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13747           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13748           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13749           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13750
13751           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13752             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13753           }
13754           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13755             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13756           }
13757         }
13758       }
13759       db->pnBytesFreed = 0;
13760       sqlite3BtreeLeaveAll(db);
13761
13762       *pHighwater = 0;
13763       *pCurrent = nByte;
13764       break;
13765     }
13766
13767     /*
13768     ** *pCurrent gets an accurate estimate of the amount of memory used
13769     ** to store all prepared statements.
13770     ** *pHighwater is set to zero.
13771     */
13772     case SQLITE_DBSTATUS_STMT_USED: {
13773       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
13774       int nByte = 0;              /* Used to accumulate return value */
13775
13776       db->pnBytesFreed = &nByte;
13777       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13778         sqlite3VdbeClearObject(db, pVdbe);
13779         sqlite3DbFree(db, pVdbe);
13780       }
13781       db->pnBytesFreed = 0;
13782
13783       *pHighwater = 0;
13784       *pCurrent = nByte;
13785
13786       break;
13787     }
13788
13789     /*
13790     ** Set *pCurrent to the total cache hits or misses encountered by all
13791     ** pagers the database handle is connected to. *pHighwater is always set 
13792     ** to zero.
13793     */
13794     case SQLITE_DBSTATUS_CACHE_HIT:
13795     case SQLITE_DBSTATUS_CACHE_MISS:
13796     case SQLITE_DBSTATUS_CACHE_WRITE:{
13797       int i;
13798       int nRet = 0;
13799       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
13800       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
13801
13802       for(i=0; i<db->nDb; i++){
13803         if( db->aDb[i].pBt ){
13804           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
13805           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
13806         }
13807       }
13808       *pHighwater = 0;
13809       *pCurrent = nRet;
13810       break;
13811     }
13812
13813     default: {
13814       rc = SQLITE_ERROR;
13815     }
13816   }
13817   sqlite3_mutex_leave(db->mutex);
13818   return rc;
13819 }
13820
13821 /************** End of status.c **********************************************/
13822 /************** Begin file date.c ********************************************/
13823 /*
13824 ** 2003 October 31
13825 **
13826 ** The author disclaims copyright to this source code.  In place of
13827 ** a legal notice, here is a blessing:
13828 **
13829 **    May you do good and not evil.
13830 **    May you find forgiveness for yourself and forgive others.
13831 **    May you share freely, never taking more than you give.
13832 **
13833 *************************************************************************
13834 ** This file contains the C functions that implement date and time
13835 ** functions for SQLite.  
13836 **
13837 ** There is only one exported symbol in this file - the function
13838 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13839 ** All other code has file scope.
13840 **
13841 ** SQLite processes all times and dates as Julian Day numbers.  The
13842 ** dates and times are stored as the number of days since noon
13843 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13844 ** calendar system. 
13845 **
13846 ** 1970-01-01 00:00:00 is JD 2440587.5
13847 ** 2000-01-01 00:00:00 is JD 2451544.5
13848 **
13849 ** This implemention requires years to be expressed as a 4-digit number
13850 ** which means that only dates between 0000-01-01 and 9999-12-31 can
13851 ** be represented, even though julian day numbers allow a much wider
13852 ** range of dates.
13853 **
13854 ** The Gregorian calendar system is used for all dates and times,
13855 ** even those that predate the Gregorian calendar.  Historians usually
13856 ** use the Julian calendar for dates prior to 1582-10-15 and for some
13857 ** dates afterwards, depending on locale.  Beware of this difference.
13858 **
13859 ** The conversion algorithms are implemented based on descriptions
13860 ** in the following text:
13861 **
13862 **      Jean Meeus
13863 **      Astronomical Algorithms, 2nd Edition, 1998
13864 **      ISBM 0-943396-61-1
13865 **      Willmann-Bell, Inc
13866 **      Richmond, Virginia (USA)
13867 */
13868 /* #include <stdlib.h> */
13869 /* #include <assert.h> */
13870 #include <time.h>
13871
13872 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13873
13874
13875 /*
13876 ** A structure for holding a single date and time.
13877 */
13878 typedef struct DateTime DateTime;
13879 struct DateTime {
13880   sqlite3_int64 iJD; /* The julian day number times 86400000 */
13881   int Y, M, D;       /* Year, month, and day */
13882   int h, m;          /* Hour and minutes */
13883   int tz;            /* Timezone offset in minutes */
13884   double s;          /* Seconds */
13885   char validYMD;     /* True (1) if Y,M,D are valid */
13886   char validHMS;     /* True (1) if h,m,s are valid */
13887   char validJD;      /* True (1) if iJD is valid */
13888   char validTZ;      /* True (1) if tz is valid */
13889 };
13890
13891
13892 /*
13893 ** Convert zDate into one or more integers.  Additional arguments
13894 ** come in groups of 5 as follows:
13895 **
13896 **       N       number of digits in the integer
13897 **       min     minimum allowed value of the integer
13898 **       max     maximum allowed value of the integer
13899 **       nextC   first character after the integer
13900 **       pVal    where to write the integers value.
13901 **
13902 ** Conversions continue until one with nextC==0 is encountered.
13903 ** The function returns the number of successful conversions.
13904 */
13905 static int getDigits(const char *zDate, ...){
13906   va_list ap;
13907   int val;
13908   int N;
13909   int min;
13910   int max;
13911   int nextC;
13912   int *pVal;
13913   int cnt = 0;
13914   va_start(ap, zDate);
13915   do{
13916     N = va_arg(ap, int);
13917     min = va_arg(ap, int);
13918     max = va_arg(ap, int);
13919     nextC = va_arg(ap, int);
13920     pVal = va_arg(ap, int*);
13921     val = 0;
13922     while( N-- ){
13923       if( !sqlite3Isdigit(*zDate) ){
13924         goto end_getDigits;
13925       }
13926       val = val*10 + *zDate - '0';
13927       zDate++;
13928     }
13929     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
13930       goto end_getDigits;
13931     }
13932     *pVal = val;
13933     zDate++;
13934     cnt++;
13935   }while( nextC );
13936 end_getDigits:
13937   va_end(ap);
13938   return cnt;
13939 }
13940
13941 /*
13942 ** Parse a timezone extension on the end of a date-time.
13943 ** The extension is of the form:
13944 **
13945 **        (+/-)HH:MM
13946 **
13947 ** Or the "zulu" notation:
13948 **
13949 **        Z
13950 **
13951 ** If the parse is successful, write the number of minutes
13952 ** of change in p->tz and return 0.  If a parser error occurs,
13953 ** return non-zero.
13954 **
13955 ** A missing specifier is not considered an error.
13956 */
13957 static int parseTimezone(const char *zDate, DateTime *p){
13958   int sgn = 0;
13959   int nHr, nMn;
13960   int c;
13961   while( sqlite3Isspace(*zDate) ){ zDate++; }
13962   p->tz = 0;
13963   c = *zDate;
13964   if( c=='-' ){
13965     sgn = -1;
13966   }else if( c=='+' ){
13967     sgn = +1;
13968   }else if( c=='Z' || c=='z' ){
13969     zDate++;
13970     goto zulu_time;
13971   }else{
13972     return c!=0;
13973   }
13974   zDate++;
13975   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13976     return 1;
13977   }
13978   zDate += 5;
13979   p->tz = sgn*(nMn + nHr*60);
13980 zulu_time:
13981   while( sqlite3Isspace(*zDate) ){ zDate++; }
13982   return *zDate!=0;
13983 }
13984
13985 /*
13986 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13987 ** The HH, MM, and SS must each be exactly 2 digits.  The
13988 ** fractional seconds FFFF can be one or more digits.
13989 **
13990 ** Return 1 if there is a parsing error and 0 on success.
13991 */
13992 static int parseHhMmSs(const char *zDate, DateTime *p){
13993   int h, m, s;
13994   double ms = 0.0;
13995   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13996     return 1;
13997   }
13998   zDate += 5;
13999   if( *zDate==':' ){
14000     zDate++;
14001     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
14002       return 1;
14003     }
14004     zDate += 2;
14005     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
14006       double rScale = 1.0;
14007       zDate++;
14008       while( sqlite3Isdigit(*zDate) ){
14009         ms = ms*10.0 + *zDate - '0';
14010         rScale *= 10.0;
14011         zDate++;
14012       }
14013       ms /= rScale;
14014     }
14015   }else{
14016     s = 0;
14017   }
14018   p->validJD = 0;
14019   p->validHMS = 1;
14020   p->h = h;
14021   p->m = m;
14022   p->s = s + ms;
14023   if( parseTimezone(zDate, p) ) return 1;
14024   p->validTZ = (p->tz!=0)?1:0;
14025   return 0;
14026 }
14027
14028 /*
14029 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
14030 ** that the YYYY-MM-DD is according to the Gregorian calendar.
14031 **
14032 ** Reference:  Meeus page 61
14033 */
14034 static void computeJD(DateTime *p){
14035   int Y, M, D, A, B, X1, X2;
14036
14037   if( p->validJD ) return;
14038   if( p->validYMD ){
14039     Y = p->Y;
14040     M = p->M;
14041     D = p->D;
14042   }else{
14043     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
14044     M = 1;
14045     D = 1;
14046   }
14047   if( M<=2 ){
14048     Y--;
14049     M += 12;
14050   }
14051   A = Y/100;
14052   B = 2 - A + (A/4);
14053   X1 = 36525*(Y+4716)/100;
14054   X2 = 306001*(M+1)/10000;
14055   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
14056   p->validJD = 1;
14057   if( p->validHMS ){
14058     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
14059     if( p->validTZ ){
14060       p->iJD -= p->tz*60000;
14061       p->validYMD = 0;
14062       p->validHMS = 0;
14063       p->validTZ = 0;
14064     }
14065   }
14066 }
14067
14068 /*
14069 ** Parse dates of the form
14070 **
14071 **     YYYY-MM-DD HH:MM:SS.FFF
14072 **     YYYY-MM-DD HH:MM:SS
14073 **     YYYY-MM-DD HH:MM
14074 **     YYYY-MM-DD
14075 **
14076 ** Write the result into the DateTime structure and return 0
14077 ** on success and 1 if the input string is not a well-formed
14078 ** date.
14079 */
14080 static int parseYyyyMmDd(const char *zDate, DateTime *p){
14081   int Y, M, D, neg;
14082
14083   if( zDate[0]=='-' ){
14084     zDate++;
14085     neg = 1;
14086   }else{
14087     neg = 0;
14088   }
14089   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
14090     return 1;
14091   }
14092   zDate += 10;
14093   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
14094   if( parseHhMmSs(zDate, p)==0 ){
14095     /* We got the time */
14096   }else if( *zDate==0 ){
14097     p->validHMS = 0;
14098   }else{
14099     return 1;
14100   }
14101   p->validJD = 0;
14102   p->validYMD = 1;
14103   p->Y = neg ? -Y : Y;
14104   p->M = M;
14105   p->D = D;
14106   if( p->validTZ ){
14107     computeJD(p);
14108   }
14109   return 0;
14110 }
14111
14112 /*
14113 ** Set the time to the current time reported by the VFS.
14114 **
14115 ** Return the number of errors.
14116 */
14117 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
14118   sqlite3 *db = sqlite3_context_db_handle(context);
14119   if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
14120     p->validJD = 1;
14121     return 0;
14122   }else{
14123     return 1;
14124   }
14125 }
14126
14127 /*
14128 ** Attempt to parse the given string into a Julian Day Number.  Return
14129 ** the number of errors.
14130 **
14131 ** The following are acceptable forms for the input string:
14132 **
14133 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
14134 **      DDDD.DD 
14135 **      now
14136 **
14137 ** In the first form, the +/-HH:MM is always optional.  The fractional
14138 ** seconds extension (the ".FFF") is optional.  The seconds portion
14139 ** (":SS.FFF") is option.  The year and date can be omitted as long
14140 ** as there is a time string.  The time string can be omitted as long
14141 ** as there is a year and date.
14142 */
14143 static int parseDateOrTime(
14144   sqlite3_context *context, 
14145   const char *zDate, 
14146   DateTime *p
14147 ){
14148   double r;
14149   if( parseYyyyMmDd(zDate,p)==0 ){
14150     return 0;
14151   }else if( parseHhMmSs(zDate, p)==0 ){
14152     return 0;
14153   }else if( sqlite3StrICmp(zDate,"now")==0){
14154     return setDateTimeToCurrent(context, p);
14155   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
14156     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
14157     p->validJD = 1;
14158     return 0;
14159   }
14160   return 1;
14161 }
14162
14163 /*
14164 ** Compute the Year, Month, and Day from the julian day number.
14165 */
14166 static void computeYMD(DateTime *p){
14167   int Z, A, B, C, D, E, X1;
14168   if( p->validYMD ) return;
14169   if( !p->validJD ){
14170     p->Y = 2000;
14171     p->M = 1;
14172     p->D = 1;
14173   }else{
14174     Z = (int)((p->iJD + 43200000)/86400000);
14175     A = (int)((Z - 1867216.25)/36524.25);
14176     A = Z + 1 + A - (A/4);
14177     B = A + 1524;
14178     C = (int)((B - 122.1)/365.25);
14179     D = (36525*C)/100;
14180     E = (int)((B-D)/30.6001);
14181     X1 = (int)(30.6001*E);
14182     p->D = B - D - X1;
14183     p->M = E<14 ? E-1 : E-13;
14184     p->Y = p->M>2 ? C - 4716 : C - 4715;
14185   }
14186   p->validYMD = 1;
14187 }
14188
14189 /*
14190 ** Compute the Hour, Minute, and Seconds from the julian day number.
14191 */
14192 static void computeHMS(DateTime *p){
14193   int s;
14194   if( p->validHMS ) return;
14195   computeJD(p);
14196   s = (int)((p->iJD + 43200000) % 86400000);
14197   p->s = s/1000.0;
14198   s = (int)p->s;
14199   p->s -= s;
14200   p->h = s/3600;
14201   s -= p->h*3600;
14202   p->m = s/60;
14203   p->s += s - p->m*60;
14204   p->validHMS = 1;
14205 }
14206
14207 /*
14208 ** Compute both YMD and HMS
14209 */
14210 static void computeYMD_HMS(DateTime *p){
14211   computeYMD(p);
14212   computeHMS(p);
14213 }
14214
14215 /*
14216 ** Clear the YMD and HMS and the TZ
14217 */
14218 static void clearYMD_HMS_TZ(DateTime *p){
14219   p->validYMD = 0;
14220   p->validHMS = 0;
14221   p->validTZ = 0;
14222 }
14223
14224 /*
14225 ** On recent Windows platforms, the localtime_s() function is available
14226 ** as part of the "Secure CRT". It is essentially equivalent to 
14227 ** localtime_r() available under most POSIX platforms, except that the 
14228 ** order of the parameters is reversed.
14229 **
14230 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
14231 **
14232 ** If the user has not indicated to use localtime_r() or localtime_s()
14233 ** already, check for an MSVC build environment that provides 
14234 ** localtime_s().
14235 */
14236 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
14237      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
14238 #define HAVE_LOCALTIME_S 1
14239 #endif
14240
14241 #ifndef SQLITE_OMIT_LOCALTIME
14242 /*
14243 ** The following routine implements the rough equivalent of localtime_r()
14244 ** using whatever operating-system specific localtime facility that
14245 ** is available.  This routine returns 0 on success and
14246 ** non-zero on any kind of error.
14247 **
14248 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
14249 ** routine will always fail.
14250 */
14251 static int osLocaltime(time_t *t, struct tm *pTm){
14252   int rc;
14253 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
14254       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
14255   struct tm *pX;
14256 #if SQLITE_THREADSAFE>0
14257   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14258 #endif
14259   sqlite3_mutex_enter(mutex);
14260   pX = localtime(t);
14261 #ifndef SQLITE_OMIT_BUILTIN_TEST
14262   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
14263 #endif
14264   if( pX ) *pTm = *pX;
14265   sqlite3_mutex_leave(mutex);
14266   rc = pX==0;
14267 #else
14268 #ifndef SQLITE_OMIT_BUILTIN_TEST
14269   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
14270 #endif
14271 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
14272   rc = localtime_r(t, pTm)==0;
14273 #else
14274   rc = localtime_s(pTm, t);
14275 #endif /* HAVE_LOCALTIME_R */
14276 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
14277   return rc;
14278 }
14279 #endif /* SQLITE_OMIT_LOCALTIME */
14280
14281
14282 #ifndef SQLITE_OMIT_LOCALTIME
14283 /*
14284 ** Compute the difference (in milliseconds) between localtime and UTC
14285 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
14286 ** return this value and set *pRc to SQLITE_OK. 
14287 **
14288 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
14289 ** is undefined in this case.
14290 */
14291 static sqlite3_int64 localtimeOffset(
14292   DateTime *p,                    /* Date at which to calculate offset */
14293   sqlite3_context *pCtx,          /* Write error here if one occurs */
14294   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
14295 ){
14296   DateTime x, y;
14297   time_t t;
14298   struct tm sLocal;
14299
14300   /* Initialize the contents of sLocal to avoid a compiler warning. */
14301   memset(&sLocal, 0, sizeof(sLocal));
14302
14303   x = *p;
14304   computeYMD_HMS(&x);
14305   if( x.Y<1971 || x.Y>=2038 ){
14306     x.Y = 2000;
14307     x.M = 1;
14308     x.D = 1;
14309     x.h = 0;
14310     x.m = 0;
14311     x.s = 0.0;
14312   } else {
14313     int s = (int)(x.s + 0.5);
14314     x.s = s;
14315   }
14316   x.tz = 0;
14317   x.validJD = 0;
14318   computeJD(&x);
14319   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
14320   if( osLocaltime(&t, &sLocal) ){
14321     sqlite3_result_error(pCtx, "local time unavailable", -1);
14322     *pRc = SQLITE_ERROR;
14323     return 0;
14324   }
14325   y.Y = sLocal.tm_year + 1900;
14326   y.M = sLocal.tm_mon + 1;
14327   y.D = sLocal.tm_mday;
14328   y.h = sLocal.tm_hour;
14329   y.m = sLocal.tm_min;
14330   y.s = sLocal.tm_sec;
14331   y.validYMD = 1;
14332   y.validHMS = 1;
14333   y.validJD = 0;
14334   y.validTZ = 0;
14335   computeJD(&y);
14336   *pRc = SQLITE_OK;
14337   return y.iJD - x.iJD;
14338 }
14339 #endif /* SQLITE_OMIT_LOCALTIME */
14340
14341 /*
14342 ** Process a modifier to a date-time stamp.  The modifiers are
14343 ** as follows:
14344 **
14345 **     NNN days
14346 **     NNN hours
14347 **     NNN minutes
14348 **     NNN.NNNN seconds
14349 **     NNN months
14350 **     NNN years
14351 **     start of month
14352 **     start of year
14353 **     start of week
14354 **     start of day
14355 **     weekday N
14356 **     unixepoch
14357 **     localtime
14358 **     utc
14359 **
14360 ** Return 0 on success and 1 if there is any kind of error. If the error
14361 ** is in a system call (i.e. localtime()), then an error message is written
14362 ** to context pCtx. If the error is an unrecognized modifier, no error is
14363 ** written to pCtx.
14364 */
14365 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
14366   int rc = 1;
14367   int n;
14368   double r;
14369   char *z, zBuf[30];
14370   z = zBuf;
14371   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
14372     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
14373   }
14374   z[n] = 0;
14375   switch( z[0] ){
14376 #ifndef SQLITE_OMIT_LOCALTIME
14377     case 'l': {
14378       /*    localtime
14379       **
14380       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
14381       ** show local time.
14382       */
14383       if( strcmp(z, "localtime")==0 ){
14384         computeJD(p);
14385         p->iJD += localtimeOffset(p, pCtx, &rc);
14386         clearYMD_HMS_TZ(p);
14387       }
14388       break;
14389     }
14390 #endif
14391     case 'u': {
14392       /*
14393       **    unixepoch
14394       **
14395       ** Treat the current value of p->iJD as the number of
14396       ** seconds since 1970.  Convert to a real julian day number.
14397       */
14398       if( strcmp(z, "unixepoch")==0 && p->validJD ){
14399         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
14400         clearYMD_HMS_TZ(p);
14401         rc = 0;
14402       }
14403 #ifndef SQLITE_OMIT_LOCALTIME
14404       else if( strcmp(z, "utc")==0 ){
14405         sqlite3_int64 c1;
14406         computeJD(p);
14407         c1 = localtimeOffset(p, pCtx, &rc);
14408         if( rc==SQLITE_OK ){
14409           p->iJD -= c1;
14410           clearYMD_HMS_TZ(p);
14411           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
14412         }
14413       }
14414 #endif
14415       break;
14416     }
14417     case 'w': {
14418       /*
14419       **    weekday N
14420       **
14421       ** Move the date to the same time on the next occurrence of
14422       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
14423       ** date is already on the appropriate weekday, this is a no-op.
14424       */
14425       if( strncmp(z, "weekday ", 8)==0
14426                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
14427                && (n=(int)r)==r && n>=0 && r<7 ){
14428         sqlite3_int64 Z;
14429         computeYMD_HMS(p);
14430         p->validTZ = 0;
14431         p->validJD = 0;
14432         computeJD(p);
14433         Z = ((p->iJD + 129600000)/86400000) % 7;
14434         if( Z>n ) Z -= 7;
14435         p->iJD += (n - Z)*86400000;
14436         clearYMD_HMS_TZ(p);
14437         rc = 0;
14438       }
14439       break;
14440     }
14441     case 's': {
14442       /*
14443       **    start of TTTTT
14444       **
14445       ** Move the date backwards to the beginning of the current day,
14446       ** or month or year.
14447       */
14448       if( strncmp(z, "start of ", 9)!=0 ) break;
14449       z += 9;
14450       computeYMD(p);
14451       p->validHMS = 1;
14452       p->h = p->m = 0;
14453       p->s = 0.0;
14454       p->validTZ = 0;
14455       p->validJD = 0;
14456       if( strcmp(z,"month")==0 ){
14457         p->D = 1;
14458         rc = 0;
14459       }else if( strcmp(z,"year")==0 ){
14460         computeYMD(p);
14461         p->M = 1;
14462         p->D = 1;
14463         rc = 0;
14464       }else if( strcmp(z,"day")==0 ){
14465         rc = 0;
14466       }
14467       break;
14468     }
14469     case '+':
14470     case '-':
14471     case '0':
14472     case '1':
14473     case '2':
14474     case '3':
14475     case '4':
14476     case '5':
14477     case '6':
14478     case '7':
14479     case '8':
14480     case '9': {
14481       double rRounder;
14482       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
14483       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
14484         rc = 1;
14485         break;
14486       }
14487       if( z[n]==':' ){
14488         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
14489         ** specified number of hours, minutes, seconds, and fractional seconds
14490         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
14491         ** omitted.
14492         */
14493         const char *z2 = z;
14494         DateTime tx;
14495         sqlite3_int64 day;
14496         if( !sqlite3Isdigit(*z2) ) z2++;
14497         memset(&tx, 0, sizeof(tx));
14498         if( parseHhMmSs(z2, &tx) ) break;
14499         computeJD(&tx);
14500         tx.iJD -= 43200000;
14501         day = tx.iJD/86400000;
14502         tx.iJD -= day*86400000;
14503         if( z[0]=='-' ) tx.iJD = -tx.iJD;
14504         computeJD(p);
14505         clearYMD_HMS_TZ(p);
14506         p->iJD += tx.iJD;
14507         rc = 0;
14508         break;
14509       }
14510       z += n;
14511       while( sqlite3Isspace(*z) ) z++;
14512       n = sqlite3Strlen30(z);
14513       if( n>10 || n<3 ) break;
14514       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
14515       computeJD(p);
14516       rc = 0;
14517       rRounder = r<0 ? -0.5 : +0.5;
14518       if( n==3 && strcmp(z,"day")==0 ){
14519         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
14520       }else if( n==4 && strcmp(z,"hour")==0 ){
14521         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
14522       }else if( n==6 && strcmp(z,"minute")==0 ){
14523         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
14524       }else if( n==6 && strcmp(z,"second")==0 ){
14525         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
14526       }else if( n==5 && strcmp(z,"month")==0 ){
14527         int x, y;
14528         computeYMD_HMS(p);
14529         p->M += (int)r;
14530         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
14531         p->Y += x;
14532         p->M -= x*12;
14533         p->validJD = 0;
14534         computeJD(p);
14535         y = (int)r;
14536         if( y!=r ){
14537           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
14538         }
14539       }else if( n==4 && strcmp(z,"year")==0 ){
14540         int y = (int)r;
14541         computeYMD_HMS(p);
14542         p->Y += y;
14543         p->validJD = 0;
14544         computeJD(p);
14545         if( y!=r ){
14546           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
14547         }
14548       }else{
14549         rc = 1;
14550       }
14551       clearYMD_HMS_TZ(p);
14552       break;
14553     }
14554     default: {
14555       break;
14556     }
14557   }
14558   return rc;
14559 }
14560
14561 /*
14562 ** Process time function arguments.  argv[0] is a date-time stamp.
14563 ** argv[1] and following are modifiers.  Parse them all and write
14564 ** the resulting time into the DateTime structure p.  Return 0
14565 ** on success and 1 if there are any errors.
14566 **
14567 ** If there are zero parameters (if even argv[0] is undefined)
14568 ** then assume a default value of "now" for argv[0].
14569 */
14570 static int isDate(
14571   sqlite3_context *context, 
14572   int argc, 
14573   sqlite3_value **argv, 
14574   DateTime *p
14575 ){
14576   int i;
14577   const unsigned char *z;
14578   int eType;
14579   memset(p, 0, sizeof(*p));
14580   if( argc==0 ){
14581     return setDateTimeToCurrent(context, p);
14582   }
14583   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
14584                    || eType==SQLITE_INTEGER ){
14585     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
14586     p->validJD = 1;
14587   }else{
14588     z = sqlite3_value_text(argv[0]);
14589     if( !z || parseDateOrTime(context, (char*)z, p) ){
14590       return 1;
14591     }
14592   }
14593   for(i=1; i<argc; i++){
14594     z = sqlite3_value_text(argv[i]);
14595     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
14596   }
14597   return 0;
14598 }
14599
14600
14601 /*
14602 ** The following routines implement the various date and time functions
14603 ** of SQLite.
14604 */
14605
14606 /*
14607 **    julianday( TIMESTRING, MOD, MOD, ...)
14608 **
14609 ** Return the julian day number of the date specified in the arguments
14610 */
14611 static void juliandayFunc(
14612   sqlite3_context *context,
14613   int argc,
14614   sqlite3_value **argv
14615 ){
14616   DateTime x;
14617   if( isDate(context, argc, argv, &x)==0 ){
14618     computeJD(&x);
14619     sqlite3_result_double(context, x.iJD/86400000.0);
14620   }
14621 }
14622
14623 /*
14624 **    datetime( TIMESTRING, MOD, MOD, ...)
14625 **
14626 ** Return YYYY-MM-DD HH:MM:SS
14627 */
14628 static void datetimeFunc(
14629   sqlite3_context *context,
14630   int argc,
14631   sqlite3_value **argv
14632 ){
14633   DateTime x;
14634   if( isDate(context, argc, argv, &x)==0 ){
14635     char zBuf[100];
14636     computeYMD_HMS(&x);
14637     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14638                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14639     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14640   }
14641 }
14642
14643 /*
14644 **    time( TIMESTRING, MOD, MOD, ...)
14645 **
14646 ** Return HH:MM:SS
14647 */
14648 static void timeFunc(
14649   sqlite3_context *context,
14650   int argc,
14651   sqlite3_value **argv
14652 ){
14653   DateTime x;
14654   if( isDate(context, argc, argv, &x)==0 ){
14655     char zBuf[100];
14656     computeHMS(&x);
14657     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14658     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14659   }
14660 }
14661
14662 /*
14663 **    date( TIMESTRING, MOD, MOD, ...)
14664 **
14665 ** Return YYYY-MM-DD
14666 */
14667 static void dateFunc(
14668   sqlite3_context *context,
14669   int argc,
14670   sqlite3_value **argv
14671 ){
14672   DateTime x;
14673   if( isDate(context, argc, argv, &x)==0 ){
14674     char zBuf[100];
14675     computeYMD(&x);
14676     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
14677     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14678   }
14679 }
14680
14681 /*
14682 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
14683 **
14684 ** Return a string described by FORMAT.  Conversions as follows:
14685 **
14686 **   %d  day of month
14687 **   %f  ** fractional seconds  SS.SSS
14688 **   %H  hour 00-24
14689 **   %j  day of year 000-366
14690 **   %J  ** Julian day number
14691 **   %m  month 01-12
14692 **   %M  minute 00-59
14693 **   %s  seconds since 1970-01-01
14694 **   %S  seconds 00-59
14695 **   %w  day of week 0-6  sunday==0
14696 **   %W  week of year 00-53
14697 **   %Y  year 0000-9999
14698 **   %%  %
14699 */
14700 static void strftimeFunc(
14701   sqlite3_context *context,
14702   int argc,
14703   sqlite3_value **argv
14704 ){
14705   DateTime x;
14706   u64 n;
14707   size_t i,j;
14708   char *z;
14709   sqlite3 *db;
14710   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14711   char zBuf[100];
14712   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14713   db = sqlite3_context_db_handle(context);
14714   for(i=0, n=1; zFmt[i]; i++, n++){
14715     if( zFmt[i]=='%' ){
14716       switch( zFmt[i+1] ){
14717         case 'd':
14718         case 'H':
14719         case 'm':
14720         case 'M':
14721         case 'S':
14722         case 'W':
14723           n++;
14724           /* fall thru */
14725         case 'w':
14726         case '%':
14727           break;
14728         case 'f':
14729           n += 8;
14730           break;
14731         case 'j':
14732           n += 3;
14733           break;
14734         case 'Y':
14735           n += 8;
14736           break;
14737         case 's':
14738         case 'J':
14739           n += 50;
14740           break;
14741         default:
14742           return;  /* ERROR.  return a NULL */
14743       }
14744       i++;
14745     }
14746   }
14747   testcase( n==sizeof(zBuf)-1 );
14748   testcase( n==sizeof(zBuf) );
14749   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14750   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14751   if( n<sizeof(zBuf) ){
14752     z = zBuf;
14753   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14754     sqlite3_result_error_toobig(context);
14755     return;
14756   }else{
14757     z = sqlite3DbMallocRaw(db, (int)n);
14758     if( z==0 ){
14759       sqlite3_result_error_nomem(context);
14760       return;
14761     }
14762   }
14763   computeJD(&x);
14764   computeYMD_HMS(&x);
14765   for(i=j=0; zFmt[i]; i++){
14766     if( zFmt[i]!='%' ){
14767       z[j++] = zFmt[i];
14768     }else{
14769       i++;
14770       switch( zFmt[i] ){
14771         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14772         case 'f': {
14773           double s = x.s;
14774           if( s>59.999 ) s = 59.999;
14775           sqlite3_snprintf(7, &z[j],"%06.3f", s);
14776           j += sqlite3Strlen30(&z[j]);
14777           break;
14778         }
14779         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14780         case 'W': /* Fall thru */
14781         case 'j': {
14782           int nDay;             /* Number of days since 1st day of year */
14783           DateTime y = x;
14784           y.validJD = 0;
14785           y.M = 1;
14786           y.D = 1;
14787           computeJD(&y);
14788           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14789           if( zFmt[i]=='W' ){
14790             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14791             wd = (int)(((x.iJD+43200000)/86400000)%7);
14792             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14793             j += 2;
14794           }else{
14795             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14796             j += 3;
14797           }
14798           break;
14799         }
14800         case 'J': {
14801           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14802           j+=sqlite3Strlen30(&z[j]);
14803           break;
14804         }
14805         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14806         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14807         case 's': {
14808           sqlite3_snprintf(30,&z[j],"%lld",
14809                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
14810           j += sqlite3Strlen30(&z[j]);
14811           break;
14812         }
14813         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14814         case 'w': {
14815           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14816           break;
14817         }
14818         case 'Y': {
14819           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14820           break;
14821         }
14822         default:   z[j++] = '%'; break;
14823       }
14824     }
14825   }
14826   z[j] = 0;
14827   sqlite3_result_text(context, z, -1,
14828                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14829 }
14830
14831 /*
14832 ** current_time()
14833 **
14834 ** This function returns the same value as time('now').
14835 */
14836 static void ctimeFunc(
14837   sqlite3_context *context,
14838   int NotUsed,
14839   sqlite3_value **NotUsed2
14840 ){
14841   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14842   timeFunc(context, 0, 0);
14843 }
14844
14845 /*
14846 ** current_date()
14847 **
14848 ** This function returns the same value as date('now').
14849 */
14850 static void cdateFunc(
14851   sqlite3_context *context,
14852   int NotUsed,
14853   sqlite3_value **NotUsed2
14854 ){
14855   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14856   dateFunc(context, 0, 0);
14857 }
14858
14859 /*
14860 ** current_timestamp()
14861 **
14862 ** This function returns the same value as datetime('now').
14863 */
14864 static void ctimestampFunc(
14865   sqlite3_context *context,
14866   int NotUsed,
14867   sqlite3_value **NotUsed2
14868 ){
14869   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14870   datetimeFunc(context, 0, 0);
14871 }
14872 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
14873
14874 #ifdef SQLITE_OMIT_DATETIME_FUNCS
14875 /*
14876 ** If the library is compiled to omit the full-scale date and time
14877 ** handling (to get a smaller binary), the following minimal version
14878 ** of the functions current_time(), current_date() and current_timestamp()
14879 ** are included instead. This is to support column declarations that
14880 ** include "DEFAULT CURRENT_TIME" etc.
14881 **
14882 ** This function uses the C-library functions time(), gmtime()
14883 ** and strftime(). The format string to pass to strftime() is supplied
14884 ** as the user-data for the function.
14885 */
14886 static void currentTimeFunc(
14887   sqlite3_context *context,
14888   int argc,
14889   sqlite3_value **argv
14890 ){
14891   time_t t;
14892   char *zFormat = (char *)sqlite3_user_data(context);
14893   sqlite3 *db;
14894   sqlite3_int64 iT;
14895   struct tm *pTm;
14896   struct tm sNow;
14897   char zBuf[20];
14898
14899   UNUSED_PARAMETER(argc);
14900   UNUSED_PARAMETER(argv);
14901
14902   db = sqlite3_context_db_handle(context);
14903   if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
14904   t = iT/1000 - 10000*(sqlite3_int64)21086676;
14905 #ifdef HAVE_GMTIME_R
14906   pTm = gmtime_r(&t, &sNow);
14907 #else
14908   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14909   pTm = gmtime(&t);
14910   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
14911   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14912 #endif
14913   if( pTm ){
14914     strftime(zBuf, 20, zFormat, &sNow);
14915     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14916   }
14917 }
14918 #endif
14919
14920 /*
14921 ** This function registered all of the above C functions as SQL
14922 ** functions.  This should be the only routine in this file with
14923 ** external linkage.
14924 */
14925 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
14926   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
14927 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14928     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
14929     FUNCTION(date,             -1, 0, 0, dateFunc      ),
14930     FUNCTION(time,             -1, 0, 0, timeFunc      ),
14931     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
14932     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
14933     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
14934     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
14935     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
14936 #else
14937     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
14938     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
14939     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
14940 #endif
14941   };
14942   int i;
14943   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
14944   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
14945
14946   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
14947     sqlite3FuncDefInsert(pHash, &aFunc[i]);
14948   }
14949 }
14950
14951 /************** End of date.c ************************************************/
14952 /************** Begin file os.c **********************************************/
14953 /*
14954 ** 2005 November 29
14955 **
14956 ** The author disclaims copyright to this source code.  In place of
14957 ** a legal notice, here is a blessing:
14958 **
14959 **    May you do good and not evil.
14960 **    May you find forgiveness for yourself and forgive others.
14961 **    May you share freely, never taking more than you give.
14962 **
14963 ******************************************************************************
14964 **
14965 ** This file contains OS interface code that is common to all
14966 ** architectures.
14967 */
14968 #define _SQLITE_OS_C_ 1
14969 #undef _SQLITE_OS_C_
14970
14971 /*
14972 ** The default SQLite sqlite3_vfs implementations do not allocate
14973 ** memory (actually, os_unix.c allocates a small amount of memory
14974 ** from within OsOpen()), but some third-party implementations may.
14975 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
14976 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
14977 **
14978 ** The following functions are instrumented for malloc() failure 
14979 ** testing:
14980 **
14981 **     sqlite3OsRead()
14982 **     sqlite3OsWrite()
14983 **     sqlite3OsSync()
14984 **     sqlite3OsFileSize()
14985 **     sqlite3OsLock()
14986 **     sqlite3OsCheckReservedLock()
14987 **     sqlite3OsFileControl()
14988 **     sqlite3OsShmMap()
14989 **     sqlite3OsOpen()
14990 **     sqlite3OsDelete()
14991 **     sqlite3OsAccess()
14992 **     sqlite3OsFullPathname()
14993 **
14994 */
14995 #if defined(SQLITE_TEST)
14996 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
14997   #define DO_OS_MALLOC_TEST(x)                                       \
14998   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
14999     void *pTstAlloc = sqlite3Malloc(10);                             \
15000     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
15001     sqlite3_free(pTstAlloc);                                         \
15002   }
15003 #else
15004   #define DO_OS_MALLOC_TEST(x)
15005 #endif
15006
15007 /*
15008 ** The following routines are convenience wrappers around methods
15009 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
15010 ** of this would be completely automatic if SQLite were coded using
15011 ** C++ instead of plain old C.
15012 */
15013 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
15014   int rc = SQLITE_OK;
15015   if( pId->pMethods ){
15016     rc = pId->pMethods->xClose(pId);
15017     pId->pMethods = 0;
15018   }
15019   return rc;
15020 }
15021 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
15022   DO_OS_MALLOC_TEST(id);
15023   return id->pMethods->xRead(id, pBuf, amt, offset);
15024 }
15025 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
15026   DO_OS_MALLOC_TEST(id);
15027   return id->pMethods->xWrite(id, pBuf, amt, offset);
15028 }
15029 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
15030   return id->pMethods->xTruncate(id, size);
15031 }
15032 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
15033   DO_OS_MALLOC_TEST(id);
15034   return id->pMethods->xSync(id, flags);
15035 }
15036 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
15037   DO_OS_MALLOC_TEST(id);
15038   return id->pMethods->xFileSize(id, pSize);
15039 }
15040 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
15041   DO_OS_MALLOC_TEST(id);
15042   return id->pMethods->xLock(id, lockType);
15043 }
15044 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
15045   return id->pMethods->xUnlock(id, lockType);
15046 }
15047 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
15048   DO_OS_MALLOC_TEST(id);
15049   return id->pMethods->xCheckReservedLock(id, pResOut);
15050 }
15051
15052 /*
15053 ** Use sqlite3OsFileControl() when we are doing something that might fail
15054 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
15055 ** when simply tossing information over the wall to the VFS and we do not
15056 ** really care if the VFS receives and understands the information since it
15057 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
15058 ** routine has no return value since the return value would be meaningless.
15059 */
15060 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
15061   DO_OS_MALLOC_TEST(id);
15062   return id->pMethods->xFileControl(id, op, pArg);
15063 }
15064 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
15065   (void)id->pMethods->xFileControl(id, op, pArg);
15066 }
15067
15068 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
15069   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
15070   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
15071 }
15072 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
15073   return id->pMethods->xDeviceCharacteristics(id);
15074 }
15075 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
15076   return id->pMethods->xShmLock(id, offset, n, flags);
15077 }
15078 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
15079   id->pMethods->xShmBarrier(id);
15080 }
15081 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
15082   return id->pMethods->xShmUnmap(id, deleteFlag);
15083 }
15084 SQLITE_PRIVATE int sqlite3OsShmMap(
15085   sqlite3_file *id,               /* Database file handle */
15086   int iPage,
15087   int pgsz,
15088   int bExtend,                    /* True to extend file if necessary */
15089   void volatile **pp              /* OUT: Pointer to mapping */
15090 ){
15091   DO_OS_MALLOC_TEST(id);
15092   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
15093 }
15094
15095 /*
15096 ** The next group of routines are convenience wrappers around the
15097 ** VFS methods.
15098 */
15099 SQLITE_PRIVATE int sqlite3OsOpen(
15100   sqlite3_vfs *pVfs, 
15101   const char *zPath, 
15102   sqlite3_file *pFile, 
15103   int flags, 
15104   int *pFlagsOut
15105 ){
15106   int rc;
15107   DO_OS_MALLOC_TEST(0);
15108   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
15109   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
15110   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
15111   ** reaching the VFS. */
15112   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
15113   assert( rc==SQLITE_OK || pFile->pMethods==0 );
15114   return rc;
15115 }
15116 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
15117   DO_OS_MALLOC_TEST(0);
15118   assert( dirSync==0 || dirSync==1 );
15119   return pVfs->xDelete(pVfs, zPath, dirSync);
15120 }
15121 SQLITE_PRIVATE int sqlite3OsAccess(
15122   sqlite3_vfs *pVfs, 
15123   const char *zPath, 
15124   int flags, 
15125   int *pResOut
15126 ){
15127   DO_OS_MALLOC_TEST(0);
15128   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
15129 }
15130 SQLITE_PRIVATE int sqlite3OsFullPathname(
15131   sqlite3_vfs *pVfs, 
15132   const char *zPath, 
15133   int nPathOut, 
15134   char *zPathOut
15135 ){
15136   DO_OS_MALLOC_TEST(0);
15137   zPathOut[0] = 0;
15138   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
15139 }
15140 #ifndef SQLITE_OMIT_LOAD_EXTENSION
15141 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
15142   return pVfs->xDlOpen(pVfs, zPath);
15143 }
15144 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15145   pVfs->xDlError(pVfs, nByte, zBufOut);
15146 }
15147 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
15148   return pVfs->xDlSym(pVfs, pHdle, zSym);
15149 }
15150 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
15151   pVfs->xDlClose(pVfs, pHandle);
15152 }
15153 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
15154 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15155   return pVfs->xRandomness(pVfs, nByte, zBufOut);
15156 }
15157 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
15158   return pVfs->xSleep(pVfs, nMicro);
15159 }
15160 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
15161   int rc;
15162   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
15163   ** method to get the current date and time if that method is available
15164   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
15165   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
15166   ** unavailable.
15167   */
15168   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
15169     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
15170   }else{
15171     double r;
15172     rc = pVfs->xCurrentTime(pVfs, &r);
15173     *pTimeOut = (sqlite3_int64)(r*86400000.0);
15174   }
15175   return rc;
15176 }
15177
15178 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
15179   sqlite3_vfs *pVfs, 
15180   const char *zFile, 
15181   sqlite3_file **ppFile, 
15182   int flags,
15183   int *pOutFlags
15184 ){
15185   int rc = SQLITE_NOMEM;
15186   sqlite3_file *pFile;
15187   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
15188   if( pFile ){
15189     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
15190     if( rc!=SQLITE_OK ){
15191       sqlite3_free(pFile);
15192     }else{
15193       *ppFile = pFile;
15194     }
15195   }
15196   return rc;
15197 }
15198 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
15199   int rc = SQLITE_OK;
15200   assert( pFile );
15201   rc = sqlite3OsClose(pFile);
15202   sqlite3_free(pFile);
15203   return rc;
15204 }
15205
15206 /*
15207 ** This function is a wrapper around the OS specific implementation of
15208 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
15209 ** ability to simulate a malloc failure, so that the handling of an
15210 ** error in sqlite3_os_init() by the upper layers can be tested.
15211 */
15212 SQLITE_PRIVATE int sqlite3OsInit(void){
15213   void *p = sqlite3_malloc(10);
15214   if( p==0 ) return SQLITE_NOMEM;
15215   sqlite3_free(p);
15216   return sqlite3_os_init();
15217 }
15218
15219 /*
15220 ** The list of all registered VFS implementations.
15221 */
15222 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
15223 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
15224
15225 /*
15226 ** Locate a VFS by name.  If no name is given, simply return the
15227 ** first VFS on the list.
15228 */
15229 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
15230   sqlite3_vfs *pVfs = 0;
15231 #if SQLITE_THREADSAFE
15232   sqlite3_mutex *mutex;
15233 #endif
15234 #ifndef SQLITE_OMIT_AUTOINIT
15235   int rc = sqlite3_initialize();
15236   if( rc ) return 0;
15237 #endif
15238 #if SQLITE_THREADSAFE
15239   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15240 #endif
15241   sqlite3_mutex_enter(mutex);
15242   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
15243     if( zVfs==0 ) break;
15244     if( strcmp(zVfs, pVfs->zName)==0 ) break;
15245   }
15246   sqlite3_mutex_leave(mutex);
15247   return pVfs;
15248 }
15249
15250 /*
15251 ** Unlink a VFS from the linked list
15252 */
15253 static void vfsUnlink(sqlite3_vfs *pVfs){
15254   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
15255   if( pVfs==0 ){
15256     /* No-op */
15257   }else if( vfsList==pVfs ){
15258     vfsList = pVfs->pNext;
15259   }else if( vfsList ){
15260     sqlite3_vfs *p = vfsList;
15261     while( p->pNext && p->pNext!=pVfs ){
15262       p = p->pNext;
15263     }
15264     if( p->pNext==pVfs ){
15265       p->pNext = pVfs->pNext;
15266     }
15267   }
15268 }
15269
15270 /*
15271 ** Register a VFS with the system.  It is harmless to register the same
15272 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
15273 ** true.
15274 */
15275 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
15276   MUTEX_LOGIC(sqlite3_mutex *mutex;)
15277 #ifndef SQLITE_OMIT_AUTOINIT
15278   int rc = sqlite3_initialize();
15279   if( rc ) return rc;
15280 #endif
15281   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
15282   sqlite3_mutex_enter(mutex);
15283   vfsUnlink(pVfs);
15284   if( makeDflt || vfsList==0 ){
15285     pVfs->pNext = vfsList;
15286     vfsList = pVfs;
15287   }else{
15288     pVfs->pNext = vfsList->pNext;
15289     vfsList->pNext = pVfs;
15290   }
15291   assert(vfsList);
15292   sqlite3_mutex_leave(mutex);
15293   return SQLITE_OK;
15294 }
15295
15296 /*
15297 ** Unregister a VFS so that it is no longer accessible.
15298 */
15299 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
15300 #if SQLITE_THREADSAFE
15301   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15302 #endif
15303   sqlite3_mutex_enter(mutex);
15304   vfsUnlink(pVfs);
15305   sqlite3_mutex_leave(mutex);
15306   return SQLITE_OK;
15307 }
15308
15309 /************** End of os.c **************************************************/
15310 /************** Begin file fault.c *******************************************/
15311 /*
15312 ** 2008 Jan 22
15313 **
15314 ** The author disclaims copyright to this source code.  In place of
15315 ** a legal notice, here is a blessing:
15316 **
15317 **    May you do good and not evil.
15318 **    May you find forgiveness for yourself and forgive others.
15319 **    May you share freely, never taking more than you give.
15320 **
15321 *************************************************************************
15322 **
15323 ** This file contains code to support the concept of "benign" 
15324 ** malloc failures (when the xMalloc() or xRealloc() method of the
15325 ** sqlite3_mem_methods structure fails to allocate a block of memory
15326 ** and returns 0). 
15327 **
15328 ** Most malloc failures are non-benign. After they occur, SQLite
15329 ** abandons the current operation and returns an error code (usually
15330 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
15331 ** fatal. For example, if a malloc fails while resizing a hash table, this 
15332 ** is completely recoverable simply by not carrying out the resize. The 
15333 ** hash table will continue to function normally.  So a malloc failure 
15334 ** during a hash table resize is a benign fault.
15335 */
15336
15337
15338 #ifndef SQLITE_OMIT_BUILTIN_TEST
15339
15340 /*
15341 ** Global variables.
15342 */
15343 typedef struct BenignMallocHooks BenignMallocHooks;
15344 static SQLITE_WSD struct BenignMallocHooks {
15345   void (*xBenignBegin)(void);
15346   void (*xBenignEnd)(void);
15347 } sqlite3Hooks = { 0, 0 };
15348
15349 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
15350 ** structure.  If writable static data is unsupported on the target,
15351 ** we have to locate the state vector at run-time.  In the more common
15352 ** case where writable static data is supported, wsdHooks can refer directly
15353 ** to the "sqlite3Hooks" state vector declared above.
15354 */
15355 #ifdef SQLITE_OMIT_WSD
15356 # define wsdHooksInit \
15357   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
15358 # define wsdHooks x[0]
15359 #else
15360 # define wsdHooksInit
15361 # define wsdHooks sqlite3Hooks
15362 #endif
15363
15364
15365 /*
15366 ** Register hooks to call when sqlite3BeginBenignMalloc() and
15367 ** sqlite3EndBenignMalloc() are called, respectively.
15368 */
15369 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
15370   void (*xBenignBegin)(void),
15371   void (*xBenignEnd)(void)
15372 ){
15373   wsdHooksInit;
15374   wsdHooks.xBenignBegin = xBenignBegin;
15375   wsdHooks.xBenignEnd = xBenignEnd;
15376 }
15377
15378 /*
15379 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
15380 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
15381 ** indicates that subsequent malloc failures are non-benign.
15382 */
15383 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
15384   wsdHooksInit;
15385   if( wsdHooks.xBenignBegin ){
15386     wsdHooks.xBenignBegin();
15387   }
15388 }
15389 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
15390   wsdHooksInit;
15391   if( wsdHooks.xBenignEnd ){
15392     wsdHooks.xBenignEnd();
15393   }
15394 }
15395
15396 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
15397
15398 /************** End of fault.c ***********************************************/
15399 /************** Begin file mem0.c ********************************************/
15400 /*
15401 ** 2008 October 28
15402 **
15403 ** The author disclaims copyright to this source code.  In place of
15404 ** a legal notice, here is a blessing:
15405 **
15406 **    May you do good and not evil.
15407 **    May you find forgiveness for yourself and forgive others.
15408 **    May you share freely, never taking more than you give.
15409 **
15410 *************************************************************************
15411 **
15412 ** This file contains a no-op memory allocation drivers for use when
15413 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
15414 ** here always fail.  SQLite will not operate with these drivers.  These
15415 ** are merely placeholders.  Real drivers must be substituted using
15416 ** sqlite3_config() before SQLite will operate.
15417 */
15418
15419 /*
15420 ** This version of the memory allocator is the default.  It is
15421 ** used when no other memory allocator is specified using compile-time
15422 ** macros.
15423 */
15424 #ifdef SQLITE_ZERO_MALLOC
15425
15426 /*
15427 ** No-op versions of all memory allocation routines
15428 */
15429 static void *sqlite3MemMalloc(int nByte){ return 0; }
15430 static void sqlite3MemFree(void *pPrior){ return; }
15431 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
15432 static int sqlite3MemSize(void *pPrior){ return 0; }
15433 static int sqlite3MemRoundup(int n){ return n; }
15434 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
15435 static void sqlite3MemShutdown(void *NotUsed){ return; }
15436
15437 /*
15438 ** This routine is the only routine in this file with external linkage.
15439 **
15440 ** Populate the low-level memory allocation function pointers in
15441 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15442 */
15443 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15444   static const sqlite3_mem_methods defaultMethods = {
15445      sqlite3MemMalloc,
15446      sqlite3MemFree,
15447      sqlite3MemRealloc,
15448      sqlite3MemSize,
15449      sqlite3MemRoundup,
15450      sqlite3MemInit,
15451      sqlite3MemShutdown,
15452      0
15453   };
15454   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15455 }
15456
15457 #endif /* SQLITE_ZERO_MALLOC */
15458
15459 /************** End of mem0.c ************************************************/
15460 /************** Begin file mem1.c ********************************************/
15461 /*
15462 ** 2007 August 14
15463 **
15464 ** The author disclaims copyright to this source code.  In place of
15465 ** a legal notice, here is a blessing:
15466 **
15467 **    May you do good and not evil.
15468 **    May you find forgiveness for yourself and forgive others.
15469 **    May you share freely, never taking more than you give.
15470 **
15471 *************************************************************************
15472 **
15473 ** This file contains low-level memory allocation drivers for when
15474 ** SQLite will use the standard C-library malloc/realloc/free interface
15475 ** to obtain the memory it needs.
15476 **
15477 ** This file contains implementations of the low-level memory allocation
15478 ** routines specified in the sqlite3_mem_methods object.  The content of
15479 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
15480 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
15481 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
15482 ** default configuration is to use memory allocation routines in this
15483 ** file.
15484 **
15485 ** C-preprocessor macro summary:
15486 **
15487 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
15488 **                                the malloc_usable_size() interface exists
15489 **                                on the target platform.  Or, this symbol
15490 **                                can be set manually, if desired.
15491 **                                If an equivalent interface exists by
15492 **                                a different name, using a separate -D
15493 **                                option to rename it.
15494 **
15495 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
15496 **                                memory allocator.  Set this symbol to enable
15497 **                                building on older macs.
15498 **
15499 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
15500 **                                _msize() on windows systems.  This might
15501 **                                be necessary when compiling for Delphi,
15502 **                                for example.
15503 */
15504
15505 /*
15506 ** This version of the memory allocator is the default.  It is
15507 ** used when no other memory allocator is specified using compile-time
15508 ** macros.
15509 */
15510 #ifdef SQLITE_SYSTEM_MALLOC
15511
15512 /*
15513 ** The MSVCRT has malloc_usable_size() but it is called _msize().
15514 ** The use of _msize() is automatic, but can be disabled by compiling
15515 ** with -DSQLITE_WITHOUT_MSIZE
15516 */
15517 #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
15518 # define SQLITE_MALLOCSIZE _msize
15519 #endif
15520
15521 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15522
15523 /*
15524 ** Use the zone allocator available on apple products unless the
15525 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
15526 */
15527 #include <sys/sysctl.h>
15528 #include <malloc/malloc.h>
15529 #include <libkern/OSAtomic.h>
15530 static malloc_zone_t* _sqliteZone_;
15531 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
15532 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
15533 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
15534 #define SQLITE_MALLOCSIZE(x) \
15535         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
15536
15537 #else /* if not __APPLE__ */
15538
15539 /*
15540 ** Use standard C library malloc and free on non-Apple systems.  
15541 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
15542 */
15543 #define SQLITE_MALLOC(x)    malloc(x)
15544 #define SQLITE_FREE(x)      free(x)
15545 #define SQLITE_REALLOC(x,y) realloc((x),(y))
15546
15547 #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
15548       || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
15549 # include <malloc.h>    /* Needed for malloc_usable_size on linux */
15550 #endif
15551 #ifdef HAVE_MALLOC_USABLE_SIZE
15552 # ifndef SQLITE_MALLOCSIZE
15553 #  define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
15554 # endif
15555 #else
15556 # undef SQLITE_MALLOCSIZE
15557 #endif
15558
15559 #endif /* __APPLE__ or not __APPLE__ */
15560
15561 /*
15562 ** Like malloc(), but remember the size of the allocation
15563 ** so that we can find it later using sqlite3MemSize().
15564 **
15565 ** For this low-level routine, we are guaranteed that nByte>0 because
15566 ** cases of nByte<=0 will be intercepted and dealt with by higher level
15567 ** routines.
15568 */
15569 static void *sqlite3MemMalloc(int nByte){
15570 #ifdef SQLITE_MALLOCSIZE
15571   void *p = SQLITE_MALLOC( nByte );
15572   if( p==0 ){
15573     testcase( sqlite3GlobalConfig.xLog!=0 );
15574     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15575   }
15576   return p;
15577 #else
15578   sqlite3_int64 *p;
15579   assert( nByte>0 );
15580   nByte = ROUND8(nByte);
15581   p = SQLITE_MALLOC( nByte+8 );
15582   if( p ){
15583     p[0] = nByte;
15584     p++;
15585   }else{
15586     testcase( sqlite3GlobalConfig.xLog!=0 );
15587     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15588   }
15589   return (void *)p;
15590 #endif
15591 }
15592
15593 /*
15594 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
15595 ** or sqlite3MemRealloc().
15596 **
15597 ** For this low-level routine, we already know that pPrior!=0 since
15598 ** cases where pPrior==0 will have been intecepted and dealt with
15599 ** by higher-level routines.
15600 */
15601 static void sqlite3MemFree(void *pPrior){
15602 #ifdef SQLITE_MALLOCSIZE
15603   SQLITE_FREE(pPrior);
15604 #else
15605   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15606   assert( pPrior!=0 );
15607   p--;
15608   SQLITE_FREE(p);
15609 #endif
15610 }
15611
15612 /*
15613 ** Report the allocated size of a prior return from xMalloc()
15614 ** or xRealloc().
15615 */
15616 static int sqlite3MemSize(void *pPrior){
15617 #ifdef SQLITE_MALLOCSIZE
15618   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
15619 #else
15620   sqlite3_int64 *p;
15621   if( pPrior==0 ) return 0;
15622   p = (sqlite3_int64*)pPrior;
15623   p--;
15624   return (int)p[0];
15625 #endif
15626 }
15627
15628 /*
15629 ** Like realloc().  Resize an allocation previously obtained from
15630 ** sqlite3MemMalloc().
15631 **
15632 ** For this low-level interface, we know that pPrior!=0.  Cases where
15633 ** pPrior==0 while have been intercepted by higher-level routine and
15634 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
15635 ** cases where nByte<=0 will have been intercepted by higher-level
15636 ** routines and redirected to xFree.
15637 */
15638 static void *sqlite3MemRealloc(void *pPrior, int nByte){
15639 #ifdef SQLITE_MALLOCSIZE
15640   void *p = SQLITE_REALLOC(pPrior, nByte);
15641   if( p==0 ){
15642     testcase( sqlite3GlobalConfig.xLog!=0 );
15643     sqlite3_log(SQLITE_NOMEM,
15644       "failed memory resize %u to %u bytes",
15645       SQLITE_MALLOCSIZE(pPrior), nByte);
15646   }
15647   return p;
15648 #else
15649   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15650   assert( pPrior!=0 && nByte>0 );
15651   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
15652   p--;
15653   p = SQLITE_REALLOC(p, nByte+8 );
15654   if( p ){
15655     p[0] = nByte;
15656     p++;
15657   }else{
15658     testcase( sqlite3GlobalConfig.xLog!=0 );
15659     sqlite3_log(SQLITE_NOMEM,
15660       "failed memory resize %u to %u bytes",
15661       sqlite3MemSize(pPrior), nByte);
15662   }
15663   return (void*)p;
15664 #endif
15665 }
15666
15667 /*
15668 ** Round up a request size to the next valid allocation size.
15669 */
15670 static int sqlite3MemRoundup(int n){
15671   return ROUND8(n);
15672 }
15673
15674 /*
15675 ** Initialize this module.
15676 */
15677 static int sqlite3MemInit(void *NotUsed){
15678 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15679   int cpuCount;
15680   size_t len;
15681   if( _sqliteZone_ ){
15682     return SQLITE_OK;
15683   }
15684   len = sizeof(cpuCount);
15685   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
15686   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
15687   if( cpuCount>1 ){
15688     /* defer MT decisions to system malloc */
15689     _sqliteZone_ = malloc_default_zone();
15690   }else{
15691     /* only 1 core, use our own zone to contention over global locks, 
15692     ** e.g. we have our own dedicated locks */
15693     bool success;
15694     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
15695     malloc_set_zone_name(newzone, "Sqlite_Heap");
15696     do{
15697       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, 
15698                                  (void * volatile *)&_sqliteZone_);
15699     }while(!_sqliteZone_);
15700     if( !success ){
15701       /* somebody registered a zone first */
15702       malloc_destroy_zone(newzone);
15703     }
15704   }
15705 #endif
15706   UNUSED_PARAMETER(NotUsed);
15707   return SQLITE_OK;
15708 }
15709
15710 /*
15711 ** Deinitialize this module.
15712 */
15713 static void sqlite3MemShutdown(void *NotUsed){
15714   UNUSED_PARAMETER(NotUsed);
15715   return;
15716 }
15717
15718 /*
15719 ** This routine is the only routine in this file with external linkage.
15720 **
15721 ** Populate the low-level memory allocation function pointers in
15722 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15723 */
15724 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15725   static const sqlite3_mem_methods defaultMethods = {
15726      sqlite3MemMalloc,
15727      sqlite3MemFree,
15728      sqlite3MemRealloc,
15729      sqlite3MemSize,
15730      sqlite3MemRoundup,
15731      sqlite3MemInit,
15732      sqlite3MemShutdown,
15733      0
15734   };
15735   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15736 }
15737
15738 #endif /* SQLITE_SYSTEM_MALLOC */
15739
15740 /************** End of mem1.c ************************************************/
15741 /************** Begin file mem2.c ********************************************/
15742 /*
15743 ** 2007 August 15
15744 **
15745 ** The author disclaims copyright to this source code.  In place of
15746 ** a legal notice, here is a blessing:
15747 **
15748 **    May you do good and not evil.
15749 **    May you find forgiveness for yourself and forgive others.
15750 **    May you share freely, never taking more than you give.
15751 **
15752 *************************************************************************
15753 **
15754 ** This file contains low-level memory allocation drivers for when
15755 ** SQLite will use the standard C-library malloc/realloc/free interface
15756 ** to obtain the memory it needs while adding lots of additional debugging
15757 ** information to each allocation in order to help detect and fix memory
15758 ** leaks and memory usage errors.
15759 **
15760 ** This file contains implementations of the low-level memory allocation
15761 ** routines specified in the sqlite3_mem_methods object.
15762 */
15763
15764 /*
15765 ** This version of the memory allocator is used only if the
15766 ** SQLITE_MEMDEBUG macro is defined
15767 */
15768 #ifdef SQLITE_MEMDEBUG
15769
15770 /*
15771 ** The backtrace functionality is only available with GLIBC
15772 */
15773 #ifdef __GLIBC__
15774   extern int backtrace(void**,int);
15775   extern void backtrace_symbols_fd(void*const*,int,int);
15776 #else
15777 # define backtrace(A,B) 1
15778 # define backtrace_symbols_fd(A,B,C)
15779 #endif
15780 /* #include <stdio.h> */
15781
15782 /*
15783 ** Each memory allocation looks like this:
15784 **
15785 **  ------------------------------------------------------------------------
15786 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
15787 **  ------------------------------------------------------------------------
15788 **
15789 ** The application code sees only a pointer to the allocation.  We have
15790 ** to back up from the allocation pointer to find the MemBlockHdr.  The
15791 ** MemBlockHdr tells us the size of the allocation and the number of
15792 ** backtrace pointers.  There is also a guard word at the end of the
15793 ** MemBlockHdr.
15794 */
15795 struct MemBlockHdr {
15796   i64 iSize;                          /* Size of this allocation */
15797   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
15798   char nBacktrace;                    /* Number of backtraces on this alloc */
15799   char nBacktraceSlots;               /* Available backtrace slots */
15800   u8 nTitle;                          /* Bytes of title; includes '\0' */
15801   u8 eType;                           /* Allocation type code */
15802   int iForeGuard;                     /* Guard word for sanity */
15803 };
15804
15805 /*
15806 ** Guard words
15807 */
15808 #define FOREGUARD 0x80F5E153
15809 #define REARGUARD 0xE4676B53
15810
15811 /*
15812 ** Number of malloc size increments to track.
15813 */
15814 #define NCSIZE  1000
15815
15816 /*
15817 ** All of the static variables used by this module are collected
15818 ** into a single structure named "mem".  This is to keep the
15819 ** static variables organized and to reduce namespace pollution
15820 ** when this module is combined with other in the amalgamation.
15821 */
15822 static struct {
15823   
15824   /*
15825   ** Mutex to control access to the memory allocation subsystem.
15826   */
15827   sqlite3_mutex *mutex;
15828
15829   /*
15830   ** Head and tail of a linked list of all outstanding allocations
15831   */
15832   struct MemBlockHdr *pFirst;
15833   struct MemBlockHdr *pLast;
15834   
15835   /*
15836   ** The number of levels of backtrace to save in new allocations.
15837   */
15838   int nBacktrace;
15839   void (*xBacktrace)(int, int, void **);
15840
15841   /*
15842   ** Title text to insert in front of each block
15843   */
15844   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
15845   char zTitle[100];  /* The title text */
15846
15847   /* 
15848   ** sqlite3MallocDisallow() increments the following counter.
15849   ** sqlite3MallocAllow() decrements it.
15850   */
15851   int disallow; /* Do not allow memory allocation */
15852
15853   /*
15854   ** Gather statistics on the sizes of memory allocations.
15855   ** nAlloc[i] is the number of allocation attempts of i*8
15856   ** bytes.  i==NCSIZE is the number of allocation attempts for
15857   ** sizes more than NCSIZE*8 bytes.
15858   */
15859   int nAlloc[NCSIZE];      /* Total number of allocations */
15860   int nCurrent[NCSIZE];    /* Current number of allocations */
15861   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
15862
15863 } mem;
15864
15865
15866 /*
15867 ** Adjust memory usage statistics
15868 */
15869 static void adjustStats(int iSize, int increment){
15870   int i = ROUND8(iSize)/8;
15871   if( i>NCSIZE-1 ){
15872     i = NCSIZE - 1;
15873   }
15874   if( increment>0 ){
15875     mem.nAlloc[i]++;
15876     mem.nCurrent[i]++;
15877     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
15878       mem.mxCurrent[i] = mem.nCurrent[i];
15879     }
15880   }else{
15881     mem.nCurrent[i]--;
15882     assert( mem.nCurrent[i]>=0 );
15883   }
15884 }
15885
15886 /*
15887 ** Given an allocation, find the MemBlockHdr for that allocation.
15888 **
15889 ** This routine checks the guards at either end of the allocation and
15890 ** if they are incorrect it asserts.
15891 */
15892 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
15893   struct MemBlockHdr *p;
15894   int *pInt;
15895   u8 *pU8;
15896   int nReserve;
15897
15898   p = (struct MemBlockHdr*)pAllocation;
15899   p--;
15900   assert( p->iForeGuard==(int)FOREGUARD );
15901   nReserve = ROUND8(p->iSize);
15902   pInt = (int*)pAllocation;
15903   pU8 = (u8*)pAllocation;
15904   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
15905   /* This checks any of the "extra" bytes allocated due
15906   ** to rounding up to an 8 byte boundary to ensure 
15907   ** they haven't been overwritten.
15908   */
15909   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
15910   return p;
15911 }
15912
15913 /*
15914 ** Return the number of bytes currently allocated at address p.
15915 */
15916 static int sqlite3MemSize(void *p){
15917   struct MemBlockHdr *pHdr;
15918   if( !p ){
15919     return 0;
15920   }
15921   pHdr = sqlite3MemsysGetHeader(p);
15922   return pHdr->iSize;
15923 }
15924
15925 /*
15926 ** Initialize the memory allocation subsystem.
15927 */
15928 static int sqlite3MemInit(void *NotUsed){
15929   UNUSED_PARAMETER(NotUsed);
15930   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
15931   if( !sqlite3GlobalConfig.bMemstat ){
15932     /* If memory status is enabled, then the malloc.c wrapper will already
15933     ** hold the STATIC_MEM mutex when the routines here are invoked. */
15934     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15935   }
15936   return SQLITE_OK;
15937 }
15938
15939 /*
15940 ** Deinitialize the memory allocation subsystem.
15941 */
15942 static void sqlite3MemShutdown(void *NotUsed){
15943   UNUSED_PARAMETER(NotUsed);
15944   mem.mutex = 0;
15945 }
15946
15947 /*
15948 ** Round up a request size to the next valid allocation size.
15949 */
15950 static int sqlite3MemRoundup(int n){
15951   return ROUND8(n);
15952 }
15953
15954 /*
15955 ** Fill a buffer with pseudo-random bytes.  This is used to preset
15956 ** the content of a new memory allocation to unpredictable values and
15957 ** to clear the content of a freed allocation to unpredictable values.
15958 */
15959 static void randomFill(char *pBuf, int nByte){
15960   unsigned int x, y, r;
15961   x = SQLITE_PTR_TO_INT(pBuf);
15962   y = nByte | 1;
15963   while( nByte >= 4 ){
15964     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15965     y = y*1103515245 + 12345;
15966     r = x ^ y;
15967     *(int*)pBuf = r;
15968     pBuf += 4;
15969     nByte -= 4;
15970   }
15971   while( nByte-- > 0 ){
15972     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15973     y = y*1103515245 + 12345;
15974     r = x ^ y;
15975     *(pBuf++) = r & 0xff;
15976   }
15977 }
15978
15979 /*
15980 ** Allocate nByte bytes of memory.
15981 */
15982 static void *sqlite3MemMalloc(int nByte){
15983   struct MemBlockHdr *pHdr;
15984   void **pBt;
15985   char *z;
15986   int *pInt;
15987   void *p = 0;
15988   int totalSize;
15989   int nReserve;
15990   sqlite3_mutex_enter(mem.mutex);
15991   assert( mem.disallow==0 );
15992   nReserve = ROUND8(nByte);
15993   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
15994                mem.nBacktrace*sizeof(void*) + mem.nTitle;
15995   p = malloc(totalSize);
15996   if( p ){
15997     z = p;
15998     pBt = (void**)&z[mem.nTitle];
15999     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
16000     pHdr->pNext = 0;
16001     pHdr->pPrev = mem.pLast;
16002     if( mem.pLast ){
16003       mem.pLast->pNext = pHdr;
16004     }else{
16005       mem.pFirst = pHdr;
16006     }
16007     mem.pLast = pHdr;
16008     pHdr->iForeGuard = FOREGUARD;
16009     pHdr->eType = MEMTYPE_HEAP;
16010     pHdr->nBacktraceSlots = mem.nBacktrace;
16011     pHdr->nTitle = mem.nTitle;
16012     if( mem.nBacktrace ){
16013       void *aAddr[40];
16014       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
16015       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
16016       assert(pBt[0]);
16017       if( mem.xBacktrace ){
16018         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
16019       }
16020     }else{
16021       pHdr->nBacktrace = 0;
16022     }
16023     if( mem.nTitle ){
16024       memcpy(z, mem.zTitle, mem.nTitle);
16025     }
16026     pHdr->iSize = nByte;
16027     adjustStats(nByte, +1);
16028     pInt = (int*)&pHdr[1];
16029     pInt[nReserve/sizeof(int)] = REARGUARD;
16030     randomFill((char*)pInt, nByte);
16031     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
16032     p = (void*)pInt;
16033   }
16034   sqlite3_mutex_leave(mem.mutex);
16035   return p; 
16036 }
16037
16038 /*
16039 ** Free memory.
16040 */
16041 static void sqlite3MemFree(void *pPrior){
16042   struct MemBlockHdr *pHdr;
16043   void **pBt;
16044   char *z;
16045   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
16046        || mem.mutex!=0 );
16047   pHdr = sqlite3MemsysGetHeader(pPrior);
16048   pBt = (void**)pHdr;
16049   pBt -= pHdr->nBacktraceSlots;
16050   sqlite3_mutex_enter(mem.mutex);
16051   if( pHdr->pPrev ){
16052     assert( pHdr->pPrev->pNext==pHdr );
16053     pHdr->pPrev->pNext = pHdr->pNext;
16054   }else{
16055     assert( mem.pFirst==pHdr );
16056     mem.pFirst = pHdr->pNext;
16057   }
16058   if( pHdr->pNext ){
16059     assert( pHdr->pNext->pPrev==pHdr );
16060     pHdr->pNext->pPrev = pHdr->pPrev;
16061   }else{
16062     assert( mem.pLast==pHdr );
16063     mem.pLast = pHdr->pPrev;
16064   }
16065   z = (char*)pBt;
16066   z -= pHdr->nTitle;
16067   adjustStats(pHdr->iSize, -1);
16068   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
16069                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
16070   free(z);
16071   sqlite3_mutex_leave(mem.mutex);  
16072 }
16073
16074 /*
16075 ** Change the size of an existing memory allocation.
16076 **
16077 ** For this debugging implementation, we *always* make a copy of the
16078 ** allocation into a new place in memory.  In this way, if the 
16079 ** higher level code is using pointer to the old allocation, it is 
16080 ** much more likely to break and we are much more liking to find
16081 ** the error.
16082 */
16083 static void *sqlite3MemRealloc(void *pPrior, int nByte){
16084   struct MemBlockHdr *pOldHdr;
16085   void *pNew;
16086   assert( mem.disallow==0 );
16087   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
16088   pOldHdr = sqlite3MemsysGetHeader(pPrior);
16089   pNew = sqlite3MemMalloc(nByte);
16090   if( pNew ){
16091     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
16092     if( nByte>pOldHdr->iSize ){
16093       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
16094     }
16095     sqlite3MemFree(pPrior);
16096   }
16097   return pNew;
16098 }
16099
16100 /*
16101 ** Populate the low-level memory allocation function pointers in
16102 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16103 */
16104 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16105   static const sqlite3_mem_methods defaultMethods = {
16106      sqlite3MemMalloc,
16107      sqlite3MemFree,
16108      sqlite3MemRealloc,
16109      sqlite3MemSize,
16110      sqlite3MemRoundup,
16111      sqlite3MemInit,
16112      sqlite3MemShutdown,
16113      0
16114   };
16115   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16116 }
16117
16118 /*
16119 ** Set the "type" of an allocation.
16120 */
16121 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
16122   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16123     struct MemBlockHdr *pHdr;
16124     pHdr = sqlite3MemsysGetHeader(p);
16125     assert( pHdr->iForeGuard==FOREGUARD );
16126     pHdr->eType = eType;
16127   }
16128 }
16129
16130 /*
16131 ** Return TRUE if the mask of type in eType matches the type of the
16132 ** allocation p.  Also return true if p==NULL.
16133 **
16134 ** This routine is designed for use within an assert() statement, to
16135 ** verify the type of an allocation.  For example:
16136 **
16137 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
16138 */
16139 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
16140   int rc = 1;
16141   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16142     struct MemBlockHdr *pHdr;
16143     pHdr = sqlite3MemsysGetHeader(p);
16144     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16145     if( (pHdr->eType&eType)==0 ){
16146       rc = 0;
16147     }
16148   }
16149   return rc;
16150 }
16151
16152 /*
16153 ** Return TRUE if the mask of type in eType matches no bits of the type of the
16154 ** allocation p.  Also return true if p==NULL.
16155 **
16156 ** This routine is designed for use within an assert() statement, to
16157 ** verify the type of an allocation.  For example:
16158 **
16159 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
16160 */
16161 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
16162   int rc = 1;
16163   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16164     struct MemBlockHdr *pHdr;
16165     pHdr = sqlite3MemsysGetHeader(p);
16166     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16167     if( (pHdr->eType&eType)!=0 ){
16168       rc = 0;
16169     }
16170   }
16171   return rc;
16172 }
16173
16174 /*
16175 ** Set the number of backtrace levels kept for each allocation.
16176 ** A value of zero turns off backtracing.  The number is always rounded
16177 ** up to a multiple of 2.
16178 */
16179 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
16180   if( depth<0 ){ depth = 0; }
16181   if( depth>20 ){ depth = 20; }
16182   depth = (depth+1)&0xfe;
16183   mem.nBacktrace = depth;
16184 }
16185
16186 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
16187   mem.xBacktrace = xBacktrace;
16188 }
16189
16190 /*
16191 ** Set the title string for subsequent allocations.
16192 */
16193 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
16194   unsigned int n = sqlite3Strlen30(zTitle) + 1;
16195   sqlite3_mutex_enter(mem.mutex);
16196   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
16197   memcpy(mem.zTitle, zTitle, n);
16198   mem.zTitle[n] = 0;
16199   mem.nTitle = ROUND8(n);
16200   sqlite3_mutex_leave(mem.mutex);
16201 }
16202
16203 SQLITE_PRIVATE void sqlite3MemdebugSync(){
16204   struct MemBlockHdr *pHdr;
16205   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16206     void **pBt = (void**)pHdr;
16207     pBt -= pHdr->nBacktraceSlots;
16208     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
16209   }
16210 }
16211
16212 /*
16213 ** Open the file indicated and write a log of all unfreed memory 
16214 ** allocations into that log.
16215 */
16216 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
16217   FILE *out;
16218   struct MemBlockHdr *pHdr;
16219   void **pBt;
16220   int i;
16221   out = fopen(zFilename, "w");
16222   if( out==0 ){
16223     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16224                     zFilename);
16225     return;
16226   }
16227   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16228     char *z = (char*)pHdr;
16229     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
16230     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
16231             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
16232     if( pHdr->nBacktrace ){
16233       fflush(out);
16234       pBt = (void**)pHdr;
16235       pBt -= pHdr->nBacktraceSlots;
16236       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
16237       fprintf(out, "\n");
16238     }
16239   }
16240   fprintf(out, "COUNTS:\n");
16241   for(i=0; i<NCSIZE-1; i++){
16242     if( mem.nAlloc[i] ){
16243       fprintf(out, "   %5d: %10d %10d %10d\n", 
16244             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
16245     }
16246   }
16247   if( mem.nAlloc[NCSIZE-1] ){
16248     fprintf(out, "   %5d: %10d %10d %10d\n",
16249              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
16250              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
16251   }
16252   fclose(out);
16253 }
16254
16255 /*
16256 ** Return the number of times sqlite3MemMalloc() has been called.
16257 */
16258 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
16259   int i;
16260   int nTotal = 0;
16261   for(i=0; i<NCSIZE; i++){
16262     nTotal += mem.nAlloc[i];
16263   }
16264   return nTotal;
16265 }
16266
16267
16268 #endif /* SQLITE_MEMDEBUG */
16269
16270 /************** End of mem2.c ************************************************/
16271 /************** Begin file mem3.c ********************************************/
16272 /*
16273 ** 2007 October 14
16274 **
16275 ** The author disclaims copyright to this source code.  In place of
16276 ** a legal notice, here is a blessing:
16277 **
16278 **    May you do good and not evil.
16279 **    May you find forgiveness for yourself and forgive others.
16280 **    May you share freely, never taking more than you give.
16281 **
16282 *************************************************************************
16283 ** This file contains the C functions that implement a memory
16284 ** allocation subsystem for use by SQLite. 
16285 **
16286 ** This version of the memory allocation subsystem omits all
16287 ** use of malloc(). The SQLite user supplies a block of memory
16288 ** before calling sqlite3_initialize() from which allocations
16289 ** are made and returned by the xMalloc() and xRealloc() 
16290 ** implementations. Once sqlite3_initialize() has been called,
16291 ** the amount of memory available to SQLite is fixed and cannot
16292 ** be changed.
16293 **
16294 ** This version of the memory allocation subsystem is included
16295 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
16296 */
16297
16298 /*
16299 ** This version of the memory allocator is only built into the library
16300 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
16301 ** mean that the library will use a memory-pool by default, just that
16302 ** it is available. The mempool allocator is activated by calling
16303 ** sqlite3_config().
16304 */
16305 #ifdef SQLITE_ENABLE_MEMSYS3
16306
16307 /*
16308 ** Maximum size (in Mem3Blocks) of a "small" chunk.
16309 */
16310 #define MX_SMALL 10
16311
16312
16313 /*
16314 ** Number of freelist hash slots
16315 */
16316 #define N_HASH  61
16317
16318 /*
16319 ** A memory allocation (also called a "chunk") consists of two or 
16320 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
16321 ** a header that is not returned to the user.
16322 **
16323 ** A chunk is two or more blocks that is either checked out or
16324 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
16325 ** size of the allocation in blocks if the allocation is free.
16326 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
16327 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
16328 ** is true if the previous chunk is checked out and false if the
16329 ** previous chunk is free.  The u.hdr.prevSize field is the size of
16330 ** the previous chunk in blocks if the previous chunk is on the
16331 ** freelist. If the previous chunk is checked out, then
16332 ** u.hdr.prevSize can be part of the data for that chunk and should
16333 ** not be read or written.
16334 **
16335 ** We often identify a chunk by its index in mem3.aPool[].  When
16336 ** this is done, the chunk index refers to the second block of
16337 ** the chunk.  In this way, the first chunk has an index of 1.
16338 ** A chunk index of 0 means "no such chunk" and is the equivalent
16339 ** of a NULL pointer.
16340 **
16341 ** The second block of free chunks is of the form u.list.  The
16342 ** two fields form a double-linked list of chunks of related sizes.
16343 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
16344 ** for smaller chunks and mem3.aiHash[] for larger chunks.
16345 **
16346 ** The second block of a chunk is user data if the chunk is checked 
16347 ** out.  If a chunk is checked out, the user data may extend into
16348 ** the u.hdr.prevSize value of the following chunk.
16349 */
16350 typedef struct Mem3Block Mem3Block;
16351 struct Mem3Block {
16352   union {
16353     struct {
16354       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
16355       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
16356     } hdr;
16357     struct {
16358       u32 next;       /* Index in mem3.aPool[] of next free chunk */
16359       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
16360     } list;
16361   } u;
16362 };
16363
16364 /*
16365 ** All of the static variables used by this module are collected
16366 ** into a single structure named "mem3".  This is to keep the
16367 ** static variables organized and to reduce namespace pollution
16368 ** when this module is combined with other in the amalgamation.
16369 */
16370 static SQLITE_WSD struct Mem3Global {
16371   /*
16372   ** Memory available for allocation. nPool is the size of the array
16373   ** (in Mem3Blocks) pointed to by aPool less 2.
16374   */
16375   u32 nPool;
16376   Mem3Block *aPool;
16377
16378   /*
16379   ** True if we are evaluating an out-of-memory callback.
16380   */
16381   int alarmBusy;
16382   
16383   /*
16384   ** Mutex to control access to the memory allocation subsystem.
16385   */
16386   sqlite3_mutex *mutex;
16387   
16388   /*
16389   ** The minimum amount of free space that we have seen.
16390   */
16391   u32 mnMaster;
16392
16393   /*
16394   ** iMaster is the index of the master chunk.  Most new allocations
16395   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
16396   ** of the current master.  iMaster is 0 if there is not master chunk.
16397   ** The master chunk is not in either the aiHash[] or aiSmall[].
16398   */
16399   u32 iMaster;
16400   u32 szMaster;
16401
16402   /*
16403   ** Array of lists of free blocks according to the block size 
16404   ** for smaller chunks, or a hash on the block size for larger
16405   ** chunks.
16406   */
16407   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
16408   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
16409 } mem3 = { 97535575 };
16410
16411 #define mem3 GLOBAL(struct Mem3Global, mem3)
16412
16413 /*
16414 ** Unlink the chunk at mem3.aPool[i] from list it is currently
16415 ** on.  *pRoot is the list that i is a member of.
16416 */
16417 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
16418   u32 next = mem3.aPool[i].u.list.next;
16419   u32 prev = mem3.aPool[i].u.list.prev;
16420   assert( sqlite3_mutex_held(mem3.mutex) );
16421   if( prev==0 ){
16422     *pRoot = next;
16423   }else{
16424     mem3.aPool[prev].u.list.next = next;
16425   }
16426   if( next ){
16427     mem3.aPool[next].u.list.prev = prev;
16428   }
16429   mem3.aPool[i].u.list.next = 0;
16430   mem3.aPool[i].u.list.prev = 0;
16431 }
16432
16433 /*
16434 ** Unlink the chunk at index i from 
16435 ** whatever list is currently a member of.
16436 */
16437 static void memsys3Unlink(u32 i){
16438   u32 size, hash;
16439   assert( sqlite3_mutex_held(mem3.mutex) );
16440   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16441   assert( i>=1 );
16442   size = mem3.aPool[i-1].u.hdr.size4x/4;
16443   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16444   assert( size>=2 );
16445   if( size <= MX_SMALL ){
16446     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
16447   }else{
16448     hash = size % N_HASH;
16449     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16450   }
16451 }
16452
16453 /*
16454 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
16455 ** at *pRoot.
16456 */
16457 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
16458   assert( sqlite3_mutex_held(mem3.mutex) );
16459   mem3.aPool[i].u.list.next = *pRoot;
16460   mem3.aPool[i].u.list.prev = 0;
16461   if( *pRoot ){
16462     mem3.aPool[*pRoot].u.list.prev = i;
16463   }
16464   *pRoot = i;
16465 }
16466
16467 /*
16468 ** Link the chunk at index i into either the appropriate
16469 ** small chunk list, or into the large chunk hash table.
16470 */
16471 static void memsys3Link(u32 i){
16472   u32 size, hash;
16473   assert( sqlite3_mutex_held(mem3.mutex) );
16474   assert( i>=1 );
16475   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16476   size = mem3.aPool[i-1].u.hdr.size4x/4;
16477   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16478   assert( size>=2 );
16479   if( size <= MX_SMALL ){
16480     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
16481   }else{
16482     hash = size % N_HASH;
16483     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
16484   }
16485 }
16486
16487 /*
16488 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16489 ** will already be held (obtained by code in malloc.c) if
16490 ** sqlite3GlobalConfig.bMemStat is true.
16491 */
16492 static void memsys3Enter(void){
16493   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
16494     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16495   }
16496   sqlite3_mutex_enter(mem3.mutex);
16497 }
16498 static void memsys3Leave(void){
16499   sqlite3_mutex_leave(mem3.mutex);
16500 }
16501
16502 /*
16503 ** Called when we are unable to satisfy an allocation of nBytes.
16504 */
16505 static void memsys3OutOfMemory(int nByte){
16506   if( !mem3.alarmBusy ){
16507     mem3.alarmBusy = 1;
16508     assert( sqlite3_mutex_held(mem3.mutex) );
16509     sqlite3_mutex_leave(mem3.mutex);
16510     sqlite3_release_memory(nByte);
16511     sqlite3_mutex_enter(mem3.mutex);
16512     mem3.alarmBusy = 0;
16513   }
16514 }
16515
16516
16517 /*
16518 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
16519 ** size parameters for check-out and return a pointer to the 
16520 ** user portion of the chunk.
16521 */
16522 static void *memsys3Checkout(u32 i, u32 nBlock){
16523   u32 x;
16524   assert( sqlite3_mutex_held(mem3.mutex) );
16525   assert( i>=1 );
16526   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
16527   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
16528   x = mem3.aPool[i-1].u.hdr.size4x;
16529   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
16530   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
16531   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
16532   return &mem3.aPool[i];
16533 }
16534
16535 /*
16536 ** Carve a piece off of the end of the mem3.iMaster free chunk.
16537 ** Return a pointer to the new allocation.  Or, if the master chunk
16538 ** is not large enough, return 0.
16539 */
16540 static void *memsys3FromMaster(u32 nBlock){
16541   assert( sqlite3_mutex_held(mem3.mutex) );
16542   assert( mem3.szMaster>=nBlock );
16543   if( nBlock>=mem3.szMaster-1 ){
16544     /* Use the entire master */
16545     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
16546     mem3.iMaster = 0;
16547     mem3.szMaster = 0;
16548     mem3.mnMaster = 0;
16549     return p;
16550   }else{
16551     /* Split the master block.  Return the tail. */
16552     u32 newi, x;
16553     newi = mem3.iMaster + mem3.szMaster - nBlock;
16554     assert( newi > mem3.iMaster+1 );
16555     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
16556     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
16557     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
16558     mem3.szMaster -= nBlock;
16559     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
16560     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16561     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16562     if( mem3.szMaster < mem3.mnMaster ){
16563       mem3.mnMaster = mem3.szMaster;
16564     }
16565     return (void*)&mem3.aPool[newi];
16566   }
16567 }
16568
16569 /*
16570 ** *pRoot is the head of a list of free chunks of the same size
16571 ** or same size hash.  In other words, *pRoot is an entry in either
16572 ** mem3.aiSmall[] or mem3.aiHash[].  
16573 **
16574 ** This routine examines all entries on the given list and tries
16575 ** to coalesce each entries with adjacent free chunks.  
16576 **
16577 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
16578 ** the current mem3.iMaster with the new larger chunk.  In order for
16579 ** this mem3.iMaster replacement to work, the master chunk must be
16580 ** linked into the hash tables.  That is not the normal state of
16581 ** affairs, of course.  The calling routine must link the master
16582 ** chunk before invoking this routine, then must unlink the (possibly
16583 ** changed) master chunk once this routine has finished.
16584 */
16585 static void memsys3Merge(u32 *pRoot){
16586   u32 iNext, prev, size, i, x;
16587
16588   assert( sqlite3_mutex_held(mem3.mutex) );
16589   for(i=*pRoot; i>0; i=iNext){
16590     iNext = mem3.aPool[i].u.list.next;
16591     size = mem3.aPool[i-1].u.hdr.size4x;
16592     assert( (size&1)==0 );
16593     if( (size&2)==0 ){
16594       memsys3UnlinkFromList(i, pRoot);
16595       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
16596       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
16597       if( prev==iNext ){
16598         iNext = mem3.aPool[prev].u.list.next;
16599       }
16600       memsys3Unlink(prev);
16601       size = i + size/4 - prev;
16602       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
16603       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
16604       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
16605       memsys3Link(prev);
16606       i = prev;
16607     }else{
16608       size /= 4;
16609     }
16610     if( size>mem3.szMaster ){
16611       mem3.iMaster = i;
16612       mem3.szMaster = size;
16613     }
16614   }
16615 }
16616
16617 /*
16618 ** Return a block of memory of at least nBytes in size.
16619 ** Return NULL if unable.
16620 **
16621 ** This function assumes that the necessary mutexes, if any, are
16622 ** already held by the caller. Hence "Unsafe".
16623 */
16624 static void *memsys3MallocUnsafe(int nByte){
16625   u32 i;
16626   u32 nBlock;
16627   u32 toFree;
16628
16629   assert( sqlite3_mutex_held(mem3.mutex) );
16630   assert( sizeof(Mem3Block)==8 );
16631   if( nByte<=12 ){
16632     nBlock = 2;
16633   }else{
16634     nBlock = (nByte + 11)/8;
16635   }
16636   assert( nBlock>=2 );
16637
16638   /* STEP 1:
16639   ** Look for an entry of the correct size in either the small
16640   ** chunk table or in the large chunk hash table.  This is
16641   ** successful most of the time (about 9 times out of 10).
16642   */
16643   if( nBlock <= MX_SMALL ){
16644     i = mem3.aiSmall[nBlock-2];
16645     if( i>0 ){
16646       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
16647       return memsys3Checkout(i, nBlock);
16648     }
16649   }else{
16650     int hash = nBlock % N_HASH;
16651     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
16652       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
16653         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16654         return memsys3Checkout(i, nBlock);
16655       }
16656     }
16657   }
16658
16659   /* STEP 2:
16660   ** Try to satisfy the allocation by carving a piece off of the end
16661   ** of the master chunk.  This step usually works if step 1 fails.
16662   */
16663   if( mem3.szMaster>=nBlock ){
16664     return memsys3FromMaster(nBlock);
16665   }
16666
16667
16668   /* STEP 3:  
16669   ** Loop through the entire memory pool.  Coalesce adjacent free
16670   ** chunks.  Recompute the master chunk as the largest free chunk.
16671   ** Then try again to satisfy the allocation by carving a piece off
16672   ** of the end of the master chunk.  This step happens very
16673   ** rarely (we hope!)
16674   */
16675   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
16676     memsys3OutOfMemory(toFree);
16677     if( mem3.iMaster ){
16678       memsys3Link(mem3.iMaster);
16679       mem3.iMaster = 0;
16680       mem3.szMaster = 0;
16681     }
16682     for(i=0; i<N_HASH; i++){
16683       memsys3Merge(&mem3.aiHash[i]);
16684     }
16685     for(i=0; i<MX_SMALL-1; i++){
16686       memsys3Merge(&mem3.aiSmall[i]);
16687     }
16688     if( mem3.szMaster ){
16689       memsys3Unlink(mem3.iMaster);
16690       if( mem3.szMaster>=nBlock ){
16691         return memsys3FromMaster(nBlock);
16692       }
16693     }
16694   }
16695
16696   /* If none of the above worked, then we fail. */
16697   return 0;
16698 }
16699
16700 /*
16701 ** Free an outstanding memory allocation.
16702 **
16703 ** This function assumes that the necessary mutexes, if any, are
16704 ** already held by the caller. Hence "Unsafe".
16705 */
16706 static void memsys3FreeUnsafe(void *pOld){
16707   Mem3Block *p = (Mem3Block*)pOld;
16708   int i;
16709   u32 size, x;
16710   assert( sqlite3_mutex_held(mem3.mutex) );
16711   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
16712   i = p - mem3.aPool;
16713   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
16714   size = mem3.aPool[i-1].u.hdr.size4x/4;
16715   assert( i+size<=mem3.nPool+1 );
16716   mem3.aPool[i-1].u.hdr.size4x &= ~1;
16717   mem3.aPool[i+size-1].u.hdr.prevSize = size;
16718   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
16719   memsys3Link(i);
16720
16721   /* Try to expand the master using the newly freed chunk */
16722   if( mem3.iMaster ){
16723     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
16724       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
16725       mem3.iMaster -= size;
16726       mem3.szMaster += size;
16727       memsys3Unlink(mem3.iMaster);
16728       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16729       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16730       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16731     }
16732     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16733     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
16734       memsys3Unlink(mem3.iMaster+mem3.szMaster);
16735       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
16736       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16737       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16738     }
16739   }
16740 }
16741
16742 /*
16743 ** Return the size of an outstanding allocation, in bytes.  The
16744 ** size returned omits the 8-byte header overhead.  This only
16745 ** works for chunks that are currently checked out.
16746 */
16747 static int memsys3Size(void *p){
16748   Mem3Block *pBlock;
16749   if( p==0 ) return 0;
16750   pBlock = (Mem3Block*)p;
16751   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
16752   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
16753 }
16754
16755 /*
16756 ** Round up a request size to the next valid allocation size.
16757 */
16758 static int memsys3Roundup(int n){
16759   if( n<=12 ){
16760     return 12;
16761   }else{
16762     return ((n+11)&~7) - 4;
16763   }
16764 }
16765
16766 /*
16767 ** Allocate nBytes of memory.
16768 */
16769 static void *memsys3Malloc(int nBytes){
16770   sqlite3_int64 *p;
16771   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
16772   memsys3Enter();
16773   p = memsys3MallocUnsafe(nBytes);
16774   memsys3Leave();
16775   return (void*)p; 
16776 }
16777
16778 /*
16779 ** Free memory.
16780 */
16781 static void memsys3Free(void *pPrior){
16782   assert( pPrior );
16783   memsys3Enter();
16784   memsys3FreeUnsafe(pPrior);
16785   memsys3Leave();
16786 }
16787
16788 /*
16789 ** Change the size of an existing memory allocation
16790 */
16791 static void *memsys3Realloc(void *pPrior, int nBytes){
16792   int nOld;
16793   void *p;
16794   if( pPrior==0 ){
16795     return sqlite3_malloc(nBytes);
16796   }
16797   if( nBytes<=0 ){
16798     sqlite3_free(pPrior);
16799     return 0;
16800   }
16801   nOld = memsys3Size(pPrior);
16802   if( nBytes<=nOld && nBytes>=nOld-128 ){
16803     return pPrior;
16804   }
16805   memsys3Enter();
16806   p = memsys3MallocUnsafe(nBytes);
16807   if( p ){
16808     if( nOld<nBytes ){
16809       memcpy(p, pPrior, nOld);
16810     }else{
16811       memcpy(p, pPrior, nBytes);
16812     }
16813     memsys3FreeUnsafe(pPrior);
16814   }
16815   memsys3Leave();
16816   return p;
16817 }
16818
16819 /*
16820 ** Initialize this module.
16821 */
16822 static int memsys3Init(void *NotUsed){
16823   UNUSED_PARAMETER(NotUsed);
16824   if( !sqlite3GlobalConfig.pHeap ){
16825     return SQLITE_ERROR;
16826   }
16827
16828   /* Store a pointer to the memory block in global structure mem3. */
16829   assert( sizeof(Mem3Block)==8 );
16830   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
16831   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
16832
16833   /* Initialize the master block. */
16834   mem3.szMaster = mem3.nPool;
16835   mem3.mnMaster = mem3.szMaster;
16836   mem3.iMaster = 1;
16837   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
16838   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
16839   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
16840
16841   return SQLITE_OK;
16842 }
16843
16844 /*
16845 ** Deinitialize this module.
16846 */
16847 static void memsys3Shutdown(void *NotUsed){
16848   UNUSED_PARAMETER(NotUsed);
16849   mem3.mutex = 0;
16850   return;
16851 }
16852
16853
16854
16855 /*
16856 ** Open the file indicated and write a log of all unfreed memory 
16857 ** allocations into that log.
16858 */
16859 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
16860 #ifdef SQLITE_DEBUG
16861   FILE *out;
16862   u32 i, j;
16863   u32 size;
16864   if( zFilename==0 || zFilename[0]==0 ){
16865     out = stdout;
16866   }else{
16867     out = fopen(zFilename, "w");
16868     if( out==0 ){
16869       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16870                       zFilename);
16871       return;
16872     }
16873   }
16874   memsys3Enter();
16875   fprintf(out, "CHUNKS:\n");
16876   for(i=1; i<=mem3.nPool; i+=size/4){
16877     size = mem3.aPool[i-1].u.hdr.size4x;
16878     if( size/4<=1 ){
16879       fprintf(out, "%p size error\n", &mem3.aPool[i]);
16880       assert( 0 );
16881       break;
16882     }
16883     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
16884       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
16885       assert( 0 );
16886       break;
16887     }
16888     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
16889       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
16890       assert( 0 );
16891       break;
16892     }
16893     if( size&1 ){
16894       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
16895     }else{
16896       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
16897                   i==mem3.iMaster ? " **master**" : "");
16898     }
16899   }
16900   for(i=0; i<MX_SMALL-1; i++){
16901     if( mem3.aiSmall[i]==0 ) continue;
16902     fprintf(out, "small(%2d):", i);
16903     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
16904       fprintf(out, " %p(%d)", &mem3.aPool[j],
16905               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16906     }
16907     fprintf(out, "\n"); 
16908   }
16909   for(i=0; i<N_HASH; i++){
16910     if( mem3.aiHash[i]==0 ) continue;
16911     fprintf(out, "hash(%2d):", i);
16912     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
16913       fprintf(out, " %p(%d)", &mem3.aPool[j],
16914               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16915     }
16916     fprintf(out, "\n"); 
16917   }
16918   fprintf(out, "master=%d\n", mem3.iMaster);
16919   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
16920   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
16921   sqlite3_mutex_leave(mem3.mutex);
16922   if( out==stdout ){
16923     fflush(stdout);
16924   }else{
16925     fclose(out);
16926   }
16927 #else
16928   UNUSED_PARAMETER(zFilename);
16929 #endif
16930 }
16931
16932 /*
16933 ** This routine is the only routine in this file with external 
16934 ** linkage.
16935 **
16936 ** Populate the low-level memory allocation function pointers in
16937 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
16938 ** arguments specify the block of memory to manage.
16939 **
16940 ** This routine is only called by sqlite3_config(), and therefore
16941 ** is not required to be threadsafe (it is not).
16942 */
16943 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
16944   static const sqlite3_mem_methods mempoolMethods = {
16945      memsys3Malloc,
16946      memsys3Free,
16947      memsys3Realloc,
16948      memsys3Size,
16949      memsys3Roundup,
16950      memsys3Init,
16951      memsys3Shutdown,
16952      0
16953   };
16954   return &mempoolMethods;
16955 }
16956
16957 #endif /* SQLITE_ENABLE_MEMSYS3 */
16958
16959 /************** End of mem3.c ************************************************/
16960 /************** Begin file mem5.c ********************************************/
16961 /*
16962 ** 2007 October 14
16963 **
16964 ** The author disclaims copyright to this source code.  In place of
16965 ** a legal notice, here is a blessing:
16966 **
16967 **    May you do good and not evil.
16968 **    May you find forgiveness for yourself and forgive others.
16969 **    May you share freely, never taking more than you give.
16970 **
16971 *************************************************************************
16972 ** This file contains the C functions that implement a memory
16973 ** allocation subsystem for use by SQLite. 
16974 **
16975 ** This version of the memory allocation subsystem omits all
16976 ** use of malloc(). The application gives SQLite a block of memory
16977 ** before calling sqlite3_initialize() from which allocations
16978 ** are made and returned by the xMalloc() and xRealloc() 
16979 ** implementations. Once sqlite3_initialize() has been called,
16980 ** the amount of memory available to SQLite is fixed and cannot
16981 ** be changed.
16982 **
16983 ** This version of the memory allocation subsystem is included
16984 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
16985 **
16986 ** This memory allocator uses the following algorithm:
16987 **
16988 **   1.  All memory allocations sizes are rounded up to a power of 2.
16989 **
16990 **   2.  If two adjacent free blocks are the halves of a larger block,
16991 **       then the two blocks are coalesed into the single larger block.
16992 **
16993 **   3.  New memory is allocated from the first available free block.
16994 **
16995 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
16996 ** Concerning Dynamic Storage Allocation". Journal of the Association for
16997 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
16998 ** 
16999 ** Let n be the size of the largest allocation divided by the minimum
17000 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
17001 ** be the maximum amount of memory ever outstanding at one time.  Let
17002 ** N be the total amount of memory available for allocation.  Robson
17003 ** proved that this memory allocator will never breakdown due to 
17004 ** fragmentation as long as the following constraint holds:
17005 **
17006 **      N >=  M*(1 + log2(n)/2) - n + 1
17007 **
17008 ** The sqlite3_status() logic tracks the maximum values of n and M so
17009 ** that an application can, at any time, verify this constraint.
17010 */
17011
17012 /*
17013 ** This version of the memory allocator is used only when 
17014 ** SQLITE_ENABLE_MEMSYS5 is defined.
17015 */
17016 #ifdef SQLITE_ENABLE_MEMSYS5
17017
17018 /*
17019 ** A minimum allocation is an instance of the following structure.
17020 ** Larger allocations are an array of these structures where the
17021 ** size of the array is a power of 2.
17022 **
17023 ** The size of this object must be a power of two.  That fact is
17024 ** verified in memsys5Init().
17025 */
17026 typedef struct Mem5Link Mem5Link;
17027 struct Mem5Link {
17028   int next;       /* Index of next free chunk */
17029   int prev;       /* Index of previous free chunk */
17030 };
17031
17032 /*
17033 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
17034 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
17035 ** it is not actually possible to reach this limit.
17036 */
17037 #define LOGMAX 30
17038
17039 /*
17040 ** Masks used for mem5.aCtrl[] elements.
17041 */
17042 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
17043 #define CTRL_FREE     0x20    /* True if not checked out */
17044
17045 /*
17046 ** All of the static variables used by this module are collected
17047 ** into a single structure named "mem5".  This is to keep the
17048 ** static variables organized and to reduce namespace pollution
17049 ** when this module is combined with other in the amalgamation.
17050 */
17051 static SQLITE_WSD struct Mem5Global {
17052   /*
17053   ** Memory available for allocation
17054   */
17055   int szAtom;      /* Smallest possible allocation in bytes */
17056   int nBlock;      /* Number of szAtom sized blocks in zPool */
17057   u8 *zPool;       /* Memory available to be allocated */
17058   
17059   /*
17060   ** Mutex to control access to the memory allocation subsystem.
17061   */
17062   sqlite3_mutex *mutex;
17063
17064   /*
17065   ** Performance statistics
17066   */
17067   u64 nAlloc;         /* Total number of calls to malloc */
17068   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
17069   u64 totalExcess;    /* Total internal fragmentation */
17070   u32 currentOut;     /* Current checkout, including internal fragmentation */
17071   u32 currentCount;   /* Current number of distinct checkouts */
17072   u32 maxOut;         /* Maximum instantaneous currentOut */
17073   u32 maxCount;       /* Maximum instantaneous currentCount */
17074   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
17075   
17076   /*
17077   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
17078   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
17079   ** and so forth.
17080   */
17081   int aiFreelist[LOGMAX+1];
17082
17083   /*
17084   ** Space for tracking which blocks are checked out and the size
17085   ** of each block.  One byte per block.
17086   */
17087   u8 *aCtrl;
17088
17089 } mem5;
17090
17091 /*
17092 ** Access the static variable through a macro for SQLITE_OMIT_WSD
17093 */
17094 #define mem5 GLOBAL(struct Mem5Global, mem5)
17095
17096 /*
17097 ** Assuming mem5.zPool is divided up into an array of Mem5Link
17098 ** structures, return a pointer to the idx-th such lik.
17099 */
17100 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
17101
17102 /*
17103 ** Unlink the chunk at mem5.aPool[i] from list it is currently
17104 ** on.  It should be found on mem5.aiFreelist[iLogsize].
17105 */
17106 static void memsys5Unlink(int i, int iLogsize){
17107   int next, prev;
17108   assert( i>=0 && i<mem5.nBlock );
17109   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17110   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17111
17112   next = MEM5LINK(i)->next;
17113   prev = MEM5LINK(i)->prev;
17114   if( prev<0 ){
17115     mem5.aiFreelist[iLogsize] = next;
17116   }else{
17117     MEM5LINK(prev)->next = next;
17118   }
17119   if( next>=0 ){
17120     MEM5LINK(next)->prev = prev;
17121   }
17122 }
17123
17124 /*
17125 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
17126 ** free list.
17127 */
17128 static void memsys5Link(int i, int iLogsize){
17129   int x;
17130   assert( sqlite3_mutex_held(mem5.mutex) );
17131   assert( i>=0 && i<mem5.nBlock );
17132   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17133   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17134
17135   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
17136   MEM5LINK(i)->prev = -1;
17137   if( x>=0 ){
17138     assert( x<mem5.nBlock );
17139     MEM5LINK(x)->prev = i;
17140   }
17141   mem5.aiFreelist[iLogsize] = i;
17142 }
17143
17144 /*
17145 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17146 ** will already be held (obtained by code in malloc.c) if
17147 ** sqlite3GlobalConfig.bMemStat is true.
17148 */
17149 static void memsys5Enter(void){
17150   sqlite3_mutex_enter(mem5.mutex);
17151 }
17152 static void memsys5Leave(void){
17153   sqlite3_mutex_leave(mem5.mutex);
17154 }
17155
17156 /*
17157 ** Return the size of an outstanding allocation, in bytes.  The
17158 ** size returned omits the 8-byte header overhead.  This only
17159 ** works for chunks that are currently checked out.
17160 */
17161 static int memsys5Size(void *p){
17162   int iSize = 0;
17163   if( p ){
17164     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
17165     assert( i>=0 && i<mem5.nBlock );
17166     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
17167   }
17168   return iSize;
17169 }
17170
17171 /*
17172 ** Find the first entry on the freelist iLogsize.  Unlink that
17173 ** entry and return its index. 
17174 */
17175 static int memsys5UnlinkFirst(int iLogsize){
17176   int i;
17177   int iFirst;
17178
17179   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17180   i = iFirst = mem5.aiFreelist[iLogsize];
17181   assert( iFirst>=0 );
17182   while( i>0 ){
17183     if( i<iFirst ) iFirst = i;
17184     i = MEM5LINK(i)->next;
17185   }
17186   memsys5Unlink(iFirst, iLogsize);
17187   return iFirst;
17188 }
17189
17190 /*
17191 ** Return a block of memory of at least nBytes in size.
17192 ** Return NULL if unable.  Return NULL if nBytes==0.
17193 **
17194 ** The caller guarantees that nByte positive.
17195 **
17196 ** The caller has obtained a mutex prior to invoking this
17197 ** routine so there is never any chance that two or more
17198 ** threads can be in this routine at the same time.
17199 */
17200 static void *memsys5MallocUnsafe(int nByte){
17201   int i;           /* Index of a mem5.aPool[] slot */
17202   int iBin;        /* Index into mem5.aiFreelist[] */
17203   int iFullSz;     /* Size of allocation rounded up to power of 2 */
17204   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
17205
17206   /* nByte must be a positive */
17207   assert( nByte>0 );
17208
17209   /* Keep track of the maximum allocation request.  Even unfulfilled
17210   ** requests are counted */
17211   if( (u32)nByte>mem5.maxRequest ){
17212     mem5.maxRequest = nByte;
17213   }
17214
17215   /* Abort if the requested allocation size is larger than the largest
17216   ** power of two that we can represent using 32-bit signed integers.
17217   */
17218   if( nByte > 0x40000000 ){
17219     return 0;
17220   }
17221
17222   /* Round nByte up to the next valid power of two */
17223   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
17224
17225   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
17226   ** block.  If not, then split a block of the next larger power of
17227   ** two in order to create a new free block of size iLogsize.
17228   */
17229   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
17230   if( iBin>LOGMAX ){
17231     testcase( sqlite3GlobalConfig.xLog!=0 );
17232     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
17233     return 0;
17234   }
17235   i = memsys5UnlinkFirst(iBin);
17236   while( iBin>iLogsize ){
17237     int newSize;
17238
17239     iBin--;
17240     newSize = 1 << iBin;
17241     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
17242     memsys5Link(i+newSize, iBin);
17243   }
17244   mem5.aCtrl[i] = iLogsize;
17245
17246   /* Update allocator performance statistics. */
17247   mem5.nAlloc++;
17248   mem5.totalAlloc += iFullSz;
17249   mem5.totalExcess += iFullSz - nByte;
17250   mem5.currentCount++;
17251   mem5.currentOut += iFullSz;
17252   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
17253   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
17254
17255   /* Return a pointer to the allocated memory. */
17256   return (void*)&mem5.zPool[i*mem5.szAtom];
17257 }
17258
17259 /*
17260 ** Free an outstanding memory allocation.
17261 */
17262 static void memsys5FreeUnsafe(void *pOld){
17263   u32 size, iLogsize;
17264   int iBlock;
17265
17266   /* Set iBlock to the index of the block pointed to by pOld in 
17267   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
17268   */
17269   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
17270
17271   /* Check that the pointer pOld points to a valid, non-free block. */
17272   assert( iBlock>=0 && iBlock<mem5.nBlock );
17273   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
17274   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
17275
17276   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
17277   size = 1<<iLogsize;
17278   assert( iBlock+size-1<(u32)mem5.nBlock );
17279
17280   mem5.aCtrl[iBlock] |= CTRL_FREE;
17281   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
17282   assert( mem5.currentCount>0 );
17283   assert( mem5.currentOut>=(size*mem5.szAtom) );
17284   mem5.currentCount--;
17285   mem5.currentOut -= size*mem5.szAtom;
17286   assert( mem5.currentOut>0 || mem5.currentCount==0 );
17287   assert( mem5.currentCount>0 || mem5.currentOut==0 );
17288
17289   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17290   while( ALWAYS(iLogsize<LOGMAX) ){
17291     int iBuddy;
17292     if( (iBlock>>iLogsize) & 1 ){
17293       iBuddy = iBlock - size;
17294     }else{
17295       iBuddy = iBlock + size;
17296     }
17297     assert( iBuddy>=0 );
17298     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
17299     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
17300     memsys5Unlink(iBuddy, iLogsize);
17301     iLogsize++;
17302     if( iBuddy<iBlock ){
17303       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
17304       mem5.aCtrl[iBlock] = 0;
17305       iBlock = iBuddy;
17306     }else{
17307       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17308       mem5.aCtrl[iBuddy] = 0;
17309     }
17310     size *= 2;
17311   }
17312   memsys5Link(iBlock, iLogsize);
17313 }
17314
17315 /*
17316 ** Allocate nBytes of memory
17317 */
17318 static void *memsys5Malloc(int nBytes){
17319   sqlite3_int64 *p = 0;
17320   if( nBytes>0 ){
17321     memsys5Enter();
17322     p = memsys5MallocUnsafe(nBytes);
17323     memsys5Leave();
17324   }
17325   return (void*)p; 
17326 }
17327
17328 /*
17329 ** Free memory.
17330 **
17331 ** The outer layer memory allocator prevents this routine from
17332 ** being called with pPrior==0.
17333 */
17334 static void memsys5Free(void *pPrior){
17335   assert( pPrior!=0 );
17336   memsys5Enter();
17337   memsys5FreeUnsafe(pPrior);
17338   memsys5Leave();  
17339 }
17340
17341 /*
17342 ** Change the size of an existing memory allocation.
17343 **
17344 ** The outer layer memory allocator prevents this routine from
17345 ** being called with pPrior==0.  
17346 **
17347 ** nBytes is always a value obtained from a prior call to
17348 ** memsys5Round().  Hence nBytes is always a non-negative power
17349 ** of two.  If nBytes==0 that means that an oversize allocation
17350 ** (an allocation larger than 0x40000000) was requested and this
17351 ** routine should return 0 without freeing pPrior.
17352 */
17353 static void *memsys5Realloc(void *pPrior, int nBytes){
17354   int nOld;
17355   void *p;
17356   assert( pPrior!=0 );
17357   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
17358   assert( nBytes>=0 );
17359   if( nBytes==0 ){
17360     return 0;
17361   }
17362   nOld = memsys5Size(pPrior);
17363   if( nBytes<=nOld ){
17364     return pPrior;
17365   }
17366   memsys5Enter();
17367   p = memsys5MallocUnsafe(nBytes);
17368   if( p ){
17369     memcpy(p, pPrior, nOld);
17370     memsys5FreeUnsafe(pPrior);
17371   }
17372   memsys5Leave();
17373   return p;
17374 }
17375
17376 /*
17377 ** Round up a request size to the next valid allocation size.  If
17378 ** the allocation is too large to be handled by this allocation system,
17379 ** return 0.
17380 **
17381 ** All allocations must be a power of two and must be expressed by a
17382 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
17383 ** or 1073741824 bytes.
17384 */
17385 static int memsys5Roundup(int n){
17386   int iFullSz;
17387   if( n > 0x40000000 ) return 0;
17388   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
17389   return iFullSz;
17390 }
17391
17392 /*
17393 ** Return the ceiling of the logarithm base 2 of iValue.
17394 **
17395 ** Examples:   memsys5Log(1) -> 0
17396 **             memsys5Log(2) -> 1
17397 **             memsys5Log(4) -> 2
17398 **             memsys5Log(5) -> 3
17399 **             memsys5Log(8) -> 3
17400 **             memsys5Log(9) -> 4
17401 */
17402 static int memsys5Log(int iValue){
17403   int iLog;
17404   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
17405   return iLog;
17406 }
17407
17408 /*
17409 ** Initialize the memory allocator.
17410 **
17411 ** This routine is not threadsafe.  The caller must be holding a mutex
17412 ** to prevent multiple threads from entering at the same time.
17413 */
17414 static int memsys5Init(void *NotUsed){
17415   int ii;            /* Loop counter */
17416   int nByte;         /* Number of bytes of memory available to this allocator */
17417   u8 *zByte;         /* Memory usable by this allocator */
17418   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
17419   int iOffset;       /* An offset into mem5.aCtrl[] */
17420
17421   UNUSED_PARAMETER(NotUsed);
17422
17423   /* For the purposes of this routine, disable the mutex */
17424   mem5.mutex = 0;
17425
17426   /* The size of a Mem5Link object must be a power of two.  Verify that
17427   ** this is case.
17428   */
17429   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
17430
17431   nByte = sqlite3GlobalConfig.nHeap;
17432   zByte = (u8*)sqlite3GlobalConfig.pHeap;
17433   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
17434
17435   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
17436   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
17437   mem5.szAtom = (1<<nMinLog);
17438   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
17439     mem5.szAtom = mem5.szAtom << 1;
17440   }
17441
17442   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
17443   mem5.zPool = zByte;
17444   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
17445
17446   for(ii=0; ii<=LOGMAX; ii++){
17447     mem5.aiFreelist[ii] = -1;
17448   }
17449
17450   iOffset = 0;
17451   for(ii=LOGMAX; ii>=0; ii--){
17452     int nAlloc = (1<<ii);
17453     if( (iOffset+nAlloc)<=mem5.nBlock ){
17454       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
17455       memsys5Link(iOffset, ii);
17456       iOffset += nAlloc;
17457     }
17458     assert((iOffset+nAlloc)>mem5.nBlock);
17459   }
17460
17461   /* If a mutex is required for normal operation, allocate one */
17462   if( sqlite3GlobalConfig.bMemstat==0 ){
17463     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17464   }
17465
17466   return SQLITE_OK;
17467 }
17468
17469 /*
17470 ** Deinitialize this module.
17471 */
17472 static void memsys5Shutdown(void *NotUsed){
17473   UNUSED_PARAMETER(NotUsed);
17474   mem5.mutex = 0;
17475   return;
17476 }
17477
17478 #ifdef SQLITE_TEST
17479 /*
17480 ** Open the file indicated and write a log of all unfreed memory 
17481 ** allocations into that log.
17482 */
17483 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
17484   FILE *out;
17485   int i, j, n;
17486   int nMinLog;
17487
17488   if( zFilename==0 || zFilename[0]==0 ){
17489     out = stdout;
17490   }else{
17491     out = fopen(zFilename, "w");
17492     if( out==0 ){
17493       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17494                       zFilename);
17495       return;
17496     }
17497   }
17498   memsys5Enter();
17499   nMinLog = memsys5Log(mem5.szAtom);
17500   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
17501     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
17502     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
17503   }
17504   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
17505   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
17506   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
17507   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
17508   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
17509   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
17510   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
17511   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
17512   memsys5Leave();
17513   if( out==stdout ){
17514     fflush(stdout);
17515   }else{
17516     fclose(out);
17517   }
17518 }
17519 #endif
17520
17521 /*
17522 ** This routine is the only routine in this file with external 
17523 ** linkage. It returns a pointer to a static sqlite3_mem_methods
17524 ** struct populated with the memsys5 methods.
17525 */
17526 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
17527   static const sqlite3_mem_methods memsys5Methods = {
17528      memsys5Malloc,
17529      memsys5Free,
17530      memsys5Realloc,
17531      memsys5Size,
17532      memsys5Roundup,
17533      memsys5Init,
17534      memsys5Shutdown,
17535      0
17536   };
17537   return &memsys5Methods;
17538 }
17539
17540 #endif /* SQLITE_ENABLE_MEMSYS5 */
17541
17542 /************** End of mem5.c ************************************************/
17543 /************** Begin file mutex.c *******************************************/
17544 /*
17545 ** 2007 August 14
17546 **
17547 ** The author disclaims copyright to this source code.  In place of
17548 ** a legal notice, here is a blessing:
17549 **
17550 **    May you do good and not evil.
17551 **    May you find forgiveness for yourself and forgive others.
17552 **    May you share freely, never taking more than you give.
17553 **
17554 *************************************************************************
17555 ** This file contains the C functions that implement mutexes.
17556 **
17557 ** This file contains code that is common across all mutex implementations.
17558 */
17559
17560 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
17561 /*
17562 ** For debugging purposes, record when the mutex subsystem is initialized
17563 ** and uninitialized so that we can assert() if there is an attempt to
17564 ** allocate a mutex while the system is uninitialized.
17565 */
17566 static SQLITE_WSD int mutexIsInit = 0;
17567 #endif /* SQLITE_DEBUG */
17568
17569
17570 #ifndef SQLITE_MUTEX_OMIT
17571 /*
17572 ** Initialize the mutex system.
17573 */
17574 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
17575   int rc = SQLITE_OK;
17576   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
17577     /* If the xMutexAlloc method has not been set, then the user did not
17578     ** install a mutex implementation via sqlite3_config() prior to 
17579     ** sqlite3_initialize() being called. This block copies pointers to
17580     ** the default implementation into the sqlite3GlobalConfig structure.
17581     */
17582     sqlite3_mutex_methods const *pFrom;
17583     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
17584
17585     if( sqlite3GlobalConfig.bCoreMutex ){
17586       pFrom = sqlite3DefaultMutex();
17587     }else{
17588       pFrom = sqlite3NoopMutex();
17589     }
17590     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
17591     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
17592            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
17593     pTo->xMutexAlloc = pFrom->xMutexAlloc;
17594   }
17595   rc = sqlite3GlobalConfig.mutex.xMutexInit();
17596
17597 #ifdef SQLITE_DEBUG
17598   GLOBAL(int, mutexIsInit) = 1;
17599 #endif
17600
17601   return rc;
17602 }
17603
17604 /*
17605 ** Shutdown the mutex system. This call frees resources allocated by
17606 ** sqlite3MutexInit().
17607 */
17608 SQLITE_PRIVATE int sqlite3MutexEnd(void){
17609   int rc = SQLITE_OK;
17610   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
17611     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
17612   }
17613
17614 #ifdef SQLITE_DEBUG
17615   GLOBAL(int, mutexIsInit) = 0;
17616 #endif
17617
17618   return rc;
17619 }
17620
17621 /*
17622 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
17623 */
17624 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
17625 #ifndef SQLITE_OMIT_AUTOINIT
17626   if( sqlite3_initialize() ) return 0;
17627 #endif
17628   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17629 }
17630
17631 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
17632   if( !sqlite3GlobalConfig.bCoreMutex ){
17633     return 0;
17634   }
17635   assert( GLOBAL(int, mutexIsInit) );
17636   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17637 }
17638
17639 /*
17640 ** Free a dynamic mutex.
17641 */
17642 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
17643   if( p ){
17644     sqlite3GlobalConfig.mutex.xMutexFree(p);
17645   }
17646 }
17647
17648 /*
17649 ** Obtain the mutex p. If some other thread already has the mutex, block
17650 ** until it can be obtained.
17651 */
17652 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
17653   if( p ){
17654     sqlite3GlobalConfig.mutex.xMutexEnter(p);
17655   }
17656 }
17657
17658 /*
17659 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
17660 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
17661 */
17662 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
17663   int rc = SQLITE_OK;
17664   if( p ){
17665     return sqlite3GlobalConfig.mutex.xMutexTry(p);
17666   }
17667   return rc;
17668 }
17669
17670 /*
17671 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
17672 ** entered by the same thread.  The behavior is undefined if the mutex 
17673 ** is not currently entered. If a NULL pointer is passed as an argument
17674 ** this function is a no-op.
17675 */
17676 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
17677   if( p ){
17678     sqlite3GlobalConfig.mutex.xMutexLeave(p);
17679   }
17680 }
17681
17682 #ifndef NDEBUG
17683 /*
17684 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17685 ** intended for use inside assert() statements.
17686 */
17687 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
17688   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
17689 }
17690 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
17691   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
17692 }
17693 #endif
17694
17695 #endif /* !defined(SQLITE_MUTEX_OMIT) */
17696
17697 /************** End of mutex.c ***********************************************/
17698 /************** Begin file mutex_noop.c **************************************/
17699 /*
17700 ** 2008 October 07
17701 **
17702 ** The author disclaims copyright to this source code.  In place of
17703 ** a legal notice, here is a blessing:
17704 **
17705 **    May you do good and not evil.
17706 **    May you find forgiveness for yourself and forgive others.
17707 **    May you share freely, never taking more than you give.
17708 **
17709 *************************************************************************
17710 ** This file contains the C functions that implement mutexes.
17711 **
17712 ** This implementation in this file does not provide any mutual
17713 ** exclusion and is thus suitable for use only in applications
17714 ** that use SQLite in a single thread.  The routines defined
17715 ** here are place-holders.  Applications can substitute working
17716 ** mutex routines at start-time using the
17717 **
17718 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
17719 **
17720 ** interface.
17721 **
17722 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
17723 ** that does error checking on mutexes to make sure they are being
17724 ** called correctly.
17725 */
17726
17727 #ifndef SQLITE_MUTEX_OMIT
17728
17729 #ifndef SQLITE_DEBUG
17730 /*
17731 ** Stub routines for all mutex methods.
17732 **
17733 ** This routines provide no mutual exclusion or error checking.
17734 */
17735 static int noopMutexInit(void){ return SQLITE_OK; }
17736 static int noopMutexEnd(void){ return SQLITE_OK; }
17737 static sqlite3_mutex *noopMutexAlloc(int id){ 
17738   UNUSED_PARAMETER(id);
17739   return (sqlite3_mutex*)8; 
17740 }
17741 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17742 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17743 static int noopMutexTry(sqlite3_mutex *p){
17744   UNUSED_PARAMETER(p);
17745   return SQLITE_OK;
17746 }
17747 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17748
17749 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17750   static const sqlite3_mutex_methods sMutex = {
17751     noopMutexInit,
17752     noopMutexEnd,
17753     noopMutexAlloc,
17754     noopMutexFree,
17755     noopMutexEnter,
17756     noopMutexTry,
17757     noopMutexLeave,
17758
17759     0,
17760     0,
17761   };
17762
17763   return &sMutex;
17764 }
17765 #endif /* !SQLITE_DEBUG */
17766
17767 #ifdef SQLITE_DEBUG
17768 /*
17769 ** In this implementation, error checking is provided for testing
17770 ** and debugging purposes.  The mutexes still do not provide any
17771 ** mutual exclusion.
17772 */
17773
17774 /*
17775 ** The mutex object
17776 */
17777 typedef struct sqlite3_debug_mutex {
17778   int id;     /* The mutex type */
17779   int cnt;    /* Number of entries without a matching leave */
17780 } sqlite3_debug_mutex;
17781
17782 /*
17783 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17784 ** intended for use inside assert() statements.
17785 */
17786 static int debugMutexHeld(sqlite3_mutex *pX){
17787   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17788   return p==0 || p->cnt>0;
17789 }
17790 static int debugMutexNotheld(sqlite3_mutex *pX){
17791   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17792   return p==0 || p->cnt==0;
17793 }
17794
17795 /*
17796 ** Initialize and deinitialize the mutex subsystem.
17797 */
17798 static int debugMutexInit(void){ return SQLITE_OK; }
17799 static int debugMutexEnd(void){ return SQLITE_OK; }
17800
17801 /*
17802 ** The sqlite3_mutex_alloc() routine allocates a new
17803 ** mutex and returns a pointer to it.  If it returns NULL
17804 ** that means that a mutex could not be allocated. 
17805 */
17806 static sqlite3_mutex *debugMutexAlloc(int id){
17807   static sqlite3_debug_mutex aStatic[6];
17808   sqlite3_debug_mutex *pNew = 0;
17809   switch( id ){
17810     case SQLITE_MUTEX_FAST:
17811     case SQLITE_MUTEX_RECURSIVE: {
17812       pNew = sqlite3Malloc(sizeof(*pNew));
17813       if( pNew ){
17814         pNew->id = id;
17815         pNew->cnt = 0;
17816       }
17817       break;
17818     }
17819     default: {
17820       assert( id-2 >= 0 );
17821       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
17822       pNew = &aStatic[id-2];
17823       pNew->id = id;
17824       break;
17825     }
17826   }
17827   return (sqlite3_mutex*)pNew;
17828 }
17829
17830 /*
17831 ** This routine deallocates a previously allocated mutex.
17832 */
17833 static void debugMutexFree(sqlite3_mutex *pX){
17834   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17835   assert( p->cnt==0 );
17836   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17837   sqlite3_free(p);
17838 }
17839
17840 /*
17841 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17842 ** to enter a mutex.  If another thread is already within the mutex,
17843 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17844 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17845 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17846 ** be entered multiple times by the same thread.  In such cases the,
17847 ** mutex must be exited an equal number of times before another thread
17848 ** can enter.  If the same thread tries to enter any other kind of mutex
17849 ** more than once, the behavior is undefined.
17850 */
17851 static void debugMutexEnter(sqlite3_mutex *pX){
17852   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17853   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17854   p->cnt++;
17855 }
17856 static int debugMutexTry(sqlite3_mutex *pX){
17857   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17858   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17859   p->cnt++;
17860   return SQLITE_OK;
17861 }
17862
17863 /*
17864 ** The sqlite3_mutex_leave() routine exits a mutex that was
17865 ** previously entered by the same thread.  The behavior
17866 ** is undefined if the mutex is not currently entered or
17867 ** is not currently allocated.  SQLite will never do either.
17868 */
17869 static void debugMutexLeave(sqlite3_mutex *pX){
17870   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17871   assert( debugMutexHeld(pX) );
17872   p->cnt--;
17873   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17874 }
17875
17876 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17877   static const sqlite3_mutex_methods sMutex = {
17878     debugMutexInit,
17879     debugMutexEnd,
17880     debugMutexAlloc,
17881     debugMutexFree,
17882     debugMutexEnter,
17883     debugMutexTry,
17884     debugMutexLeave,
17885
17886     debugMutexHeld,
17887     debugMutexNotheld
17888   };
17889
17890   return &sMutex;
17891 }
17892 #endif /* SQLITE_DEBUG */
17893
17894 /*
17895 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
17896 ** is used regardless of the run-time threadsafety setting.
17897 */
17898 #ifdef SQLITE_MUTEX_NOOP
17899 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17900   return sqlite3NoopMutex();
17901 }
17902 #endif /* defined(SQLITE_MUTEX_NOOP) */
17903 #endif /* !defined(SQLITE_MUTEX_OMIT) */
17904
17905 /************** End of mutex_noop.c ******************************************/
17906 /************** Begin file mutex_unix.c **************************************/
17907 /*
17908 ** 2007 August 28
17909 **
17910 ** The author disclaims copyright to this source code.  In place of
17911 ** a legal notice, here is a blessing:
17912 **
17913 **    May you do good and not evil.
17914 **    May you find forgiveness for yourself and forgive others.
17915 **    May you share freely, never taking more than you give.
17916 **
17917 *************************************************************************
17918 ** This file contains the C functions that implement mutexes for pthreads
17919 */
17920
17921 /*
17922 ** The code in this file is only used if we are compiling threadsafe
17923 ** under unix with pthreads.
17924 **
17925 ** Note that this implementation requires a version of pthreads that
17926 ** supports recursive mutexes.
17927 */
17928 #ifdef SQLITE_MUTEX_PTHREADS
17929
17930 #include <pthread.h>
17931
17932 /*
17933 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17934 ** are necessary under two condidtions:  (1) Debug builds and (2) using
17935 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
17936 */
17937 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17938 # define SQLITE_MUTEX_NREF 1
17939 #else
17940 # define SQLITE_MUTEX_NREF 0
17941 #endif
17942
17943 /*
17944 ** Each recursive mutex is an instance of the following structure.
17945 */
17946 struct sqlite3_mutex {
17947   pthread_mutex_t mutex;     /* Mutex controlling the lock */
17948 #if SQLITE_MUTEX_NREF
17949   int id;                    /* Mutex type */
17950   volatile int nRef;         /* Number of entrances */
17951   volatile pthread_t owner;  /* Thread that is within this mutex */
17952   int trace;                 /* True to trace changes */
17953 #endif
17954 };
17955 #if SQLITE_MUTEX_NREF
17956 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17957 #else
17958 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17959 #endif
17960
17961 /*
17962 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17963 ** intended for use only inside assert() statements.  On some platforms,
17964 ** there might be race conditions that can cause these routines to
17965 ** deliver incorrect results.  In particular, if pthread_equal() is
17966 ** not an atomic operation, then these routines might delivery
17967 ** incorrect results.  On most platforms, pthread_equal() is a 
17968 ** comparison of two integers and is therefore atomic.  But we are
17969 ** told that HPUX is not such a platform.  If so, then these routines
17970 ** will not always work correctly on HPUX.
17971 **
17972 ** On those platforms where pthread_equal() is not atomic, SQLite
17973 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17974 ** make sure no assert() statements are evaluated and hence these
17975 ** routines are never called.
17976 */
17977 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17978 static int pthreadMutexHeld(sqlite3_mutex *p){
17979   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17980 }
17981 static int pthreadMutexNotheld(sqlite3_mutex *p){
17982   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17983 }
17984 #endif
17985
17986 /*
17987 ** Initialize and deinitialize the mutex subsystem.
17988 */
17989 static int pthreadMutexInit(void){ return SQLITE_OK; }
17990 static int pthreadMutexEnd(void){ return SQLITE_OK; }
17991
17992 /*
17993 ** The sqlite3_mutex_alloc() routine allocates a new
17994 ** mutex and returns a pointer to it.  If it returns NULL
17995 ** that means that a mutex could not be allocated.  SQLite
17996 ** will unwind its stack and return an error.  The argument
17997 ** to sqlite3_mutex_alloc() is one of these integer constants:
17998 **
17999 ** <ul>
18000 ** <li>  SQLITE_MUTEX_FAST
18001 ** <li>  SQLITE_MUTEX_RECURSIVE
18002 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18003 ** <li>  SQLITE_MUTEX_STATIC_MEM
18004 ** <li>  SQLITE_MUTEX_STATIC_MEM2
18005 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18006 ** <li>  SQLITE_MUTEX_STATIC_LRU
18007 ** <li>  SQLITE_MUTEX_STATIC_PMEM
18008 ** </ul>
18009 **
18010 ** The first two constants cause sqlite3_mutex_alloc() to create
18011 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18012 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18013 ** The mutex implementation does not need to make a distinction
18014 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18015 ** not want to.  But SQLite will only request a recursive mutex in
18016 ** cases where it really needs one.  If a faster non-recursive mutex
18017 ** implementation is available on the host platform, the mutex subsystem
18018 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18019 **
18020 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18021 ** a pointer to a static preexisting mutex.  Six static mutexes are
18022 ** used by the current version of SQLite.  Future versions of SQLite
18023 ** may add additional static mutexes.  Static mutexes are for internal
18024 ** use by SQLite only.  Applications that use SQLite mutexes should
18025 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18026 ** SQLITE_MUTEX_RECURSIVE.
18027 **
18028 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18029 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18030 ** returns a different mutex on every call.  But for the static 
18031 ** mutex types, the same mutex is returned on every call that has
18032 ** the same type number.
18033 */
18034 static sqlite3_mutex *pthreadMutexAlloc(int iType){
18035   static sqlite3_mutex staticMutexes[] = {
18036     SQLITE3_MUTEX_INITIALIZER,
18037     SQLITE3_MUTEX_INITIALIZER,
18038     SQLITE3_MUTEX_INITIALIZER,
18039     SQLITE3_MUTEX_INITIALIZER,
18040     SQLITE3_MUTEX_INITIALIZER,
18041     SQLITE3_MUTEX_INITIALIZER
18042   };
18043   sqlite3_mutex *p;
18044   switch( iType ){
18045     case SQLITE_MUTEX_RECURSIVE: {
18046       p = sqlite3MallocZero( sizeof(*p) );
18047       if( p ){
18048 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18049         /* If recursive mutexes are not available, we will have to
18050         ** build our own.  See below. */
18051         pthread_mutex_init(&p->mutex, 0);
18052 #else
18053         /* Use a recursive mutex if it is available */
18054         pthread_mutexattr_t recursiveAttr;
18055         pthread_mutexattr_init(&recursiveAttr);
18056         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
18057         pthread_mutex_init(&p->mutex, &recursiveAttr);
18058         pthread_mutexattr_destroy(&recursiveAttr);
18059 #endif
18060 #if SQLITE_MUTEX_NREF
18061         p->id = iType;
18062 #endif
18063       }
18064       break;
18065     }
18066     case SQLITE_MUTEX_FAST: {
18067       p = sqlite3MallocZero( sizeof(*p) );
18068       if( p ){
18069 #if SQLITE_MUTEX_NREF
18070         p->id = iType;
18071 #endif
18072         pthread_mutex_init(&p->mutex, 0);
18073       }
18074       break;
18075     }
18076     default: {
18077       assert( iType-2 >= 0 );
18078       assert( iType-2 < ArraySize(staticMutexes) );
18079       p = &staticMutexes[iType-2];
18080 #if SQLITE_MUTEX_NREF
18081       p->id = iType;
18082 #endif
18083       break;
18084     }
18085   }
18086   return p;
18087 }
18088
18089
18090 /*
18091 ** This routine deallocates a previously
18092 ** allocated mutex.  SQLite is careful to deallocate every
18093 ** mutex that it allocates.
18094 */
18095 static void pthreadMutexFree(sqlite3_mutex *p){
18096   assert( p->nRef==0 );
18097   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18098   pthread_mutex_destroy(&p->mutex);
18099   sqlite3_free(p);
18100 }
18101
18102 /*
18103 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18104 ** to enter a mutex.  If another thread is already within the mutex,
18105 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18106 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18107 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18108 ** be entered multiple times by the same thread.  In such cases the,
18109 ** mutex must be exited an equal number of times before another thread
18110 ** can enter.  If the same thread tries to enter any other kind of mutex
18111 ** more than once, the behavior is undefined.
18112 */
18113 static void pthreadMutexEnter(sqlite3_mutex *p){
18114   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18115
18116 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18117   /* If recursive mutexes are not available, then we have to grow
18118   ** our own.  This implementation assumes that pthread_equal()
18119   ** is atomic - that it cannot be deceived into thinking self
18120   ** and p->owner are equal if p->owner changes between two values
18121   ** that are not equal to self while the comparison is taking place.
18122   ** This implementation also assumes a coherent cache - that 
18123   ** separate processes cannot read different values from the same
18124   ** address at the same time.  If either of these two conditions
18125   ** are not met, then the mutexes will fail and problems will result.
18126   */
18127   {
18128     pthread_t self = pthread_self();
18129     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18130       p->nRef++;
18131     }else{
18132       pthread_mutex_lock(&p->mutex);
18133       assert( p->nRef==0 );
18134       p->owner = self;
18135       p->nRef = 1;
18136     }
18137   }
18138 #else
18139   /* Use the built-in recursive mutexes if they are available.
18140   */
18141   pthread_mutex_lock(&p->mutex);
18142 #if SQLITE_MUTEX_NREF
18143   assert( p->nRef>0 || p->owner==0 );
18144   p->owner = pthread_self();
18145   p->nRef++;
18146 #endif
18147 #endif
18148
18149 #ifdef SQLITE_DEBUG
18150   if( p->trace ){
18151     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18152   }
18153 #endif
18154 }
18155 static int pthreadMutexTry(sqlite3_mutex *p){
18156   int rc;
18157   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18158
18159 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18160   /* If recursive mutexes are not available, then we have to grow
18161   ** our own.  This implementation assumes that pthread_equal()
18162   ** is atomic - that it cannot be deceived into thinking self
18163   ** and p->owner are equal if p->owner changes between two values
18164   ** that are not equal to self while the comparison is taking place.
18165   ** This implementation also assumes a coherent cache - that 
18166   ** separate processes cannot read different values from the same
18167   ** address at the same time.  If either of these two conditions
18168   ** are not met, then the mutexes will fail and problems will result.
18169   */
18170   {
18171     pthread_t self = pthread_self();
18172     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18173       p->nRef++;
18174       rc = SQLITE_OK;
18175     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18176       assert( p->nRef==0 );
18177       p->owner = self;
18178       p->nRef = 1;
18179       rc = SQLITE_OK;
18180     }else{
18181       rc = SQLITE_BUSY;
18182     }
18183   }
18184 #else
18185   /* Use the built-in recursive mutexes if they are available.
18186   */
18187   if( pthread_mutex_trylock(&p->mutex)==0 ){
18188 #if SQLITE_MUTEX_NREF
18189     p->owner = pthread_self();
18190     p->nRef++;
18191 #endif
18192     rc = SQLITE_OK;
18193   }else{
18194     rc = SQLITE_BUSY;
18195   }
18196 #endif
18197
18198 #ifdef SQLITE_DEBUG
18199   if( rc==SQLITE_OK && p->trace ){
18200     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18201   }
18202 #endif
18203   return rc;
18204 }
18205
18206 /*
18207 ** The sqlite3_mutex_leave() routine exits a mutex that was
18208 ** previously entered by the same thread.  The behavior
18209 ** is undefined if the mutex is not currently entered or
18210 ** is not currently allocated.  SQLite will never do either.
18211 */
18212 static void pthreadMutexLeave(sqlite3_mutex *p){
18213   assert( pthreadMutexHeld(p) );
18214 #if SQLITE_MUTEX_NREF
18215   p->nRef--;
18216   if( p->nRef==0 ) p->owner = 0;
18217 #endif
18218   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18219
18220 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18221   if( p->nRef==0 ){
18222     pthread_mutex_unlock(&p->mutex);
18223   }
18224 #else
18225   pthread_mutex_unlock(&p->mutex);
18226 #endif
18227
18228 #ifdef SQLITE_DEBUG
18229   if( p->trace ){
18230     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18231   }
18232 #endif
18233 }
18234
18235 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18236   static const sqlite3_mutex_methods sMutex = {
18237     pthreadMutexInit,
18238     pthreadMutexEnd,
18239     pthreadMutexAlloc,
18240     pthreadMutexFree,
18241     pthreadMutexEnter,
18242     pthreadMutexTry,
18243     pthreadMutexLeave,
18244 #ifdef SQLITE_DEBUG
18245     pthreadMutexHeld,
18246     pthreadMutexNotheld
18247 #else
18248     0,
18249     0
18250 #endif
18251   };
18252
18253   return &sMutex;
18254 }
18255
18256 #endif /* SQLITE_MUTEX_PTHREADS */
18257
18258 /************** End of mutex_unix.c ******************************************/
18259 /************** Begin file mutex_w32.c ***************************************/
18260 /*
18261 ** 2007 August 14
18262 **
18263 ** The author disclaims copyright to this source code.  In place of
18264 ** a legal notice, here is a blessing:
18265 **
18266 **    May you do good and not evil.
18267 **    May you find forgiveness for yourself and forgive others.
18268 **    May you share freely, never taking more than you give.
18269 **
18270 *************************************************************************
18271 ** This file contains the C functions that implement mutexes for win32
18272 */
18273
18274 /*
18275 ** The code in this file is only used if we are compiling multithreaded
18276 ** on a win32 system.
18277 */
18278 #ifdef SQLITE_MUTEX_W32
18279
18280 /*
18281 ** Each recursive mutex is an instance of the following structure.
18282 */
18283 struct sqlite3_mutex {
18284   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
18285   int id;                    /* Mutex type */
18286 #ifdef SQLITE_DEBUG
18287   volatile int nRef;         /* Number of enterances */
18288   volatile DWORD owner;      /* Thread holding this mutex */
18289   int trace;                 /* True to trace changes */
18290 #endif
18291 };
18292 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
18293 #ifdef SQLITE_DEBUG
18294 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
18295 #else
18296 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
18297 #endif
18298
18299 /*
18300 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18301 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
18302 **
18303 ** Here is an interesting observation:  Win95, Win98, and WinME lack
18304 ** the LockFileEx() API.  But we can still statically link against that
18305 ** API as long as we don't call it win running Win95/98/ME.  A call to
18306 ** this routine is used to determine if the host is Win95/98/ME or
18307 ** WinNT/2K/XP so that we will know whether or not we can safely call
18308 ** the LockFileEx() API.
18309 **
18310 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
18311 ** which is only available if your application was compiled with 
18312 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
18313 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
18314 ** this out as well.
18315 */
18316 #if 0
18317 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
18318 # define mutexIsNT()  (1)
18319 #else
18320   static int mutexIsNT(void){
18321     static int osType = 0;
18322     if( osType==0 ){
18323       OSVERSIONINFO sInfo;
18324       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18325       GetVersionEx(&sInfo);
18326       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18327     }
18328     return osType==2;
18329   }
18330 #endif /* SQLITE_OS_WINCE */
18331 #endif
18332
18333 #ifdef SQLITE_DEBUG
18334 /*
18335 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18336 ** intended for use only inside assert() statements.
18337 */
18338 static int winMutexHeld(sqlite3_mutex *p){
18339   return p->nRef!=0 && p->owner==GetCurrentThreadId();
18340 }
18341 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
18342   return p->nRef==0 || p->owner!=tid;
18343 }
18344 static int winMutexNotheld(sqlite3_mutex *p){
18345   DWORD tid = GetCurrentThreadId(); 
18346   return winMutexNotheld2(p, tid);
18347 }
18348 #endif
18349
18350
18351 /*
18352 ** Initialize and deinitialize the mutex subsystem.
18353 */
18354 static sqlite3_mutex winMutex_staticMutexes[6] = {
18355   SQLITE3_MUTEX_INITIALIZER,
18356   SQLITE3_MUTEX_INITIALIZER,
18357   SQLITE3_MUTEX_INITIALIZER,
18358   SQLITE3_MUTEX_INITIALIZER,
18359   SQLITE3_MUTEX_INITIALIZER,
18360   SQLITE3_MUTEX_INITIALIZER
18361 };
18362 static int winMutex_isInit = 0;
18363 /* As winMutexInit() and winMutexEnd() are called as part
18364 ** of the sqlite3_initialize and sqlite3_shutdown()
18365 ** processing, the "interlocked" magic is probably not
18366 ** strictly necessary.
18367 */
18368 static long winMutex_lock = 0;
18369
18370 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
18371
18372 static int winMutexInit(void){ 
18373   /* The first to increment to 1 does actual initialization */
18374   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
18375     int i;
18376     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18377 #if SQLITE_OS_WINRT
18378       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
18379 #else
18380       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
18381 #endif
18382     }
18383     winMutex_isInit = 1;
18384   }else{
18385     /* Someone else is in the process of initing the static mutexes */
18386     while( !winMutex_isInit ){
18387       sqlite3_win32_sleep(1);
18388     }
18389   }
18390   return SQLITE_OK; 
18391 }
18392
18393 static int winMutexEnd(void){ 
18394   /* The first to decrement to 0 does actual shutdown 
18395   ** (which should be the last to shutdown.) */
18396   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
18397     if( winMutex_isInit==1 ){
18398       int i;
18399       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18400         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
18401       }
18402       winMutex_isInit = 0;
18403     }
18404   }
18405   return SQLITE_OK; 
18406 }
18407
18408 /*
18409 ** The sqlite3_mutex_alloc() routine allocates a new
18410 ** mutex and returns a pointer to it.  If it returns NULL
18411 ** that means that a mutex could not be allocated.  SQLite
18412 ** will unwind its stack and return an error.  The argument
18413 ** to sqlite3_mutex_alloc() is one of these integer constants:
18414 **
18415 ** <ul>
18416 ** <li>  SQLITE_MUTEX_FAST
18417 ** <li>  SQLITE_MUTEX_RECURSIVE
18418 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18419 ** <li>  SQLITE_MUTEX_STATIC_MEM
18420 ** <li>  SQLITE_MUTEX_STATIC_MEM2
18421 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18422 ** <li>  SQLITE_MUTEX_STATIC_LRU
18423 ** <li>  SQLITE_MUTEX_STATIC_PMEM
18424 ** </ul>
18425 **
18426 ** The first two constants cause sqlite3_mutex_alloc() to create
18427 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18428 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18429 ** The mutex implementation does not need to make a distinction
18430 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18431 ** not want to.  But SQLite will only request a recursive mutex in
18432 ** cases where it really needs one.  If a faster non-recursive mutex
18433 ** implementation is available on the host platform, the mutex subsystem
18434 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18435 **
18436 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18437 ** a pointer to a static preexisting mutex.  Six static mutexes are
18438 ** used by the current version of SQLite.  Future versions of SQLite
18439 ** may add additional static mutexes.  Static mutexes are for internal
18440 ** use by SQLite only.  Applications that use SQLite mutexes should
18441 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18442 ** SQLITE_MUTEX_RECURSIVE.
18443 **
18444 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18445 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18446 ** returns a different mutex on every call.  But for the static 
18447 ** mutex types, the same mutex is returned on every call that has
18448 ** the same type number.
18449 */
18450 static sqlite3_mutex *winMutexAlloc(int iType){
18451   sqlite3_mutex *p;
18452
18453   switch( iType ){
18454     case SQLITE_MUTEX_FAST:
18455     case SQLITE_MUTEX_RECURSIVE: {
18456       p = sqlite3MallocZero( sizeof(*p) );
18457       if( p ){  
18458 #ifdef SQLITE_DEBUG
18459         p->id = iType;
18460 #endif
18461 #if SQLITE_OS_WINRT
18462         InitializeCriticalSectionEx(&p->mutex, 0, 0);
18463 #else
18464         InitializeCriticalSection(&p->mutex);
18465 #endif
18466       }
18467       break;
18468     }
18469     default: {
18470       assert( winMutex_isInit==1 );
18471       assert( iType-2 >= 0 );
18472       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
18473       p = &winMutex_staticMutexes[iType-2];
18474 #ifdef SQLITE_DEBUG
18475       p->id = iType;
18476 #endif
18477       break;
18478     }
18479   }
18480   return p;
18481 }
18482
18483
18484 /*
18485 ** This routine deallocates a previously
18486 ** allocated mutex.  SQLite is careful to deallocate every
18487 ** mutex that it allocates.
18488 */
18489 static void winMutexFree(sqlite3_mutex *p){
18490   assert( p );
18491   assert( p->nRef==0 && p->owner==0 );
18492   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18493   DeleteCriticalSection(&p->mutex);
18494   sqlite3_free(p);
18495 }
18496
18497 /*
18498 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18499 ** to enter a mutex.  If another thread is already within the mutex,
18500 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18501 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18502 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18503 ** be entered multiple times by the same thread.  In such cases the,
18504 ** mutex must be exited an equal number of times before another thread
18505 ** can enter.  If the same thread tries to enter any other kind of mutex
18506 ** more than once, the behavior is undefined.
18507 */
18508 static void winMutexEnter(sqlite3_mutex *p){
18509 #ifdef SQLITE_DEBUG
18510   DWORD tid = GetCurrentThreadId(); 
18511   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18512 #endif
18513   EnterCriticalSection(&p->mutex);
18514 #ifdef SQLITE_DEBUG
18515   assert( p->nRef>0 || p->owner==0 );
18516   p->owner = tid; 
18517   p->nRef++;
18518   if( p->trace ){
18519     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18520   }
18521 #endif
18522 }
18523 static int winMutexTry(sqlite3_mutex *p){
18524 #ifndef NDEBUG
18525   DWORD tid = GetCurrentThreadId(); 
18526 #endif
18527   int rc = SQLITE_BUSY;
18528   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18529   /*
18530   ** The sqlite3_mutex_try() routine is very rarely used, and when it
18531   ** is used it is merely an optimization.  So it is OK for it to always
18532   ** fail.  
18533   **
18534   ** The TryEnterCriticalSection() interface is only available on WinNT.
18535   ** And some windows compilers complain if you try to use it without
18536   ** first doing some #defines that prevent SQLite from building on Win98.
18537   ** For that reason, we will omit this optimization for now.  See
18538   ** ticket #2685.
18539   */
18540 #if 0
18541   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18542     p->owner = tid;
18543     p->nRef++;
18544     rc = SQLITE_OK;
18545   }
18546 #else
18547   UNUSED_PARAMETER(p);
18548 #endif
18549 #ifdef SQLITE_DEBUG
18550   if( rc==SQLITE_OK && p->trace ){
18551     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18552   }
18553 #endif
18554   return rc;
18555 }
18556
18557 /*
18558 ** The sqlite3_mutex_leave() routine exits a mutex that was
18559 ** previously entered by the same thread.  The behavior
18560 ** is undefined if the mutex is not currently entered or
18561 ** is not currently allocated.  SQLite will never do either.
18562 */
18563 static void winMutexLeave(sqlite3_mutex *p){
18564 #ifndef NDEBUG
18565   DWORD tid = GetCurrentThreadId();
18566   assert( p->nRef>0 );
18567   assert( p->owner==tid );
18568   p->nRef--;
18569   if( p->nRef==0 ) p->owner = 0;
18570   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18571 #endif
18572   LeaveCriticalSection(&p->mutex);
18573 #ifdef SQLITE_DEBUG
18574   if( p->trace ){
18575     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18576   }
18577 #endif
18578 }
18579
18580 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18581   static const sqlite3_mutex_methods sMutex = {
18582     winMutexInit,
18583     winMutexEnd,
18584     winMutexAlloc,
18585     winMutexFree,
18586     winMutexEnter,
18587     winMutexTry,
18588     winMutexLeave,
18589 #ifdef SQLITE_DEBUG
18590     winMutexHeld,
18591     winMutexNotheld
18592 #else
18593     0,
18594     0
18595 #endif
18596   };
18597
18598   return &sMutex;
18599 }
18600 #endif /* SQLITE_MUTEX_W32 */
18601
18602 /************** End of mutex_w32.c *******************************************/
18603 /************** Begin file malloc.c ******************************************/
18604 /*
18605 ** 2001 September 15
18606 **
18607 ** The author disclaims copyright to this source code.  In place of
18608 ** a legal notice, here is a blessing:
18609 **
18610 **    May you do good and not evil.
18611 **    May you find forgiveness for yourself and forgive others.
18612 **    May you share freely, never taking more than you give.
18613 **
18614 *************************************************************************
18615 **
18616 ** Memory allocation functions used throughout sqlite.
18617 */
18618 /* #include <stdarg.h> */
18619
18620 /*
18621 ** Attempt to release up to n bytes of non-essential memory currently
18622 ** held by SQLite. An example of non-essential memory is memory used to
18623 ** cache database pages that are not currently in use.
18624 */
18625 SQLITE_API int sqlite3_release_memory(int n){
18626 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18627   return sqlite3PcacheReleaseMemory(n);
18628 #else
18629   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18630   ** is a no-op returning zero if SQLite is not compiled with
18631   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18632   UNUSED_PARAMETER(n);
18633   return 0;
18634 #endif
18635 }
18636
18637 /*
18638 ** An instance of the following object records the location of
18639 ** each unused scratch buffer.
18640 */
18641 typedef struct ScratchFreeslot {
18642   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
18643 } ScratchFreeslot;
18644
18645 /*
18646 ** State information local to the memory allocation subsystem.
18647 */
18648 static SQLITE_WSD struct Mem0Global {
18649   sqlite3_mutex *mutex;         /* Mutex to serialize access */
18650
18651   /*
18652   ** The alarm callback and its arguments.  The mem0.mutex lock will
18653   ** be held while the callback is running.  Recursive calls into
18654   ** the memory subsystem are allowed, but no new callbacks will be
18655   ** issued.
18656   */
18657   sqlite3_int64 alarmThreshold;
18658   void (*alarmCallback)(void*, sqlite3_int64,int);
18659   void *alarmArg;
18660
18661   /*
18662   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18663   ** (so that a range test can be used to determine if an allocation
18664   ** being freed came from pScratch) and a pointer to the list of
18665   ** unused scratch allocations.
18666   */
18667   void *pScratchEnd;
18668   ScratchFreeslot *pScratchFree;
18669   u32 nScratchFree;
18670
18671   /*
18672   ** True if heap is nearly "full" where "full" is defined by the
18673   ** sqlite3_soft_heap_limit() setting.
18674   */
18675   int nearlyFull;
18676 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18677
18678 #define mem0 GLOBAL(struct Mem0Global, mem0)
18679
18680 /*
18681 ** This routine runs when the memory allocator sees that the
18682 ** total memory allocation is about to exceed the soft heap
18683 ** limit.
18684 */
18685 static void softHeapLimitEnforcer(
18686   void *NotUsed, 
18687   sqlite3_int64 NotUsed2,
18688   int allocSize
18689 ){
18690   UNUSED_PARAMETER2(NotUsed, NotUsed2);
18691   sqlite3_release_memory(allocSize);
18692 }
18693
18694 /*
18695 ** Change the alarm callback
18696 */
18697 static int sqlite3MemoryAlarm(
18698   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18699   void *pArg,
18700   sqlite3_int64 iThreshold
18701 ){
18702   int nUsed;
18703   sqlite3_mutex_enter(mem0.mutex);
18704   mem0.alarmCallback = xCallback;
18705   mem0.alarmArg = pArg;
18706   mem0.alarmThreshold = iThreshold;
18707   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18708   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18709   sqlite3_mutex_leave(mem0.mutex);
18710   return SQLITE_OK;
18711 }
18712
18713 #ifndef SQLITE_OMIT_DEPRECATED
18714 /*
18715 ** Deprecated external interface.  Internal/core SQLite code
18716 ** should call sqlite3MemoryAlarm.
18717 */
18718 SQLITE_API int sqlite3_memory_alarm(
18719   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18720   void *pArg,
18721   sqlite3_int64 iThreshold
18722 ){
18723   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18724 }
18725 #endif
18726
18727 /*
18728 ** Set the soft heap-size limit for the library. Passing a zero or 
18729 ** negative value indicates no limit.
18730 */
18731 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18732   sqlite3_int64 priorLimit;
18733   sqlite3_int64 excess;
18734 #ifndef SQLITE_OMIT_AUTOINIT
18735   int rc = sqlite3_initialize();
18736   if( rc ) return -1;
18737 #endif
18738   sqlite3_mutex_enter(mem0.mutex);
18739   priorLimit = mem0.alarmThreshold;
18740   sqlite3_mutex_leave(mem0.mutex);
18741   if( n<0 ) return priorLimit;
18742   if( n>0 ){
18743     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18744   }else{
18745     sqlite3MemoryAlarm(0, 0, 0);
18746   }
18747   excess = sqlite3_memory_used() - n;
18748   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18749   return priorLimit;
18750 }
18751 SQLITE_API void sqlite3_soft_heap_limit(int n){
18752   if( n<0 ) n = 0;
18753   sqlite3_soft_heap_limit64(n);
18754 }
18755
18756 /*
18757 ** Initialize the memory allocation subsystem.
18758 */
18759 SQLITE_PRIVATE int sqlite3MallocInit(void){
18760   if( sqlite3GlobalConfig.m.xMalloc==0 ){
18761     sqlite3MemSetDefault();
18762   }
18763   memset(&mem0, 0, sizeof(mem0));
18764   if( sqlite3GlobalConfig.bCoreMutex ){
18765     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18766   }
18767   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18768       && sqlite3GlobalConfig.nScratch>0 ){
18769     int i, n, sz;
18770     ScratchFreeslot *pSlot;
18771     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18772     sqlite3GlobalConfig.szScratch = sz;
18773     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18774     n = sqlite3GlobalConfig.nScratch;
18775     mem0.pScratchFree = pSlot;
18776     mem0.nScratchFree = n;
18777     for(i=0; i<n-1; i++){
18778       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18779       pSlot = pSlot->pNext;
18780     }
18781     pSlot->pNext = 0;
18782     mem0.pScratchEnd = (void*)&pSlot[1];
18783   }else{
18784     mem0.pScratchEnd = 0;
18785     sqlite3GlobalConfig.pScratch = 0;
18786     sqlite3GlobalConfig.szScratch = 0;
18787     sqlite3GlobalConfig.nScratch = 0;
18788   }
18789   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18790       || sqlite3GlobalConfig.nPage<1 ){
18791     sqlite3GlobalConfig.pPage = 0;
18792     sqlite3GlobalConfig.szPage = 0;
18793     sqlite3GlobalConfig.nPage = 0;
18794   }
18795   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18796 }
18797
18798 /*
18799 ** Return true if the heap is currently under memory pressure - in other
18800 ** words if the amount of heap used is close to the limit set by
18801 ** sqlite3_soft_heap_limit().
18802 */
18803 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18804   return mem0.nearlyFull;
18805 }
18806
18807 /*
18808 ** Deinitialize the memory allocation subsystem.
18809 */
18810 SQLITE_PRIVATE void sqlite3MallocEnd(void){
18811   if( sqlite3GlobalConfig.m.xShutdown ){
18812     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18813   }
18814   memset(&mem0, 0, sizeof(mem0));
18815 }
18816
18817 /*
18818 ** Return the amount of memory currently checked out.
18819 */
18820 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18821   int n, mx;
18822   sqlite3_int64 res;
18823   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18824   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
18825   return res;
18826 }
18827
18828 /*
18829 ** Return the maximum amount of memory that has ever been
18830 ** checked out since either the beginning of this process
18831 ** or since the most recent reset.
18832 */
18833 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18834   int n, mx;
18835   sqlite3_int64 res;
18836   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
18837   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
18838   return res;
18839 }
18840
18841 /*
18842 ** Trigger the alarm 
18843 */
18844 static void sqlite3MallocAlarm(int nByte){
18845   void (*xCallback)(void*,sqlite3_int64,int);
18846   sqlite3_int64 nowUsed;
18847   void *pArg;
18848   if( mem0.alarmCallback==0 ) return;
18849   xCallback = mem0.alarmCallback;
18850   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18851   pArg = mem0.alarmArg;
18852   mem0.alarmCallback = 0;
18853   sqlite3_mutex_leave(mem0.mutex);
18854   xCallback(pArg, nowUsed, nByte);
18855   sqlite3_mutex_enter(mem0.mutex);
18856   mem0.alarmCallback = xCallback;
18857   mem0.alarmArg = pArg;
18858 }
18859
18860 /*
18861 ** Do a memory allocation with statistics and alarms.  Assume the
18862 ** lock is already held.
18863 */
18864 static int mallocWithAlarm(int n, void **pp){
18865   int nFull;
18866   void *p;
18867   assert( sqlite3_mutex_held(mem0.mutex) );
18868   nFull = sqlite3GlobalConfig.m.xRoundup(n);
18869   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
18870   if( mem0.alarmCallback!=0 ){
18871     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18872     if( nUsed >= mem0.alarmThreshold - nFull ){
18873       mem0.nearlyFull = 1;
18874       sqlite3MallocAlarm(nFull);
18875     }else{
18876       mem0.nearlyFull = 0;
18877     }
18878   }
18879   p = sqlite3GlobalConfig.m.xMalloc(nFull);
18880 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18881   if( p==0 && mem0.alarmCallback ){
18882     sqlite3MallocAlarm(nFull);
18883     p = sqlite3GlobalConfig.m.xMalloc(nFull);
18884   }
18885 #endif
18886   if( p ){
18887     nFull = sqlite3MallocSize(p);
18888     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
18889     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
18890   }
18891   *pp = p;
18892   return nFull;
18893 }
18894
18895 /*
18896 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
18897 ** assumes the memory subsystem has already been initialized.
18898 */
18899 SQLITE_PRIVATE void *sqlite3Malloc(int n){
18900   void *p;
18901   if( n<=0               /* IMP: R-65312-04917 */ 
18902    || n>=0x7fffff00
18903   ){
18904     /* A memory allocation of a number of bytes which is near the maximum
18905     ** signed integer value might cause an integer overflow inside of the
18906     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
18907     ** 255 bytes of overhead.  SQLite itself will never use anything near
18908     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
18909     p = 0;
18910   }else if( sqlite3GlobalConfig.bMemstat ){
18911     sqlite3_mutex_enter(mem0.mutex);
18912     mallocWithAlarm(n, &p);
18913     sqlite3_mutex_leave(mem0.mutex);
18914   }else{
18915     p = sqlite3GlobalConfig.m.xMalloc(n);
18916   }
18917   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
18918   return p;
18919 }
18920
18921 /*
18922 ** This version of the memory allocation is for use by the application.
18923 ** First make sure the memory subsystem is initialized, then do the
18924 ** allocation.
18925 */
18926 SQLITE_API void *sqlite3_malloc(int n){
18927 #ifndef SQLITE_OMIT_AUTOINIT
18928   if( sqlite3_initialize() ) return 0;
18929 #endif
18930   return sqlite3Malloc(n);
18931 }
18932
18933 /*
18934 ** Each thread may only have a single outstanding allocation from
18935 ** xScratchMalloc().  We verify this constraint in the single-threaded
18936 ** case by setting scratchAllocOut to 1 when an allocation
18937 ** is outstanding clearing it when the allocation is freed.
18938 */
18939 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18940 static int scratchAllocOut = 0;
18941 #endif
18942
18943
18944 /*
18945 ** Allocate memory that is to be used and released right away.
18946 ** This routine is similar to alloca() in that it is not intended
18947 ** for situations where the memory might be held long-term.  This
18948 ** routine is intended to get memory to old large transient data
18949 ** structures that would not normally fit on the stack of an
18950 ** embedded processor.
18951 */
18952 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18953   void *p;
18954   assert( n>0 );
18955
18956   sqlite3_mutex_enter(mem0.mutex);
18957   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18958     p = mem0.pScratchFree;
18959     mem0.pScratchFree = mem0.pScratchFree->pNext;
18960     mem0.nScratchFree--;
18961     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18962     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18963     sqlite3_mutex_leave(mem0.mutex);
18964   }else{
18965     if( sqlite3GlobalConfig.bMemstat ){
18966       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18967       n = mallocWithAlarm(n, &p);
18968       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18969       sqlite3_mutex_leave(mem0.mutex);
18970     }else{
18971       sqlite3_mutex_leave(mem0.mutex);
18972       p = sqlite3GlobalConfig.m.xMalloc(n);
18973     }
18974     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18975   }
18976   assert( sqlite3_mutex_notheld(mem0.mutex) );
18977
18978
18979 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18980   /* Verify that no more than two scratch allocations per thread
18981   ** are outstanding at one time.  (This is only checked in the
18982   ** single-threaded case since checking in the multi-threaded case
18983   ** would be much more complicated.) */
18984   assert( scratchAllocOut<=1 );
18985   if( p ) scratchAllocOut++;
18986 #endif
18987
18988   return p;
18989 }
18990 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18991   if( p ){
18992
18993 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18994     /* Verify that no more than two scratch allocation per thread
18995     ** is outstanding at one time.  (This is only checked in the
18996     ** single-threaded case since checking in the multi-threaded case
18997     ** would be much more complicated.) */
18998     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18999     scratchAllocOut--;
19000 #endif
19001
19002     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
19003       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
19004       ScratchFreeslot *pSlot;
19005       pSlot = (ScratchFreeslot*)p;
19006       sqlite3_mutex_enter(mem0.mutex);
19007       pSlot->pNext = mem0.pScratchFree;
19008       mem0.pScratchFree = pSlot;
19009       mem0.nScratchFree++;
19010       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
19011       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
19012       sqlite3_mutex_leave(mem0.mutex);
19013     }else{
19014       /* Release memory back to the heap */
19015       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
19016       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
19017       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19018       if( sqlite3GlobalConfig.bMemstat ){
19019         int iSize = sqlite3MallocSize(p);
19020         sqlite3_mutex_enter(mem0.mutex);
19021         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
19022         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
19023         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19024         sqlite3GlobalConfig.m.xFree(p);
19025         sqlite3_mutex_leave(mem0.mutex);
19026       }else{
19027         sqlite3GlobalConfig.m.xFree(p);
19028       }
19029     }
19030   }
19031 }
19032
19033 /*
19034 ** TRUE if p is a lookaside memory allocation from db
19035 */
19036 #ifndef SQLITE_OMIT_LOOKASIDE
19037 static int isLookaside(sqlite3 *db, void *p){
19038   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
19039 }
19040 #else
19041 #define isLookaside(A,B) 0
19042 #endif
19043
19044 /*
19045 ** Return the size of a memory allocation previously obtained from
19046 ** sqlite3Malloc() or sqlite3_malloc().
19047 */
19048 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
19049   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19050   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19051   return sqlite3GlobalConfig.m.xSize(p);
19052 }
19053 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
19054   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19055   if( db && isLookaside(db, p) ){
19056     return db->lookaside.sz;
19057   }else{
19058     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19059     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19060     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19061     return sqlite3GlobalConfig.m.xSize(p);
19062   }
19063 }
19064
19065 /*
19066 ** Free memory previously obtained from sqlite3Malloc().
19067 */
19068 SQLITE_API void sqlite3_free(void *p){
19069   if( p==0 ) return;  /* IMP: R-49053-54554 */
19070   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19071   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19072   if( sqlite3GlobalConfig.bMemstat ){
19073     sqlite3_mutex_enter(mem0.mutex);
19074     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
19075     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19076     sqlite3GlobalConfig.m.xFree(p);
19077     sqlite3_mutex_leave(mem0.mutex);
19078   }else{
19079     sqlite3GlobalConfig.m.xFree(p);
19080   }
19081 }
19082
19083 /*
19084 ** Free memory that might be associated with a particular database
19085 ** connection.
19086 */
19087 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
19088   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19089   if( db ){
19090     if( db->pnBytesFreed ){
19091       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
19092       return;
19093     }
19094     if( isLookaside(db, p) ){
19095       LookasideSlot *pBuf = (LookasideSlot*)p;
19096 #if SQLITE_DEBUG
19097       /* Trash all content in the buffer being freed */
19098       memset(p, 0xaa, db->lookaside.sz);
19099 #endif
19100       pBuf->pNext = db->lookaside.pFree;
19101       db->lookaside.pFree = pBuf;
19102       db->lookaside.nOut--;
19103       return;
19104     }
19105   }
19106   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19107   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19108   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19109   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19110   sqlite3_free(p);
19111 }
19112
19113 /*
19114 ** Change the size of an existing memory allocation
19115 */
19116 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
19117   int nOld, nNew, nDiff;
19118   void *pNew;
19119   if( pOld==0 ){
19120     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
19121   }
19122   if( nBytes<=0 ){
19123     sqlite3_free(pOld); /* IMP: R-31593-10574 */
19124     return 0;
19125   }
19126   if( nBytes>=0x7fffff00 ){
19127     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
19128     return 0;
19129   }
19130   nOld = sqlite3MallocSize(pOld);
19131   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
19132   ** argument to xRealloc is always a value returned by a prior call to
19133   ** xRoundup. */
19134   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
19135   if( nOld==nNew ){
19136     pNew = pOld;
19137   }else if( sqlite3GlobalConfig.bMemstat ){
19138     sqlite3_mutex_enter(mem0.mutex);
19139     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
19140     nDiff = nNew - nOld;
19141     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 
19142           mem0.alarmThreshold-nDiff ){
19143       sqlite3MallocAlarm(nDiff);
19144     }
19145     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19146     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
19147     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19148     if( pNew==0 && mem0.alarmCallback ){
19149       sqlite3MallocAlarm(nBytes);
19150       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19151     }
19152     if( pNew ){
19153       nNew = sqlite3MallocSize(pNew);
19154       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
19155     }
19156     sqlite3_mutex_leave(mem0.mutex);
19157   }else{
19158     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19159   }
19160   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
19161   return pNew;
19162 }
19163
19164 /*
19165 ** The public interface to sqlite3Realloc.  Make sure that the memory
19166 ** subsystem is initialized prior to invoking sqliteRealloc.
19167 */
19168 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
19169 #ifndef SQLITE_OMIT_AUTOINIT
19170   if( sqlite3_initialize() ) return 0;
19171 #endif
19172   return sqlite3Realloc(pOld, n);
19173 }
19174
19175
19176 /*
19177 ** Allocate and zero memory.
19178 */ 
19179 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
19180   void *p = sqlite3Malloc(n);
19181   if( p ){
19182     memset(p, 0, n);
19183   }
19184   return p;
19185 }
19186
19187 /*
19188 ** Allocate and zero memory.  If the allocation fails, make
19189 ** the mallocFailed flag in the connection pointer.
19190 */
19191 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
19192   void *p = sqlite3DbMallocRaw(db, n);
19193   if( p ){
19194     memset(p, 0, n);
19195   }
19196   return p;
19197 }
19198
19199 /*
19200 ** Allocate and zero memory.  If the allocation fails, make
19201 ** the mallocFailed flag in the connection pointer.
19202 **
19203 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
19204 ** failure on the same database connection) then always return 0.
19205 ** Hence for a particular database connection, once malloc starts
19206 ** failing, it fails consistently until mallocFailed is reset.
19207 ** This is an important assumption.  There are many places in the
19208 ** code that do things like this:
19209 **
19210 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
19211 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
19212 **         if( b ) a[10] = 9;
19213 **
19214 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
19215 ** that all prior mallocs (ex: "a") worked too.
19216 */
19217 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
19218   void *p;
19219   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19220   assert( db==0 || db->pnBytesFreed==0 );
19221 #ifndef SQLITE_OMIT_LOOKASIDE
19222   if( db ){
19223     LookasideSlot *pBuf;
19224     if( db->mallocFailed ){
19225       return 0;
19226     }
19227     if( db->lookaside.bEnabled ){
19228       if( n>db->lookaside.sz ){
19229         db->lookaside.anStat[1]++;
19230       }else if( (pBuf = db->lookaside.pFree)==0 ){
19231         db->lookaside.anStat[2]++;
19232       }else{
19233         db->lookaside.pFree = pBuf->pNext;
19234         db->lookaside.nOut++;
19235         db->lookaside.anStat[0]++;
19236         if( db->lookaside.nOut>db->lookaside.mxOut ){
19237           db->lookaside.mxOut = db->lookaside.nOut;
19238         }
19239         return (void*)pBuf;
19240       }
19241     }
19242   }
19243 #else
19244   if( db && db->mallocFailed ){
19245     return 0;
19246   }
19247 #endif
19248   p = sqlite3Malloc(n);
19249   if( !p && db ){
19250     db->mallocFailed = 1;
19251   }
19252   sqlite3MemdebugSetType(p, MEMTYPE_DB |
19253          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19254   return p;
19255 }
19256
19257 /*
19258 ** Resize the block of memory pointed to by p to n bytes. If the
19259 ** resize fails, set the mallocFailed flag in the connection object.
19260 */
19261 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
19262   void *pNew = 0;
19263   assert( db!=0 );
19264   assert( sqlite3_mutex_held(db->mutex) );
19265   if( db->mallocFailed==0 ){
19266     if( p==0 ){
19267       return sqlite3DbMallocRaw(db, n);
19268     }
19269     if( isLookaside(db, p) ){
19270       if( n<=db->lookaside.sz ){
19271         return p;
19272       }
19273       pNew = sqlite3DbMallocRaw(db, n);
19274       if( pNew ){
19275         memcpy(pNew, p, db->lookaside.sz);
19276         sqlite3DbFree(db, p);
19277       }
19278     }else{
19279       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19280       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19281       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19282       pNew = sqlite3_realloc(p, n);
19283       if( !pNew ){
19284         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
19285         db->mallocFailed = 1;
19286       }
19287       sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
19288             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19289     }
19290   }
19291   return pNew;
19292 }
19293
19294 /*
19295 ** Attempt to reallocate p.  If the reallocation fails, then free p
19296 ** and set the mallocFailed flag in the database connection.
19297 */
19298 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
19299   void *pNew;
19300   pNew = sqlite3DbRealloc(db, p, n);
19301   if( !pNew ){
19302     sqlite3DbFree(db, p);
19303   }
19304   return pNew;
19305 }
19306
19307 /*
19308 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
19309 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
19310 ** is because when memory debugging is turned on, these two functions are 
19311 ** called via macros that record the current file and line number in the
19312 ** ThreadData structure.
19313 */
19314 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
19315   char *zNew;
19316   size_t n;
19317   if( z==0 ){
19318     return 0;
19319   }
19320   n = sqlite3Strlen30(z) + 1;
19321   assert( (n&0x7fffffff)==n );
19322   zNew = sqlite3DbMallocRaw(db, (int)n);
19323   if( zNew ){
19324     memcpy(zNew, z, n);
19325   }
19326   return zNew;
19327 }
19328 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
19329   char *zNew;
19330   if( z==0 ){
19331     return 0;
19332   }
19333   assert( (n&0x7fffffff)==n );
19334   zNew = sqlite3DbMallocRaw(db, n+1);
19335   if( zNew ){
19336     memcpy(zNew, z, n);
19337     zNew[n] = 0;
19338   }
19339   return zNew;
19340 }
19341
19342 /*
19343 ** Create a string from the zFromat argument and the va_list that follows.
19344 ** Store the string in memory obtained from sqliteMalloc() and make *pz
19345 ** point to that string.
19346 */
19347 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
19348   va_list ap;
19349   char *z;
19350
19351   va_start(ap, zFormat);
19352   z = sqlite3VMPrintf(db, zFormat, ap);
19353   va_end(ap);
19354   sqlite3DbFree(db, *pz);
19355   *pz = z;
19356 }
19357
19358
19359 /*
19360 ** This function must be called before exiting any API function (i.e. 
19361 ** returning control to the user) that has called sqlite3_malloc or
19362 ** sqlite3_realloc.
19363 **
19364 ** The returned value is normally a copy of the second argument to this
19365 ** function. However, if a malloc() failure has occurred since the previous
19366 ** invocation SQLITE_NOMEM is returned instead. 
19367 **
19368 ** If the first argument, db, is not NULL and a malloc() error has occurred,
19369 ** then the connection error-code (the value returned by sqlite3_errcode())
19370 ** is set to SQLITE_NOMEM.
19371 */
19372 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
19373   /* If the db handle is not NULL, then we must hold the connection handle
19374   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
19375   ** is unsafe, as is the call to sqlite3Error().
19376   */
19377   assert( !db || sqlite3_mutex_held(db->mutex) );
19378   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
19379     sqlite3Error(db, SQLITE_NOMEM, 0);
19380     db->mallocFailed = 0;
19381     rc = SQLITE_NOMEM;
19382   }
19383   return rc & (db ? db->errMask : 0xff);
19384 }
19385
19386 /************** End of malloc.c **********************************************/
19387 /************** Begin file printf.c ******************************************/
19388 /*
19389 ** The "printf" code that follows dates from the 1980's.  It is in
19390 ** the public domain.  The original comments are included here for
19391 ** completeness.  They are very out-of-date but might be useful as
19392 ** an historical reference.  Most of the "enhancements" have been backed
19393 ** out so that the functionality is now the same as standard printf().
19394 **
19395 **************************************************************************
19396 **
19397 ** This file contains code for a set of "printf"-like routines.  These
19398 ** routines format strings much like the printf() from the standard C
19399 ** library, though the implementation here has enhancements to support
19400 ** SQLlite.
19401 */
19402
19403 /*
19404 ** Conversion types fall into various categories as defined by the
19405 ** following enumeration.
19406 */
19407 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
19408 #define etFLOAT       2 /* Floating point.  %f */
19409 #define etEXP         3 /* Exponentional notation. %e and %E */
19410 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
19411 #define etSIZE        5 /* Return number of characters processed so far. %n */
19412 #define etSTRING      6 /* Strings. %s */
19413 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
19414 #define etPERCENT     8 /* Percent symbol. %% */
19415 #define etCHARX       9 /* Characters. %c */
19416 /* The rest are extensions, not normally found in printf() */
19417 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
19418 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
19419                           NULL pointers replaced by SQL NULL.  %Q */
19420 #define etTOKEN      12 /* a pointer to a Token structure */
19421 #define etSRCLIST    13 /* a pointer to a SrcList */
19422 #define etPOINTER    14 /* The %p conversion */
19423 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
19424 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
19425
19426 #define etINVALID     0 /* Any unrecognized conversion type */
19427
19428
19429 /*
19430 ** An "etByte" is an 8-bit unsigned value.
19431 */
19432 typedef unsigned char etByte;
19433
19434 /*
19435 ** Each builtin conversion character (ex: the 'd' in "%d") is described
19436 ** by an instance of the following structure
19437 */
19438 typedef struct et_info {   /* Information about each format field */
19439   char fmttype;            /* The format field code letter */
19440   etByte base;             /* The base for radix conversion */
19441   etByte flags;            /* One or more of FLAG_ constants below */
19442   etByte type;             /* Conversion paradigm */
19443   etByte charset;          /* Offset into aDigits[] of the digits string */
19444   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
19445 } et_info;
19446
19447 /*
19448 ** Allowed values for et_info.flags
19449 */
19450 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
19451 #define FLAG_INTERN  2     /* True if for internal use only */
19452 #define FLAG_STRING  4     /* Allow infinity precision */
19453
19454
19455 /*
19456 ** The following table is searched linearly, so it is good to put the
19457 ** most frequently used conversion types first.
19458 */
19459 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
19460 static const char aPrefix[] = "-x0\000X0";
19461 static const et_info fmtinfo[] = {
19462   {  'd', 10, 1, etRADIX,      0,  0 },
19463   {  's',  0, 4, etSTRING,     0,  0 },
19464   {  'g',  0, 1, etGENERIC,    30, 0 },
19465   {  'z',  0, 4, etDYNSTRING,  0,  0 },
19466   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
19467   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
19468   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
19469   {  'c',  0, 0, etCHARX,      0,  0 },
19470   {  'o',  8, 0, etRADIX,      0,  2 },
19471   {  'u', 10, 0, etRADIX,      0,  0 },
19472   {  'x', 16, 0, etRADIX,      16, 1 },
19473   {  'X', 16, 0, etRADIX,      0,  4 },
19474 #ifndef SQLITE_OMIT_FLOATING_POINT
19475   {  'f',  0, 1, etFLOAT,      0,  0 },
19476   {  'e',  0, 1, etEXP,        30, 0 },
19477   {  'E',  0, 1, etEXP,        14, 0 },
19478   {  'G',  0, 1, etGENERIC,    14, 0 },
19479 #endif
19480   {  'i', 10, 1, etRADIX,      0,  0 },
19481   {  'n',  0, 0, etSIZE,       0,  0 },
19482   {  '%',  0, 0, etPERCENT,    0,  0 },
19483   {  'p', 16, 0, etPOINTER,    0,  1 },
19484
19485 /* All the rest have the FLAG_INTERN bit set and are thus for internal
19486 ** use only */
19487   {  'T',  0, 2, etTOKEN,      0,  0 },
19488   {  'S',  0, 2, etSRCLIST,    0,  0 },
19489   {  'r', 10, 3, etORDINAL,    0,  0 },
19490 };
19491
19492 /*
19493 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19494 ** conversions will work.
19495 */
19496 #ifndef SQLITE_OMIT_FLOATING_POINT
19497 /*
19498 ** "*val" is a double such that 0.1 <= *val < 10.0
19499 ** Return the ascii code for the leading digit of *val, then
19500 ** multiply "*val" by 10.0 to renormalize.
19501 **
19502 ** Example:
19503 **     input:     *val = 3.14159
19504 **     output:    *val = 1.4159    function return = '3'
19505 **
19506 ** The counter *cnt is incremented each time.  After counter exceeds
19507 ** 16 (the number of significant digits in a 64-bit float) '0' is
19508 ** always returned.
19509 */
19510 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19511   int digit;
19512   LONGDOUBLE_TYPE d;
19513   if( (*cnt)<=0 ) return '0';
19514   (*cnt)--;
19515   digit = (int)*val;
19516   d = digit;
19517   digit += '0';
19518   *val = (*val - d)*10.0;
19519   return (char)digit;
19520 }
19521 #endif /* SQLITE_OMIT_FLOATING_POINT */
19522
19523 /*
19524 ** Append N space characters to the given string buffer.
19525 */
19526 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
19527   static const char zSpaces[] = "                             ";
19528   while( N>=(int)sizeof(zSpaces)-1 ){
19529     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19530     N -= sizeof(zSpaces)-1;
19531   }
19532   if( N>0 ){
19533     sqlite3StrAccumAppend(pAccum, zSpaces, N);
19534   }
19535 }
19536
19537 /*
19538 ** On machines with a small stack size, you can redefine the
19539 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19540 */
19541 #ifndef SQLITE_PRINT_BUF_SIZE
19542 # define SQLITE_PRINT_BUF_SIZE 70
19543 #endif
19544 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
19545
19546 /*
19547 ** Render a string given by "fmt" into the StrAccum object.
19548 */
19549 SQLITE_PRIVATE void sqlite3VXPrintf(
19550   StrAccum *pAccum,                  /* Accumulate results here */
19551   int useExtended,                   /* Allow extended %-conversions */
19552   const char *fmt,                   /* Format string */
19553   va_list ap                         /* arguments */
19554 ){
19555   int c;                     /* Next character in the format string */
19556   char *bufpt;               /* Pointer to the conversion buffer */
19557   int precision;             /* Precision of the current field */
19558   int length;                /* Length of the field */
19559   int idx;                   /* A general purpose loop counter */
19560   int width;                 /* Width of the current field */
19561   etByte flag_leftjustify;   /* True if "-" flag is present */
19562   etByte flag_plussign;      /* True if "+" flag is present */
19563   etByte flag_blanksign;     /* True if " " flag is present */
19564   etByte flag_alternateform; /* True if "#" flag is present */
19565   etByte flag_altform2;      /* True if "!" flag is present */
19566   etByte flag_zeropad;       /* True if field width constant starts with zero */
19567   etByte flag_long;          /* True if "l" flag is present */
19568   etByte flag_longlong;      /* True if the "ll" flag is present */
19569   etByte done;               /* Loop termination flag */
19570   etByte xtype = 0;          /* Conversion paradigm */
19571   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19572   sqlite_uint64 longvalue;   /* Value for integer types */
19573   LONGDOUBLE_TYPE realvalue; /* Value for real types */
19574   const et_info *infop;      /* Pointer to the appropriate info structure */
19575   char *zOut;                /* Rendering buffer */
19576   int nOut;                  /* Size of the rendering buffer */
19577   char *zExtra;              /* Malloced memory used by some conversion */
19578 #ifndef SQLITE_OMIT_FLOATING_POINT
19579   int  exp, e2;              /* exponent of real numbers */
19580   int nsd;                   /* Number of significant digits returned */
19581   double rounder;            /* Used for rounding floating point values */
19582   etByte flag_dp;            /* True if decimal point should be shown */
19583   etByte flag_rtz;           /* True if trailing zeros should be removed */
19584 #endif
19585   char buf[etBUFSIZE];       /* Conversion buffer */
19586
19587   bufpt = 0;
19588   for(; (c=(*fmt))!=0; ++fmt){
19589     if( c!='%' ){
19590       int amt;
19591       bufpt = (char *)fmt;
19592       amt = 1;
19593       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19594       sqlite3StrAccumAppend(pAccum, bufpt, amt);
19595       if( c==0 ) break;
19596     }
19597     if( (c=(*++fmt))==0 ){
19598       sqlite3StrAccumAppend(pAccum, "%", 1);
19599       break;
19600     }
19601     /* Find out what flags are present */
19602     flag_leftjustify = flag_plussign = flag_blanksign = 
19603      flag_alternateform = flag_altform2 = flag_zeropad = 0;
19604     done = 0;
19605     do{
19606       switch( c ){
19607         case '-':   flag_leftjustify = 1;     break;
19608         case '+':   flag_plussign = 1;        break;
19609         case ' ':   flag_blanksign = 1;       break;
19610         case '#':   flag_alternateform = 1;   break;
19611         case '!':   flag_altform2 = 1;        break;
19612         case '0':   flag_zeropad = 1;         break;
19613         default:    done = 1;                 break;
19614       }
19615     }while( !done && (c=(*++fmt))!=0 );
19616     /* Get the field width */
19617     width = 0;
19618     if( c=='*' ){
19619       width = va_arg(ap,int);
19620       if( width<0 ){
19621         flag_leftjustify = 1;
19622         width = -width;
19623       }
19624       c = *++fmt;
19625     }else{
19626       while( c>='0' && c<='9' ){
19627         width = width*10 + c - '0';
19628         c = *++fmt;
19629       }
19630     }
19631     /* Get the precision */
19632     if( c=='.' ){
19633       precision = 0;
19634       c = *++fmt;
19635       if( c=='*' ){
19636         precision = va_arg(ap,int);
19637         if( precision<0 ) precision = -precision;
19638         c = *++fmt;
19639       }else{
19640         while( c>='0' && c<='9' ){
19641           precision = precision*10 + c - '0';
19642           c = *++fmt;
19643         }
19644       }
19645     }else{
19646       precision = -1;
19647     }
19648     /* Get the conversion type modifier */
19649     if( c=='l' ){
19650       flag_long = 1;
19651       c = *++fmt;
19652       if( c=='l' ){
19653         flag_longlong = 1;
19654         c = *++fmt;
19655       }else{
19656         flag_longlong = 0;
19657       }
19658     }else{
19659       flag_long = flag_longlong = 0;
19660     }
19661     /* Fetch the info entry for the field */
19662     infop = &fmtinfo[0];
19663     xtype = etINVALID;
19664     for(idx=0; idx<ArraySize(fmtinfo); idx++){
19665       if( c==fmtinfo[idx].fmttype ){
19666         infop = &fmtinfo[idx];
19667         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19668           xtype = infop->type;
19669         }else{
19670           return;
19671         }
19672         break;
19673       }
19674     }
19675     zExtra = 0;
19676
19677     /*
19678     ** At this point, variables are initialized as follows:
19679     **
19680     **   flag_alternateform          TRUE if a '#' is present.
19681     **   flag_altform2               TRUE if a '!' is present.
19682     **   flag_plussign               TRUE if a '+' is present.
19683     **   flag_leftjustify            TRUE if a '-' is present or if the
19684     **                               field width was negative.
19685     **   flag_zeropad                TRUE if the width began with 0.
19686     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
19687     **                               the conversion character.
19688     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
19689     **                               the conversion character.
19690     **   flag_blanksign              TRUE if a ' ' is present.
19691     **   width                       The specified field width.  This is
19692     **                               always non-negative.  Zero is the default.
19693     **   precision                   The specified precision.  The default
19694     **                               is -1.
19695     **   xtype                       The class of the conversion.
19696     **   infop                       Pointer to the appropriate info struct.
19697     */
19698     switch( xtype ){
19699       case etPOINTER:
19700         flag_longlong = sizeof(char*)==sizeof(i64);
19701         flag_long = sizeof(char*)==sizeof(long int);
19702         /* Fall through into the next case */
19703       case etORDINAL:
19704       case etRADIX:
19705         if( infop->flags & FLAG_SIGNED ){
19706           i64 v;
19707           if( flag_longlong ){
19708             v = va_arg(ap,i64);
19709           }else if( flag_long ){
19710             v = va_arg(ap,long int);
19711           }else{
19712             v = va_arg(ap,int);
19713           }
19714           if( v<0 ){
19715             if( v==SMALLEST_INT64 ){
19716               longvalue = ((u64)1)<<63;
19717             }else{
19718               longvalue = -v;
19719             }
19720             prefix = '-';
19721           }else{
19722             longvalue = v;
19723             if( flag_plussign )        prefix = '+';
19724             else if( flag_blanksign )  prefix = ' ';
19725             else                       prefix = 0;
19726           }
19727         }else{
19728           if( flag_longlong ){
19729             longvalue = va_arg(ap,u64);
19730           }else if( flag_long ){
19731             longvalue = va_arg(ap,unsigned long int);
19732           }else{
19733             longvalue = va_arg(ap,unsigned int);
19734           }
19735           prefix = 0;
19736         }
19737         if( longvalue==0 ) flag_alternateform = 0;
19738         if( flag_zeropad && precision<width-(prefix!=0) ){
19739           precision = width-(prefix!=0);
19740         }
19741         if( precision<etBUFSIZE-10 ){
19742           nOut = etBUFSIZE;
19743           zOut = buf;
19744         }else{
19745           nOut = precision + 10;
19746           zOut = zExtra = sqlite3Malloc( nOut );
19747           if( zOut==0 ){
19748             pAccum->mallocFailed = 1;
19749             return;
19750           }
19751         }
19752         bufpt = &zOut[nOut-1];
19753         if( xtype==etORDINAL ){
19754           static const char zOrd[] = "thstndrd";
19755           int x = (int)(longvalue % 10);
19756           if( x>=4 || (longvalue/10)%10==1 ){
19757             x = 0;
19758           }
19759           *(--bufpt) = zOrd[x*2+1];
19760           *(--bufpt) = zOrd[x*2];
19761         }
19762         {
19763           register const char *cset;      /* Use registers for speed */
19764           register int base;
19765           cset = &aDigits[infop->charset];
19766           base = infop->base;
19767           do{                                           /* Convert to ascii */
19768             *(--bufpt) = cset[longvalue%base];
19769             longvalue = longvalue/base;
19770           }while( longvalue>0 );
19771         }
19772         length = (int)(&zOut[nOut-1]-bufpt);
19773         for(idx=precision-length; idx>0; idx--){
19774           *(--bufpt) = '0';                             /* Zero pad */
19775         }
19776         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
19777         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
19778           const char *pre;
19779           char x;
19780           pre = &aPrefix[infop->prefix];
19781           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19782         }
19783         length = (int)(&zOut[nOut-1]-bufpt);
19784         break;
19785       case etFLOAT:
19786       case etEXP:
19787       case etGENERIC:
19788         realvalue = va_arg(ap,double);
19789 #ifdef SQLITE_OMIT_FLOATING_POINT
19790         length = 0;
19791 #else
19792         if( precision<0 ) precision = 6;         /* Set default precision */
19793         if( realvalue<0.0 ){
19794           realvalue = -realvalue;
19795           prefix = '-';
19796         }else{
19797           if( flag_plussign )          prefix = '+';
19798           else if( flag_blanksign )    prefix = ' ';
19799           else                         prefix = 0;
19800         }
19801         if( xtype==etGENERIC && precision>0 ) precision--;
19802 #if 0
19803         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
19804         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19805 #else
19806         /* It makes more sense to use 0.5 */
19807         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19808 #endif
19809         if( xtype==etFLOAT ) realvalue += rounder;
19810         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19811         exp = 0;
19812         if( sqlite3IsNaN((double)realvalue) ){
19813           bufpt = "NaN";
19814           length = 3;
19815           break;
19816         }
19817         if( realvalue>0.0 ){
19818           LONGDOUBLE_TYPE scale = 1.0;
19819           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
19820           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
19821           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
19822           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
19823           realvalue /= scale;
19824           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19825           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19826           if( exp>350 ){
19827             if( prefix=='-' ){
19828               bufpt = "-Inf";
19829             }else if( prefix=='+' ){
19830               bufpt = "+Inf";
19831             }else{
19832               bufpt = "Inf";
19833             }
19834             length = sqlite3Strlen30(bufpt);
19835             break;
19836           }
19837         }
19838         bufpt = buf;
19839         /*
19840         ** If the field type is etGENERIC, then convert to either etEXP
19841         ** or etFLOAT, as appropriate.
19842         */
19843         if( xtype!=etFLOAT ){
19844           realvalue += rounder;
19845           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19846         }
19847         if( xtype==etGENERIC ){
19848           flag_rtz = !flag_alternateform;
19849           if( exp<-4 || exp>precision ){
19850             xtype = etEXP;
19851           }else{
19852             precision = precision - exp;
19853             xtype = etFLOAT;
19854           }
19855         }else{
19856           flag_rtz = flag_altform2;
19857         }
19858         if( xtype==etEXP ){
19859           e2 = 0;
19860         }else{
19861           e2 = exp;
19862         }
19863         if( e2+precision+width > etBUFSIZE - 15 ){
19864           bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
19865           if( bufpt==0 ){
19866             pAccum->mallocFailed = 1;
19867             return;
19868           }
19869         }
19870         zOut = bufpt;
19871         nsd = 16 + flag_altform2*10;
19872         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19873         /* The sign in front of the number */
19874         if( prefix ){
19875           *(bufpt++) = prefix;
19876         }
19877         /* Digits prior to the decimal point */
19878         if( e2<0 ){
19879           *(bufpt++) = '0';
19880         }else{
19881           for(; e2>=0; e2--){
19882             *(bufpt++) = et_getdigit(&realvalue,&nsd);
19883           }
19884         }
19885         /* The decimal point */
19886         if( flag_dp ){
19887           *(bufpt++) = '.';
19888         }
19889         /* "0" digits after the decimal point but before the first
19890         ** significant digit of the number */
19891         for(e2++; e2<0; precision--, e2++){
19892           assert( precision>0 );
19893           *(bufpt++) = '0';
19894         }
19895         /* Significant digits after the decimal point */
19896         while( (precision--)>0 ){
19897           *(bufpt++) = et_getdigit(&realvalue,&nsd);
19898         }
19899         /* Remove trailing zeros and the "." if no digits follow the "." */
19900         if( flag_rtz && flag_dp ){
19901           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19902           assert( bufpt>zOut );
19903           if( bufpt[-1]=='.' ){
19904             if( flag_altform2 ){
19905               *(bufpt++) = '0';
19906             }else{
19907               *(--bufpt) = 0;
19908             }
19909           }
19910         }
19911         /* Add the "eNNN" suffix */
19912         if( xtype==etEXP ){
19913           *(bufpt++) = aDigits[infop->charset];
19914           if( exp<0 ){
19915             *(bufpt++) = '-'; exp = -exp;
19916           }else{
19917             *(bufpt++) = '+';
19918           }
19919           if( exp>=100 ){
19920             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
19921             exp %= 100;
19922           }
19923           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
19924           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
19925         }
19926         *bufpt = 0;
19927
19928         /* The converted number is in buf[] and zero terminated. Output it.
19929         ** Note that the number is in the usual order, not reversed as with
19930         ** integer conversions. */
19931         length = (int)(bufpt-zOut);
19932         bufpt = zOut;
19933
19934         /* Special case:  Add leading zeros if the flag_zeropad flag is
19935         ** set and we are not left justified */
19936         if( flag_zeropad && !flag_leftjustify && length < width){
19937           int i;
19938           int nPad = width - length;
19939           for(i=width; i>=nPad; i--){
19940             bufpt[i] = bufpt[i-nPad];
19941           }
19942           i = prefix!=0;
19943           while( nPad-- ) bufpt[i++] = '0';
19944           length = width;
19945         }
19946 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19947         break;
19948       case etSIZE:
19949         *(va_arg(ap,int*)) = pAccum->nChar;
19950         length = width = 0;
19951         break;
19952       case etPERCENT:
19953         buf[0] = '%';
19954         bufpt = buf;
19955         length = 1;
19956         break;
19957       case etCHARX:
19958         c = va_arg(ap,int);
19959         buf[0] = (char)c;
19960         if( precision>=0 ){
19961           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19962           length = precision;
19963         }else{
19964           length =1;
19965         }
19966         bufpt = buf;
19967         break;
19968       case etSTRING:
19969       case etDYNSTRING:
19970         bufpt = va_arg(ap,char*);
19971         if( bufpt==0 ){
19972           bufpt = "";
19973         }else if( xtype==etDYNSTRING ){
19974           zExtra = bufpt;
19975         }
19976         if( precision>=0 ){
19977           for(length=0; length<precision && bufpt[length]; length++){}
19978         }else{
19979           length = sqlite3Strlen30(bufpt);
19980         }
19981         break;
19982       case etSQLESCAPE:
19983       case etSQLESCAPE2:
19984       case etSQLESCAPE3: {
19985         int i, j, k, n, isnull;
19986         int needQuote;
19987         char ch;
19988         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
19989         char *escarg = va_arg(ap,char*);
19990         isnull = escarg==0;
19991         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19992         k = precision;
19993         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19994           if( ch==q )  n++;
19995         }
19996         needQuote = !isnull && xtype==etSQLESCAPE2;
19997         n += i + 1 + needQuote*2;
19998         if( n>etBUFSIZE ){
19999           bufpt = zExtra = sqlite3Malloc( n );
20000           if( bufpt==0 ){
20001             pAccum->mallocFailed = 1;
20002             return;
20003           }
20004         }else{
20005           bufpt = buf;
20006         }
20007         j = 0;
20008         if( needQuote ) bufpt[j++] = q;
20009         k = i;
20010         for(i=0; i<k; i++){
20011           bufpt[j++] = ch = escarg[i];
20012           if( ch==q ) bufpt[j++] = ch;
20013         }
20014         if( needQuote ) bufpt[j++] = q;
20015         bufpt[j] = 0;
20016         length = j;
20017         /* The precision in %q and %Q means how many input characters to
20018         ** consume, not the length of the output...
20019         ** if( precision>=0 && precision<length ) length = precision; */
20020         break;
20021       }
20022       case etTOKEN: {
20023         Token *pToken = va_arg(ap, Token*);
20024         if( pToken ){
20025           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
20026         }
20027         length = width = 0;
20028         break;
20029       }
20030       case etSRCLIST: {
20031         SrcList *pSrc = va_arg(ap, SrcList*);
20032         int k = va_arg(ap, int);
20033         struct SrcList_item *pItem = &pSrc->a[k];
20034         assert( k>=0 && k<pSrc->nSrc );
20035         if( pItem->zDatabase ){
20036           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
20037           sqlite3StrAccumAppend(pAccum, ".", 1);
20038         }
20039         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
20040         length = width = 0;
20041         break;
20042       }
20043       default: {
20044         assert( xtype==etINVALID );
20045         return;
20046       }
20047     }/* End switch over the format type */
20048     /*
20049     ** The text of the conversion is pointed to by "bufpt" and is
20050     ** "length" characters long.  The field width is "width".  Do
20051     ** the output.
20052     */
20053     if( !flag_leftjustify ){
20054       register int nspace;
20055       nspace = width-length;
20056       if( nspace>0 ){
20057         sqlite3AppendSpace(pAccum, nspace);
20058       }
20059     }
20060     if( length>0 ){
20061       sqlite3StrAccumAppend(pAccum, bufpt, length);
20062     }
20063     if( flag_leftjustify ){
20064       register int nspace;
20065       nspace = width-length;
20066       if( nspace>0 ){
20067         sqlite3AppendSpace(pAccum, nspace);
20068       }
20069     }
20070     sqlite3_free(zExtra);
20071   }/* End for loop over the format string */
20072 } /* End of function */
20073
20074 /*
20075 ** Append N bytes of text from z to the StrAccum object.
20076 */
20077 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
20078   assert( z!=0 || N==0 );
20079   if( p->tooBig | p->mallocFailed ){
20080     testcase(p->tooBig);
20081     testcase(p->mallocFailed);
20082     return;
20083   }
20084   assert( p->zText!=0 || p->nChar==0 );
20085   if( N<0 ){
20086     N = sqlite3Strlen30(z);
20087   }
20088   if( N==0 || NEVER(z==0) ){
20089     return;
20090   }
20091   if( p->nChar+N >= p->nAlloc ){
20092     char *zNew;
20093     if( !p->useMalloc ){
20094       p->tooBig = 1;
20095       N = p->nAlloc - p->nChar - 1;
20096       if( N<=0 ){
20097         return;
20098       }
20099     }else{
20100       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
20101       i64 szNew = p->nChar;
20102       szNew += N + 1;
20103       if( szNew > p->mxAlloc ){
20104         sqlite3StrAccumReset(p);
20105         p->tooBig = 1;
20106         return;
20107       }else{
20108         p->nAlloc = (int)szNew;
20109       }
20110       if( p->useMalloc==1 ){
20111         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
20112       }else{
20113         zNew = sqlite3_realloc(zOld, p->nAlloc);
20114       }
20115       if( zNew ){
20116         if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
20117         p->zText = zNew;
20118       }else{
20119         p->mallocFailed = 1;
20120         sqlite3StrAccumReset(p);
20121         return;
20122       }
20123     }
20124   }
20125   assert( p->zText );
20126   memcpy(&p->zText[p->nChar], z, N);
20127   p->nChar += N;
20128 }
20129
20130 /*
20131 ** Finish off a string by making sure it is zero-terminated.
20132 ** Return a pointer to the resulting string.  Return a NULL
20133 ** pointer if any kind of error was encountered.
20134 */
20135 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
20136   if( p->zText ){
20137     p->zText[p->nChar] = 0;
20138     if( p->useMalloc && p->zText==p->zBase ){
20139       if( p->useMalloc==1 ){
20140         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
20141       }else{
20142         p->zText = sqlite3_malloc(p->nChar+1);
20143       }
20144       if( p->zText ){
20145         memcpy(p->zText, p->zBase, p->nChar+1);
20146       }else{
20147         p->mallocFailed = 1;
20148       }
20149     }
20150   }
20151   return p->zText;
20152 }
20153
20154 /*
20155 ** Reset an StrAccum string.  Reclaim all malloced memory.
20156 */
20157 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
20158   if( p->zText!=p->zBase ){
20159     if( p->useMalloc==1 ){
20160       sqlite3DbFree(p->db, p->zText);
20161     }else{
20162       sqlite3_free(p->zText);
20163     }
20164   }
20165   p->zText = 0;
20166 }
20167
20168 /*
20169 ** Initialize a string accumulator
20170 */
20171 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
20172   p->zText = p->zBase = zBase;
20173   p->db = 0;
20174   p->nChar = 0;
20175   p->nAlloc = n;
20176   p->mxAlloc = mx;
20177   p->useMalloc = 1;
20178   p->tooBig = 0;
20179   p->mallocFailed = 0;
20180 }
20181
20182 /*
20183 ** Print into memory obtained from sqliteMalloc().  Use the internal
20184 ** %-conversion extensions.
20185 */
20186 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
20187   char *z;
20188   char zBase[SQLITE_PRINT_BUF_SIZE];
20189   StrAccum acc;
20190   assert( db!=0 );
20191   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
20192                       db->aLimit[SQLITE_LIMIT_LENGTH]);
20193   acc.db = db;
20194   sqlite3VXPrintf(&acc, 1, zFormat, ap);
20195   z = sqlite3StrAccumFinish(&acc);
20196   if( acc.mallocFailed ){
20197     db->mallocFailed = 1;
20198   }
20199   return z;
20200 }
20201
20202 /*
20203 ** Print into memory obtained from sqliteMalloc().  Use the internal
20204 ** %-conversion extensions.
20205 */
20206 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
20207   va_list ap;
20208   char *z;
20209   va_start(ap, zFormat);
20210   z = sqlite3VMPrintf(db, zFormat, ap);
20211   va_end(ap);
20212   return z;
20213 }
20214
20215 /*
20216 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
20217 ** the string and before returnning.  This routine is intended to be used
20218 ** to modify an existing string.  For example:
20219 **
20220 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
20221 **
20222 */
20223 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
20224   va_list ap;
20225   char *z;
20226   va_start(ap, zFormat);
20227   z = sqlite3VMPrintf(db, zFormat, ap);
20228   va_end(ap);
20229   sqlite3DbFree(db, zStr);
20230   return z;
20231 }
20232
20233 /*
20234 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
20235 ** %-conversion extensions.
20236 */
20237 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
20238   char *z;
20239   char zBase[SQLITE_PRINT_BUF_SIZE];
20240   StrAccum acc;
20241 #ifndef SQLITE_OMIT_AUTOINIT
20242   if( sqlite3_initialize() ) return 0;
20243 #endif
20244   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
20245   acc.useMalloc = 2;
20246   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20247   z = sqlite3StrAccumFinish(&acc);
20248   return z;
20249 }
20250
20251 /*
20252 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
20253 ** %-conversion extensions.
20254 */
20255 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
20256   va_list ap;
20257   char *z;
20258 #ifndef SQLITE_OMIT_AUTOINIT
20259   if( sqlite3_initialize() ) return 0;
20260 #endif
20261   va_start(ap, zFormat);
20262   z = sqlite3_vmprintf(zFormat, ap);
20263   va_end(ap);
20264   return z;
20265 }
20266
20267 /*
20268 ** sqlite3_snprintf() works like snprintf() except that it ignores the
20269 ** current locale settings.  This is important for SQLite because we
20270 ** are not able to use a "," as the decimal point in place of "." as
20271 ** specified by some locales.
20272 **
20273 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
20274 ** from the snprintf() standard.  Unfortunately, it is too late to change
20275 ** this without breaking compatibility, so we just have to live with the
20276 ** mistake.
20277 **
20278 ** sqlite3_vsnprintf() is the varargs version.
20279 */
20280 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
20281   StrAccum acc;
20282   if( n<=0 ) return zBuf;
20283   sqlite3StrAccumInit(&acc, zBuf, n, 0);
20284   acc.useMalloc = 0;
20285   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20286   return sqlite3StrAccumFinish(&acc);
20287 }
20288 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
20289   char *z;
20290   va_list ap;
20291   va_start(ap,zFormat);
20292   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
20293   va_end(ap);
20294   return z;
20295 }
20296
20297 /*
20298 ** This is the routine that actually formats the sqlite3_log() message.
20299 ** We house it in a separate routine from sqlite3_log() to avoid using
20300 ** stack space on small-stack systems when logging is disabled.
20301 **
20302 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
20303 ** allocate memory because it might be called while the memory allocator
20304 ** mutex is held.
20305 */
20306 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
20307   StrAccum acc;                          /* String accumulator */
20308   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
20309
20310   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
20311   acc.useMalloc = 0;
20312   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20313   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
20314                            sqlite3StrAccumFinish(&acc));
20315 }
20316
20317 /*
20318 ** Format and write a message to the log if logging is enabled.
20319 */
20320 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
20321   va_list ap;                             /* Vararg list */
20322   if( sqlite3GlobalConfig.xLog ){
20323     va_start(ap, zFormat);
20324     renderLogMsg(iErrCode, zFormat, ap);
20325     va_end(ap);
20326   }
20327 }
20328
20329 #if defined(SQLITE_DEBUG)
20330 /*
20331 ** A version of printf() that understands %lld.  Used for debugging.
20332 ** The printf() built into some versions of windows does not understand %lld
20333 ** and segfaults if you give it a long long int.
20334 */
20335 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
20336   va_list ap;
20337   StrAccum acc;
20338   char zBuf[500];
20339   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
20340   acc.useMalloc = 0;
20341   va_start(ap,zFormat);
20342   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20343   va_end(ap);
20344   sqlite3StrAccumFinish(&acc);
20345   fprintf(stdout,"%s", zBuf);
20346   fflush(stdout);
20347 }
20348 #endif
20349
20350 #ifndef SQLITE_OMIT_TRACE
20351 /*
20352 ** variable-argument wrapper around sqlite3VXPrintf().
20353 */
20354 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
20355   va_list ap;
20356   va_start(ap,zFormat);
20357   sqlite3VXPrintf(p, 1, zFormat, ap);
20358   va_end(ap);
20359 }
20360 #endif
20361
20362 /************** End of printf.c **********************************************/
20363 /************** Begin file random.c ******************************************/
20364 /*
20365 ** 2001 September 15
20366 **
20367 ** The author disclaims copyright to this source code.  In place of
20368 ** a legal notice, here is a blessing:
20369 **
20370 **    May you do good and not evil.
20371 **    May you find forgiveness for yourself and forgive others.
20372 **    May you share freely, never taking more than you give.
20373 **
20374 *************************************************************************
20375 ** This file contains code to implement a pseudo-random number
20376 ** generator (PRNG) for SQLite.
20377 **
20378 ** Random numbers are used by some of the database backends in order
20379 ** to generate random integer keys for tables or random filenames.
20380 */
20381
20382
20383 /* All threads share a single random number generator.
20384 ** This structure is the current state of the generator.
20385 */
20386 static SQLITE_WSD struct sqlite3PrngType {
20387   unsigned char isInit;          /* True if initialized */
20388   unsigned char i, j;            /* State variables */
20389   unsigned char s[256];          /* State variables */
20390 } sqlite3Prng;
20391
20392 /*
20393 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
20394 ** must be held while executing this routine.
20395 **
20396 ** Why not just use a library random generator like lrand48() for this?
20397 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
20398 ** good source of random numbers.  The lrand48() library function may
20399 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
20400 ** subtle problems on some systems that could cause problems.  It is hard
20401 ** to know.  To minimize the risk of problems due to bad lrand48()
20402 ** implementations, SQLite uses this random number generator based
20403 ** on RC4, which we know works very well.
20404 **
20405 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
20406 ** randomness any more.  But we will leave this code in all the same.
20407 */
20408 static u8 randomByte(void){
20409   unsigned char t;
20410
20411
20412   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
20413   ** state vector.  If writable static data is unsupported on the target,
20414   ** we have to locate the state vector at run-time.  In the more common
20415   ** case where writable static data is supported, wsdPrng can refer directly
20416   ** to the "sqlite3Prng" state vector declared above.
20417   */
20418 #ifdef SQLITE_OMIT_WSD
20419   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
20420 # define wsdPrng p[0]
20421 #else
20422 # define wsdPrng sqlite3Prng
20423 #endif
20424
20425
20426   /* Initialize the state of the random number generator once,
20427   ** the first time this routine is called.  The seed value does
20428   ** not need to contain a lot of randomness since we are not
20429   ** trying to do secure encryption or anything like that...
20430   **
20431   ** Nothing in this file or anywhere else in SQLite does any kind of
20432   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
20433   ** number generator) not as an encryption device.
20434   */
20435   if( !wsdPrng.isInit ){
20436     int i;
20437     char k[256];
20438     wsdPrng.j = 0;
20439     wsdPrng.i = 0;
20440     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
20441     for(i=0; i<256; i++){
20442       wsdPrng.s[i] = (u8)i;
20443     }
20444     for(i=0; i<256; i++){
20445       wsdPrng.j += wsdPrng.s[i] + k[i];
20446       t = wsdPrng.s[wsdPrng.j];
20447       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
20448       wsdPrng.s[i] = t;
20449     }
20450     wsdPrng.isInit = 1;
20451   }
20452
20453   /* Generate and return single random byte
20454   */
20455   wsdPrng.i++;
20456   t = wsdPrng.s[wsdPrng.i];
20457   wsdPrng.j += t;
20458   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20459   wsdPrng.s[wsdPrng.j] = t;
20460   t += wsdPrng.s[wsdPrng.i];
20461   return wsdPrng.s[t];
20462 }
20463
20464 /*
20465 ** Return N random bytes.
20466 */
20467 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20468   unsigned char *zBuf = pBuf;
20469 #if SQLITE_THREADSAFE
20470   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20471 #endif
20472   sqlite3_mutex_enter(mutex);
20473   while( N-- ){
20474     *(zBuf++) = randomByte();
20475   }
20476   sqlite3_mutex_leave(mutex);
20477 }
20478
20479 #ifndef SQLITE_OMIT_BUILTIN_TEST
20480 /*
20481 ** For testing purposes, we sometimes want to preserve the state of
20482 ** PRNG and restore the PRNG to its saved state at a later time, or
20483 ** to reset the PRNG to its initial state.  These routines accomplish
20484 ** those tasks.
20485 **
20486 ** The sqlite3_test_control() interface calls these routines to
20487 ** control the PRNG.
20488 */
20489 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
20490 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20491   memcpy(
20492     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20493     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20494     sizeof(sqlite3Prng)
20495   );
20496 }
20497 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20498   memcpy(
20499     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20500     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20501     sizeof(sqlite3Prng)
20502   );
20503 }
20504 SQLITE_PRIVATE void sqlite3PrngResetState(void){
20505   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20506 }
20507 #endif /* SQLITE_OMIT_BUILTIN_TEST */
20508
20509 /************** End of random.c **********************************************/
20510 /************** Begin file utf.c *********************************************/
20511 /*
20512 ** 2004 April 13
20513 **
20514 ** The author disclaims copyright to this source code.  In place of
20515 ** a legal notice, here is a blessing:
20516 **
20517 **    May you do good and not evil.
20518 **    May you find forgiveness for yourself and forgive others.
20519 **    May you share freely, never taking more than you give.
20520 **
20521 *************************************************************************
20522 ** This file contains routines used to translate between UTF-8, 
20523 ** UTF-16, UTF-16BE, and UTF-16LE.
20524 **
20525 ** Notes on UTF-8:
20526 **
20527 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
20528 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
20529 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
20530 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
20531 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
20532 **
20533 **
20534 ** Notes on UTF-16:  (with wwww+1==uuuuu)
20535 **
20536 **      Word-0               Word-1          Value
20537 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
20538 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
20539 **
20540 **
20541 ** BOM or Byte Order Mark:
20542 **     0xff 0xfe   little-endian utf-16 follows
20543 **     0xfe 0xff   big-endian utf-16 follows
20544 **
20545 */
20546 /* #include <assert.h> */
20547
20548 #ifndef SQLITE_AMALGAMATION
20549 /*
20550 ** The following constant value is used by the SQLITE_BIGENDIAN and
20551 ** SQLITE_LITTLEENDIAN macros.
20552 */
20553 SQLITE_PRIVATE const int sqlite3one = 1;
20554 #endif /* SQLITE_AMALGAMATION */
20555
20556 /*
20557 ** This lookup table is used to help decode the first byte of
20558 ** a multi-byte UTF8 character.
20559 */
20560 static const unsigned char sqlite3Utf8Trans1[] = {
20561   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20562   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20563   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20564   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20565   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20566   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20567   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20568   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20569 };
20570
20571
20572 #define WRITE_UTF8(zOut, c) {                          \
20573   if( c<0x00080 ){                                     \
20574     *zOut++ = (u8)(c&0xFF);                            \
20575   }                                                    \
20576   else if( c<0x00800 ){                                \
20577     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
20578     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20579   }                                                    \
20580   else if( c<0x10000 ){                                \
20581     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
20582     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20583     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20584   }else{                                               \
20585     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
20586     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
20587     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20588     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20589   }                                                    \
20590 }
20591
20592 #define WRITE_UTF16LE(zOut, c) {                                    \
20593   if( c<=0xFFFF ){                                                  \
20594     *zOut++ = (u8)(c&0x00FF);                                       \
20595     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20596   }else{                                                            \
20597     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20598     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20599     *zOut++ = (u8)(c&0x00FF);                                       \
20600     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20601   }                                                                 \
20602 }
20603
20604 #define WRITE_UTF16BE(zOut, c) {                                    \
20605   if( c<=0xFFFF ){                                                  \
20606     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20607     *zOut++ = (u8)(c&0x00FF);                                       \
20608   }else{                                                            \
20609     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20610     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20611     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20612     *zOut++ = (u8)(c&0x00FF);                                       \
20613   }                                                                 \
20614 }
20615
20616 #define READ_UTF16LE(zIn, TERM, c){                                   \
20617   c = (*zIn++);                                                       \
20618   c += ((*zIn++)<<8);                                                 \
20619   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20620     int c2 = (*zIn++);                                                \
20621     c2 += ((*zIn++)<<8);                                              \
20622     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20623   }                                                                   \
20624 }
20625
20626 #define READ_UTF16BE(zIn, TERM, c){                                   \
20627   c = ((*zIn++)<<8);                                                  \
20628   c += (*zIn++);                                                      \
20629   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20630     int c2 = ((*zIn++)<<8);                                           \
20631     c2 += (*zIn++);                                                   \
20632     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20633   }                                                                   \
20634 }
20635
20636 /*
20637 ** Translate a single UTF-8 character.  Return the unicode value.
20638 **
20639 ** During translation, assume that the byte that zTerm points
20640 ** is a 0x00.
20641 **
20642 ** Write a pointer to the next unread byte back into *pzNext.
20643 **
20644 ** Notes On Invalid UTF-8:
20645 **
20646 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
20647 **     be encoded as a multi-byte character.  Any multi-byte character that
20648 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20649 **
20650 **  *  This routine never allows a UTF16 surrogate value to be encoded.
20651 **     If a multi-byte character attempts to encode a value between
20652 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
20653 **
20654 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
20655 **     byte of a character are interpreted as single-byte characters
20656 **     and rendered as themselves even though they are technically
20657 **     invalid characters.
20658 **
20659 **  *  This routine accepts an infinite number of different UTF8 encodings
20660 **     for unicode values 0x80 and greater.  It do not change over-length
20661 **     encodings to 0xfffd as some systems recommend.
20662 */
20663 #define READ_UTF8(zIn, zTerm, c)                           \
20664   c = *(zIn++);                                            \
20665   if( c>=0xc0 ){                                           \
20666     c = sqlite3Utf8Trans1[c-0xc0];                         \
20667     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
20668       c = (c<<6) + (0x3f & *(zIn++));                      \
20669     }                                                      \
20670     if( c<0x80                                             \
20671         || (c&0xFFFFF800)==0xD800                          \
20672         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
20673   }
20674 SQLITE_PRIVATE u32 sqlite3Utf8Read(
20675   const unsigned char **pz    /* Pointer to string from which to read char */
20676 ){
20677   unsigned int c;
20678
20679   /* Same as READ_UTF8() above but without the zTerm parameter.
20680   ** For this routine, we assume the UTF8 string is always zero-terminated.
20681   */
20682   c = *((*pz)++);
20683   if( c>=0xc0 ){
20684     c = sqlite3Utf8Trans1[c-0xc0];
20685     while( (*(*pz) & 0xc0)==0x80 ){
20686       c = (c<<6) + (0x3f & *((*pz)++));
20687     }
20688     if( c<0x80
20689         || (c&0xFFFFF800)==0xD800
20690         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
20691   }
20692   return c;
20693 }
20694
20695
20696
20697
20698 /*
20699 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20700 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20701 */ 
20702 /* #define TRANSLATE_TRACE 1 */
20703
20704 #ifndef SQLITE_OMIT_UTF16
20705 /*
20706 ** This routine transforms the internal text encoding used by pMem to
20707 ** desiredEnc. It is an error if the string is already of the desired
20708 ** encoding, or if *pMem does not contain a string value.
20709 */
20710 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20711   int len;                    /* Maximum length of output string in bytes */
20712   unsigned char *zOut;                  /* Output buffer */
20713   unsigned char *zIn;                   /* Input iterator */
20714   unsigned char *zTerm;                 /* End of input */
20715   unsigned char *z;                     /* Output iterator */
20716   unsigned int c;
20717
20718   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20719   assert( pMem->flags&MEM_Str );
20720   assert( pMem->enc!=desiredEnc );
20721   assert( pMem->enc!=0 );
20722   assert( pMem->n>=0 );
20723
20724 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20725   {
20726     char zBuf[100];
20727     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20728     fprintf(stderr, "INPUT:  %s\n", zBuf);
20729   }
20730 #endif
20731
20732   /* If the translation is between UTF-16 little and big endian, then 
20733   ** all that is required is to swap the byte order. This case is handled
20734   ** differently from the others.
20735   */
20736   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20737     u8 temp;
20738     int rc;
20739     rc = sqlite3VdbeMemMakeWriteable(pMem);
20740     if( rc!=SQLITE_OK ){
20741       assert( rc==SQLITE_NOMEM );
20742       return SQLITE_NOMEM;
20743     }
20744     zIn = (u8*)pMem->z;
20745     zTerm = &zIn[pMem->n&~1];
20746     while( zIn<zTerm ){
20747       temp = *zIn;
20748       *zIn = *(zIn+1);
20749       zIn++;
20750       *zIn++ = temp;
20751     }
20752     pMem->enc = desiredEnc;
20753     goto translate_out;
20754   }
20755
20756   /* Set len to the maximum number of bytes required in the output buffer. */
20757   if( desiredEnc==SQLITE_UTF8 ){
20758     /* When converting from UTF-16, the maximum growth results from
20759     ** translating a 2-byte character to a 4-byte UTF-8 character.
20760     ** A single byte is required for the output string
20761     ** nul-terminator.
20762     */
20763     pMem->n &= ~1;
20764     len = pMem->n * 2 + 1;
20765   }else{
20766     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20767     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20768     ** character. Two bytes are required in the output buffer for the
20769     ** nul-terminator.
20770     */
20771     len = pMem->n * 2 + 2;
20772   }
20773
20774   /* Set zIn to point at the start of the input buffer and zTerm to point 1
20775   ** byte past the end.
20776   **
20777   ** Variable zOut is set to point at the output buffer, space obtained
20778   ** from sqlite3_malloc().
20779   */
20780   zIn = (u8*)pMem->z;
20781   zTerm = &zIn[pMem->n];
20782   zOut = sqlite3DbMallocRaw(pMem->db, len);
20783   if( !zOut ){
20784     return SQLITE_NOMEM;
20785   }
20786   z = zOut;
20787
20788   if( pMem->enc==SQLITE_UTF8 ){
20789     if( desiredEnc==SQLITE_UTF16LE ){
20790       /* UTF-8 -> UTF-16 Little-endian */
20791       while( zIn<zTerm ){
20792         READ_UTF8(zIn, zTerm, c);
20793         WRITE_UTF16LE(z, c);
20794       }
20795     }else{
20796       assert( desiredEnc==SQLITE_UTF16BE );
20797       /* UTF-8 -> UTF-16 Big-endian */
20798       while( zIn<zTerm ){
20799         READ_UTF8(zIn, zTerm, c);
20800         WRITE_UTF16BE(z, c);
20801       }
20802     }
20803     pMem->n = (int)(z - zOut);
20804     *z++ = 0;
20805   }else{
20806     assert( desiredEnc==SQLITE_UTF8 );
20807     if( pMem->enc==SQLITE_UTF16LE ){
20808       /* UTF-16 Little-endian -> UTF-8 */
20809       while( zIn<zTerm ){
20810         READ_UTF16LE(zIn, zIn<zTerm, c); 
20811         WRITE_UTF8(z, c);
20812       }
20813     }else{
20814       /* UTF-16 Big-endian -> UTF-8 */
20815       while( zIn<zTerm ){
20816         READ_UTF16BE(zIn, zIn<zTerm, c); 
20817         WRITE_UTF8(z, c);
20818       }
20819     }
20820     pMem->n = (int)(z - zOut);
20821   }
20822   *z = 0;
20823   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20824
20825   sqlite3VdbeMemRelease(pMem);
20826   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20827   pMem->enc = desiredEnc;
20828   pMem->flags |= (MEM_Term|MEM_Dyn);
20829   pMem->z = (char*)zOut;
20830   pMem->zMalloc = pMem->z;
20831
20832 translate_out:
20833 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20834   {
20835     char zBuf[100];
20836     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20837     fprintf(stderr, "OUTPUT: %s\n", zBuf);
20838   }
20839 #endif
20840   return SQLITE_OK;
20841 }
20842
20843 /*
20844 ** This routine checks for a byte-order mark at the beginning of the 
20845 ** UTF-16 string stored in *pMem. If one is present, it is removed and
20846 ** the encoding of the Mem adjusted. This routine does not do any
20847 ** byte-swapping, it just sets Mem.enc appropriately.
20848 **
20849 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
20850 ** changed by this function.
20851 */
20852 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20853   int rc = SQLITE_OK;
20854   u8 bom = 0;
20855
20856   assert( pMem->n>=0 );
20857   if( pMem->n>1 ){
20858     u8 b1 = *(u8 *)pMem->z;
20859     u8 b2 = *(((u8 *)pMem->z) + 1);
20860     if( b1==0xFE && b2==0xFF ){
20861       bom = SQLITE_UTF16BE;
20862     }
20863     if( b1==0xFF && b2==0xFE ){
20864       bom = SQLITE_UTF16LE;
20865     }
20866   }
20867   
20868   if( bom ){
20869     rc = sqlite3VdbeMemMakeWriteable(pMem);
20870     if( rc==SQLITE_OK ){
20871       pMem->n -= 2;
20872       memmove(pMem->z, &pMem->z[2], pMem->n);
20873       pMem->z[pMem->n] = '\0';
20874       pMem->z[pMem->n+1] = '\0';
20875       pMem->flags |= MEM_Term;
20876       pMem->enc = bom;
20877     }
20878   }
20879   return rc;
20880 }
20881 #endif /* SQLITE_OMIT_UTF16 */
20882
20883 /*
20884 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20885 ** return the number of unicode characters in pZ up to (but not including)
20886 ** the first 0x00 byte. If nByte is not less than zero, return the
20887 ** number of unicode characters in the first nByte of pZ (or up to 
20888 ** the first 0x00, whichever comes first).
20889 */
20890 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20891   int r = 0;
20892   const u8 *z = (const u8*)zIn;
20893   const u8 *zTerm;
20894   if( nByte>=0 ){
20895     zTerm = &z[nByte];
20896   }else{
20897     zTerm = (const u8*)(-1);
20898   }
20899   assert( z<=zTerm );
20900   while( *z!=0 && z<zTerm ){
20901     SQLITE_SKIP_UTF8(z);
20902     r++;
20903   }
20904   return r;
20905 }
20906
20907 /* This test function is not currently used by the automated test-suite. 
20908 ** Hence it is only available in debug builds.
20909 */
20910 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20911 /*
20912 ** Translate UTF-8 to UTF-8.
20913 **
20914 ** This has the effect of making sure that the string is well-formed
20915 ** UTF-8.  Miscoded characters are removed.
20916 **
20917 ** The translation is done in-place and aborted if the output
20918 ** overruns the input.
20919 */
20920 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20921   unsigned char *zOut = zIn;
20922   unsigned char *zStart = zIn;
20923   u32 c;
20924
20925   while( zIn[0] && zOut<=zIn ){
20926     c = sqlite3Utf8Read((const u8**)&zIn);
20927     if( c!=0xfffd ){
20928       WRITE_UTF8(zOut, c);
20929     }
20930   }
20931   *zOut = 0;
20932   return (int)(zOut - zStart);
20933 }
20934 #endif
20935
20936 #ifndef SQLITE_OMIT_UTF16
20937 /*
20938 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20939 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20940 ** be freed by the calling function.
20941 **
20942 ** NULL is returned if there is an allocation error.
20943 */
20944 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20945   Mem m;
20946   memset(&m, 0, sizeof(m));
20947   m.db = db;
20948   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20949   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20950   if( db->mallocFailed ){
20951     sqlite3VdbeMemRelease(&m);
20952     m.z = 0;
20953   }
20954   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20955   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20956   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20957   assert( m.z || db->mallocFailed );
20958   return m.z;
20959 }
20960
20961 /*
20962 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20963 ** enc. A pointer to the new string is returned, and the value of *pnOut
20964 ** is set to the length of the returned string in bytes. The call should
20965 ** arrange to call sqlite3DbFree() on the returned pointer when it is
20966 ** no longer required.
20967 ** 
20968 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20969 ** flag set.
20970 */
20971 #ifdef SQLITE_ENABLE_STAT3
20972 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20973   Mem m;
20974   memset(&m, 0, sizeof(m));
20975   m.db = db;
20976   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20977   if( sqlite3VdbeMemTranslate(&m, enc) ){
20978     assert( db->mallocFailed );
20979     return 0;
20980   }
20981   assert( m.z==m.zMalloc );
20982   *pnOut = m.n;
20983   return m.z;
20984 }
20985 #endif
20986
20987 /*
20988 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20989 ** Return the number of bytes in the first nChar unicode characters
20990 ** in pZ.  nChar must be non-negative.
20991 */
20992 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20993   int c;
20994   unsigned char const *z = zIn;
20995   int n = 0;
20996   
20997   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20998     while( n<nChar ){
20999       READ_UTF16BE(z, 1, c);
21000       n++;
21001     }
21002   }else{
21003     while( n<nChar ){
21004       READ_UTF16LE(z, 1, c);
21005       n++;
21006     }
21007   }
21008   return (int)(z-(unsigned char const *)zIn);
21009 }
21010
21011 #if defined(SQLITE_TEST)
21012 /*
21013 ** This routine is called from the TCL test function "translate_selftest".
21014 ** It checks that the primitives for serializing and deserializing
21015 ** characters in each encoding are inverses of each other.
21016 */
21017 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
21018   unsigned int i, t;
21019   unsigned char zBuf[20];
21020   unsigned char *z;
21021   int n;
21022   unsigned int c;
21023
21024   for(i=0; i<0x00110000; i++){
21025     z = zBuf;
21026     WRITE_UTF8(z, i);
21027     n = (int)(z-zBuf);
21028     assert( n>0 && n<=4 );
21029     z[0] = 0;
21030     z = zBuf;
21031     c = sqlite3Utf8Read((const u8**)&z);
21032     t = i;
21033     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
21034     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
21035     assert( c==t );
21036     assert( (z-zBuf)==n );
21037   }
21038   for(i=0; i<0x00110000; i++){
21039     if( i>=0xD800 && i<0xE000 ) continue;
21040     z = zBuf;
21041     WRITE_UTF16LE(z, i);
21042     n = (int)(z-zBuf);
21043     assert( n>0 && n<=4 );
21044     z[0] = 0;
21045     z = zBuf;
21046     READ_UTF16LE(z, 1, c);
21047     assert( c==i );
21048     assert( (z-zBuf)==n );
21049   }
21050   for(i=0; i<0x00110000; i++){
21051     if( i>=0xD800 && i<0xE000 ) continue;
21052     z = zBuf;
21053     WRITE_UTF16BE(z, i);
21054     n = (int)(z-zBuf);
21055     assert( n>0 && n<=4 );
21056     z[0] = 0;
21057     z = zBuf;
21058     READ_UTF16BE(z, 1, c);
21059     assert( c==i );
21060     assert( (z-zBuf)==n );
21061   }
21062 }
21063 #endif /* SQLITE_TEST */
21064 #endif /* SQLITE_OMIT_UTF16 */
21065
21066 /************** End of utf.c *************************************************/
21067 /************** Begin file util.c ********************************************/
21068 /*
21069 ** 2001 September 15
21070 **
21071 ** The author disclaims copyright to this source code.  In place of
21072 ** a legal notice, here is a blessing:
21073 **
21074 **    May you do good and not evil.
21075 **    May you find forgiveness for yourself and forgive others.
21076 **    May you share freely, never taking more than you give.
21077 **
21078 *************************************************************************
21079 ** Utility functions used throughout sqlite.
21080 **
21081 ** This file contains functions for allocating memory, comparing
21082 ** strings, and stuff like that.
21083 **
21084 */
21085 /* #include <stdarg.h> */
21086 #ifdef SQLITE_HAVE_ISNAN
21087 # include <math.h>
21088 #endif
21089
21090 /*
21091 ** Routine needed to support the testcase() macro.
21092 */
21093 #ifdef SQLITE_COVERAGE_TEST
21094 SQLITE_PRIVATE void sqlite3Coverage(int x){
21095   static unsigned dummy = 0;
21096   dummy += (unsigned)x;
21097 }
21098 #endif
21099
21100 #ifndef SQLITE_OMIT_FLOATING_POINT
21101 /*
21102 ** Return true if the floating point value is Not a Number (NaN).
21103 **
21104 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
21105 ** Otherwise, we have our own implementation that works on most systems.
21106 */
21107 SQLITE_PRIVATE int sqlite3IsNaN(double x){
21108   int rc;   /* The value return */
21109 #if !defined(SQLITE_HAVE_ISNAN)
21110   /*
21111   ** Systems that support the isnan() library function should probably
21112   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
21113   ** found that many systems do not have a working isnan() function so
21114   ** this implementation is provided as an alternative.
21115   **
21116   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
21117   ** On the other hand, the use of -ffast-math comes with the following
21118   ** warning:
21119   **
21120   **      This option [-ffast-math] should never be turned on by any
21121   **      -O option since it can result in incorrect output for programs
21122   **      which depend on an exact implementation of IEEE or ISO 
21123   **      rules/specifications for math functions.
21124   **
21125   ** Under MSVC, this NaN test may fail if compiled with a floating-
21126   ** point precision mode other than /fp:precise.  From the MSDN 
21127   ** documentation:
21128   **
21129   **      The compiler [with /fp:precise] will properly handle comparisons 
21130   **      involving NaN. For example, x != x evaluates to true if x is NaN 
21131   **      ...
21132   */
21133 #ifdef __FAST_MATH__
21134 # error SQLite will not work correctly with the -ffast-math option of GCC.
21135 #endif
21136   volatile double y = x;
21137   volatile double z = y;
21138   rc = (y!=z);
21139 #else  /* if defined(SQLITE_HAVE_ISNAN) */
21140   rc = isnan(x);
21141 #endif /* SQLITE_HAVE_ISNAN */
21142   testcase( rc );
21143   return rc;
21144 }
21145 #endif /* SQLITE_OMIT_FLOATING_POINT */
21146
21147 /*
21148 ** Compute a string length that is limited to what can be stored in
21149 ** lower 30 bits of a 32-bit signed integer.
21150 **
21151 ** The value returned will never be negative.  Nor will it ever be greater
21152 ** than the actual length of the string.  For very long strings (greater
21153 ** than 1GiB) the value returned might be less than the true string length.
21154 */
21155 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
21156   const char *z2 = z;
21157   if( z==0 ) return 0;
21158   while( *z2 ){ z2++; }
21159   return 0x3fffffff & (int)(z2 - z);
21160 }
21161
21162 /*
21163 ** Set the most recent error code and error string for the sqlite
21164 ** handle "db". The error code is set to "err_code".
21165 **
21166 ** If it is not NULL, string zFormat specifies the format of the
21167 ** error string in the style of the printf functions: The following
21168 ** format characters are allowed:
21169 **
21170 **      %s      Insert a string
21171 **      %z      A string that should be freed after use
21172 **      %d      Insert an integer
21173 **      %T      Insert a token
21174 **      %S      Insert the first element of a SrcList
21175 **
21176 ** zFormat and any string tokens that follow it are assumed to be
21177 ** encoded in UTF-8.
21178 **
21179 ** To clear the most recent error for sqlite handle "db", sqlite3Error
21180 ** should be called with err_code set to SQLITE_OK and zFormat set
21181 ** to NULL.
21182 */
21183 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
21184   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
21185     db->errCode = err_code;
21186     if( zFormat ){
21187       char *z;
21188       va_list ap;
21189       va_start(ap, zFormat);
21190       z = sqlite3VMPrintf(db, zFormat, ap);
21191       va_end(ap);
21192       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
21193     }else{
21194       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
21195     }
21196   }
21197 }
21198
21199 /*
21200 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
21201 ** The following formatting characters are allowed:
21202 **
21203 **      %s      Insert a string
21204 **      %z      A string that should be freed after use
21205 **      %d      Insert an integer
21206 **      %T      Insert a token
21207 **      %S      Insert the first element of a SrcList
21208 **
21209 ** This function should be used to report any error that occurs whilst
21210 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
21211 ** last thing the sqlite3_prepare() function does is copy the error
21212 ** stored by this function into the database handle using sqlite3Error().
21213 ** Function sqlite3Error() should be used during statement execution
21214 ** (sqlite3_step() etc.).
21215 */
21216 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
21217   char *zMsg;
21218   va_list ap;
21219   sqlite3 *db = pParse->db;
21220   va_start(ap, zFormat);
21221   zMsg = sqlite3VMPrintf(db, zFormat, ap);
21222   va_end(ap);
21223   if( db->suppressErr ){
21224     sqlite3DbFree(db, zMsg);
21225   }else{
21226     pParse->nErr++;
21227     sqlite3DbFree(db, pParse->zErrMsg);
21228     pParse->zErrMsg = zMsg;
21229     pParse->rc = SQLITE_ERROR;
21230   }
21231 }
21232
21233 /*
21234 ** Convert an SQL-style quoted string into a normal string by removing
21235 ** the quote characters.  The conversion is done in-place.  If the
21236 ** input does not begin with a quote character, then this routine
21237 ** is a no-op.
21238 **
21239 ** The input string must be zero-terminated.  A new zero-terminator
21240 ** is added to the dequoted string.
21241 **
21242 ** The return value is -1 if no dequoting occurs or the length of the
21243 ** dequoted string, exclusive of the zero terminator, if dequoting does
21244 ** occur.
21245 **
21246 ** 2002-Feb-14: This routine is extended to remove MS-Access style
21247 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
21248 ** "a-b-c".
21249 */
21250 SQLITE_PRIVATE int sqlite3Dequote(char *z){
21251   char quote;
21252   int i, j;
21253   if( z==0 ) return -1;
21254   quote = z[0];
21255   switch( quote ){
21256     case '\'':  break;
21257     case '"':   break;
21258     case '`':   break;                /* For MySQL compatibility */
21259     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
21260     default:    return -1;
21261   }
21262   for(i=1, j=0; ALWAYS(z[i]); i++){
21263     if( z[i]==quote ){
21264       if( z[i+1]==quote ){
21265         z[j++] = quote;
21266         i++;
21267       }else{
21268         break;
21269       }
21270     }else{
21271       z[j++] = z[i];
21272     }
21273   }
21274   z[j] = 0;
21275   return j;
21276 }
21277
21278 /* Convenient short-hand */
21279 #define UpperToLower sqlite3UpperToLower
21280
21281 /*
21282 ** Some systems have stricmp().  Others have strcasecmp().  Because
21283 ** there is no consistency, we will define our own.
21284 **
21285 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
21286 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
21287 ** the contents of two buffers containing UTF-8 strings in a
21288 ** case-independent fashion, using the same definition of "case
21289 ** independence" that SQLite uses internally when comparing identifiers.
21290 */
21291 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
21292   register unsigned char *a, *b;
21293   a = (unsigned char *)zLeft;
21294   b = (unsigned char *)zRight;
21295   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21296   return UpperToLower[*a] - UpperToLower[*b];
21297 }
21298 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
21299   register unsigned char *a, *b;
21300   a = (unsigned char *)zLeft;
21301   b = (unsigned char *)zRight;
21302   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21303   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
21304 }
21305
21306 /*
21307 ** The string z[] is an text representation of a real number.
21308 ** Convert this string to a double and write it into *pResult.
21309 **
21310 ** The string z[] is length bytes in length (bytes, not characters) and
21311 ** uses the encoding enc.  The string is not necessarily zero-terminated.
21312 **
21313 ** Return TRUE if the result is a valid real number (or integer) and FALSE
21314 ** if the string is empty or contains extraneous text.  Valid numbers
21315 ** are in one of these formats:
21316 **
21317 **    [+-]digits[E[+-]digits]
21318 **    [+-]digits.[digits][E[+-]digits]
21319 **    [+-].digits[E[+-]digits]
21320 **
21321 ** Leading and trailing whitespace is ignored for the purpose of determining
21322 ** validity.
21323 **
21324 ** If some prefix of the input string is a valid number, this routine
21325 ** returns FALSE but it still converts the prefix and writes the result
21326 ** into *pResult.
21327 */
21328 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
21329 #ifndef SQLITE_OMIT_FLOATING_POINT
21330   int incr;
21331   const char *zEnd = z + length;
21332   /* sign * significand * (10 ^ (esign * exponent)) */
21333   int sign = 1;    /* sign of significand */
21334   i64 s = 0;       /* significand */
21335   int d = 0;       /* adjust exponent for shifting decimal point */
21336   int esign = 1;   /* sign of exponent */
21337   int e = 0;       /* exponent */
21338   int eValid = 1;  /* True exponent is either not used or is well-formed */
21339   double result;
21340   int nDigits = 0;
21341   int nonNum = 0;
21342
21343   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21344   *pResult = 0.0;   /* Default return value, in case of an error */
21345
21346   if( enc==SQLITE_UTF8 ){
21347     incr = 1;
21348   }else{
21349     int i;
21350     incr = 2;
21351     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21352     for(i=3-enc; i<length && z[i]==0; i+=2){}
21353     nonNum = i<length;
21354     zEnd = z+i+enc-3;
21355     z += (enc&1);
21356   }
21357
21358   /* skip leading spaces */
21359   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21360   if( z>=zEnd ) return 0;
21361
21362   /* get sign of significand */
21363   if( *z=='-' ){
21364     sign = -1;
21365     z+=incr;
21366   }else if( *z=='+' ){
21367     z+=incr;
21368   }
21369
21370   /* skip leading zeroes */
21371   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
21372
21373   /* copy max significant digits to significand */
21374   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21375     s = s*10 + (*z - '0');
21376     z+=incr, nDigits++;
21377   }
21378
21379   /* skip non-significant significand digits
21380   ** (increase exponent by d to shift decimal left) */
21381   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
21382   if( z>=zEnd ) goto do_atof_calc;
21383
21384   /* if decimal point is present */
21385   if( *z=='.' ){
21386     z+=incr;
21387     /* copy digits from after decimal to significand
21388     ** (decrease exponent by d to shift decimal right) */
21389     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21390       s = s*10 + (*z - '0');
21391       z+=incr, nDigits++, d--;
21392     }
21393     /* skip non-significant digits */
21394     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
21395   }
21396   if( z>=zEnd ) goto do_atof_calc;
21397
21398   /* if exponent is present */
21399   if( *z=='e' || *z=='E' ){
21400     z+=incr;
21401     eValid = 0;
21402     if( z>=zEnd ) goto do_atof_calc;
21403     /* get sign of exponent */
21404     if( *z=='-' ){
21405       esign = -1;
21406       z+=incr;
21407     }else if( *z=='+' ){
21408       z+=incr;
21409     }
21410     /* copy digits to exponent */
21411     while( z<zEnd && sqlite3Isdigit(*z) ){
21412       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
21413       z+=incr;
21414       eValid = 1;
21415     }
21416   }
21417
21418   /* skip trailing spaces */
21419   if( nDigits && eValid ){
21420     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21421   }
21422
21423 do_atof_calc:
21424   /* adjust exponent by d, and update sign */
21425   e = (e*esign) + d;
21426   if( e<0 ) {
21427     esign = -1;
21428     e *= -1;
21429   } else {
21430     esign = 1;
21431   }
21432
21433   /* if 0 significand */
21434   if( !s ) {
21435     /* In the IEEE 754 standard, zero is signed.
21436     ** Add the sign if we've seen at least one digit */
21437     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
21438   } else {
21439     /* attempt to reduce exponent */
21440     if( esign>0 ){
21441       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
21442     }else{
21443       while( !(s%10) && e>0 ) e--,s/=10;
21444     }
21445
21446     /* adjust the sign of significand */
21447     s = sign<0 ? -s : s;
21448
21449     /* if exponent, scale significand as appropriate
21450     ** and store in result. */
21451     if( e ){
21452       LONGDOUBLE_TYPE scale = 1.0;
21453       /* attempt to handle extremely small/large numbers better */
21454       if( e>307 && e<342 ){
21455         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
21456         if( esign<0 ){
21457           result = s / scale;
21458           result /= 1.0e+308;
21459         }else{
21460           result = s * scale;
21461           result *= 1.0e+308;
21462         }
21463       }else if( e>=342 ){
21464         if( esign<0 ){
21465           result = 0.0*s;
21466         }else{
21467           result = 1e308*1e308*s;  /* Infinity */
21468         }
21469       }else{
21470         /* 1.0e+22 is the largest power of 10 than can be 
21471         ** represented exactly. */
21472         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21473         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21474         if( esign<0 ){
21475           result = s / scale;
21476         }else{
21477           result = s * scale;
21478         }
21479       }
21480     } else {
21481       result = (double)s;
21482     }
21483   }
21484
21485   /* store the result */
21486   *pResult = result;
21487
21488   /* return true if number and no extra non-whitespace chracters after */
21489   return z>=zEnd && nDigits>0 && eValid && nonNum==0;
21490 #else
21491   return !sqlite3Atoi64(z, pResult, length, enc);
21492 #endif /* SQLITE_OMIT_FLOATING_POINT */
21493 }
21494
21495 /*
21496 ** Compare the 19-character string zNum against the text representation
21497 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
21498 ** if zNum is less than, equal to, or greater than the string.
21499 ** Note that zNum must contain exactly 19 characters.
21500 **
21501 ** Unlike memcmp() this routine is guaranteed to return the difference
21502 ** in the values of the last digit if the only difference is in the
21503 ** last digit.  So, for example,
21504 **
21505 **      compare2pow63("9223372036854775800", 1)
21506 **
21507 ** will return -8.
21508 */
21509 static int compare2pow63(const char *zNum, int incr){
21510   int c = 0;
21511   int i;
21512                     /* 012345678901234567 */
21513   const char *pow63 = "922337203685477580";
21514   for(i=0; c==0 && i<18; i++){
21515     c = (zNum[i*incr]-pow63[i])*10;
21516   }
21517   if( c==0 ){
21518     c = zNum[18*incr] - '8';
21519     testcase( c==(-1) );
21520     testcase( c==0 );
21521     testcase( c==(+1) );
21522   }
21523   return c;
21524 }
21525
21526
21527 /*
21528 ** Convert zNum to a 64-bit signed integer.
21529 **
21530 ** If the zNum value is representable as a 64-bit twos-complement 
21531 ** integer, then write that value into *pNum and return 0.
21532 **
21533 ** If zNum is exactly 9223372036854665808, return 2.  This special
21534 ** case is broken out because while 9223372036854665808 cannot be a 
21535 ** signed 64-bit integer, its negative -9223372036854665808 can be.
21536 **
21537 ** If zNum is too big for a 64-bit integer and is not
21538 ** 9223372036854665808  or if zNum contains any non-numeric text,
21539 ** then return 1.
21540 **
21541 ** length is the number of bytes in the string (bytes, not characters).
21542 ** The string is not necessarily zero-terminated.  The encoding is
21543 ** given by enc.
21544 */
21545 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21546   int incr;
21547   u64 u = 0;
21548   int neg = 0; /* assume positive */
21549   int i;
21550   int c = 0;
21551   int nonNum = 0;
21552   const char *zStart;
21553   const char *zEnd = zNum + length;
21554   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21555   if( enc==SQLITE_UTF8 ){
21556     incr = 1;
21557   }else{
21558     incr = 2;
21559     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21560     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
21561     nonNum = i<length;
21562     zEnd = zNum+i+enc-3;
21563     zNum += (enc&1);
21564   }
21565   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21566   if( zNum<zEnd ){
21567     if( *zNum=='-' ){
21568       neg = 1;
21569       zNum+=incr;
21570     }else if( *zNum=='+' ){
21571       zNum+=incr;
21572     }
21573   }
21574   zStart = zNum;
21575   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21576   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21577     u = u*10 + c - '0';
21578   }
21579   if( u>LARGEST_INT64 ){
21580     *pNum = SMALLEST_INT64;
21581   }else if( neg ){
21582     *pNum = -(i64)u;
21583   }else{
21584     *pNum = (i64)u;
21585   }
21586   testcase( i==18 );
21587   testcase( i==19 );
21588   testcase( i==20 );
21589   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
21590     /* zNum is empty or contains non-numeric text or is longer
21591     ** than 19 digits (thus guaranteeing that it is too large) */
21592     return 1;
21593   }else if( i<19*incr ){
21594     /* Less than 19 digits, so we know that it fits in 64 bits */
21595     assert( u<=LARGEST_INT64 );
21596     return 0;
21597   }else{
21598     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
21599     c = compare2pow63(zNum, incr);
21600     if( c<0 ){
21601       /* zNum is less than 9223372036854775808 so it fits */
21602       assert( u<=LARGEST_INT64 );
21603       return 0;
21604     }else if( c>0 ){
21605       /* zNum is greater than 9223372036854775808 so it overflows */
21606       return 1;
21607     }else{
21608       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
21609       ** special case 2 overflow if positive */
21610       assert( u-1==LARGEST_INT64 );
21611       assert( (*pNum)==SMALLEST_INT64 );
21612       return neg ? 0 : 2;
21613     }
21614   }
21615 }
21616
21617 /*
21618 ** If zNum represents an integer that will fit in 32-bits, then set
21619 ** *pValue to that integer and return true.  Otherwise return false.
21620 **
21621 ** Any non-numeric characters that following zNum are ignored.
21622 ** This is different from sqlite3Atoi64() which requires the
21623 ** input number to be zero-terminated.
21624 */
21625 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21626   sqlite_int64 v = 0;
21627   int i, c;
21628   int neg = 0;
21629   if( zNum[0]=='-' ){
21630     neg = 1;
21631     zNum++;
21632   }else if( zNum[0]=='+' ){
21633     zNum++;
21634   }
21635   while( zNum[0]=='0' ) zNum++;
21636   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21637     v = v*10 + c;
21638   }
21639
21640   /* The longest decimal representation of a 32 bit integer is 10 digits:
21641   **
21642   **             1234567890
21643   **     2^31 -> 2147483648
21644   */
21645   testcase( i==10 );
21646   if( i>10 ){
21647     return 0;
21648   }
21649   testcase( v-neg==2147483647 );
21650   if( v-neg>2147483647 ){
21651     return 0;
21652   }
21653   if( neg ){
21654     v = -v;
21655   }
21656   *pValue = (int)v;
21657   return 1;
21658 }
21659
21660 /*
21661 ** Return a 32-bit integer value extracted from a string.  If the
21662 ** string is not an integer, just return 0.
21663 */
21664 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21665   int x = 0;
21666   if( z ) sqlite3GetInt32(z, &x);
21667   return x;
21668 }
21669
21670 /*
21671 ** The variable-length integer encoding is as follows:
21672 **
21673 ** KEY:
21674 **         A = 0xxxxxxx    7 bits of data and one flag bit
21675 **         B = 1xxxxxxx    7 bits of data and one flag bit
21676 **         C = xxxxxxxx    8 bits of data
21677 **
21678 **  7 bits - A
21679 ** 14 bits - BA
21680 ** 21 bits - BBA
21681 ** 28 bits - BBBA
21682 ** 35 bits - BBBBA
21683 ** 42 bits - BBBBBA
21684 ** 49 bits - BBBBBBA
21685 ** 56 bits - BBBBBBBA
21686 ** 64 bits - BBBBBBBBC
21687 */
21688
21689 /*
21690 ** Write a 64-bit variable-length integer to memory starting at p[0].
21691 ** The length of data write will be between 1 and 9 bytes.  The number
21692 ** of bytes written is returned.
21693 **
21694 ** A variable-length integer consists of the lower 7 bits of each byte
21695 ** for all bytes that have the 8th bit set and one byte with the 8th
21696 ** bit clear.  Except, if we get to the 9th byte, it stores the full
21697 ** 8 bits and is the last byte.
21698 */
21699 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21700   int i, j, n;
21701   u8 buf[10];
21702   if( v & (((u64)0xff000000)<<32) ){
21703     p[8] = (u8)v;
21704     v >>= 8;
21705     for(i=7; i>=0; i--){
21706       p[i] = (u8)((v & 0x7f) | 0x80);
21707       v >>= 7;
21708     }
21709     return 9;
21710   }    
21711   n = 0;
21712   do{
21713     buf[n++] = (u8)((v & 0x7f) | 0x80);
21714     v >>= 7;
21715   }while( v!=0 );
21716   buf[0] &= 0x7f;
21717   assert( n<=9 );
21718   for(i=0, j=n-1; j>=0; j--, i++){
21719     p[i] = buf[j];
21720   }
21721   return n;
21722 }
21723
21724 /*
21725 ** This routine is a faster version of sqlite3PutVarint() that only
21726 ** works for 32-bit positive integers and which is optimized for
21727 ** the common case of small integers.  A MACRO version, putVarint32,
21728 ** is provided which inlines the single-byte case.  All code should use
21729 ** the MACRO version as this function assumes the single-byte case has
21730 ** already been handled.
21731 */
21732 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21733 #ifndef putVarint32
21734   if( (v & ~0x7f)==0 ){
21735     p[0] = v;
21736     return 1;
21737   }
21738 #endif
21739   if( (v & ~0x3fff)==0 ){
21740     p[0] = (u8)((v>>7) | 0x80);
21741     p[1] = (u8)(v & 0x7f);
21742     return 2;
21743   }
21744   return sqlite3PutVarint(p, v);
21745 }
21746
21747 /*
21748 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
21749 ** are defined here rather than simply putting the constant expressions
21750 ** inline in order to work around bugs in the RVT compiler.
21751 **
21752 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
21753 **
21754 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
21755 */
21756 #define SLOT_2_0     0x001fc07f
21757 #define SLOT_4_2_0   0xf01fc07f
21758
21759
21760 /*
21761 ** Read a 64-bit variable-length integer from memory starting at p[0].
21762 ** Return the number of bytes read.  The value is stored in *v.
21763 */
21764 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21765   u32 a,b,s;
21766
21767   a = *p;
21768   /* a: p0 (unmasked) */
21769   if (!(a&0x80))
21770   {
21771     *v = a;
21772     return 1;
21773   }
21774
21775   p++;
21776   b = *p;
21777   /* b: p1 (unmasked) */
21778   if (!(b&0x80))
21779   {
21780     a &= 0x7f;
21781     a = a<<7;
21782     a |= b;
21783     *v = a;
21784     return 2;
21785   }
21786
21787   /* Verify that constants are precomputed correctly */
21788   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21789   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21790
21791   p++;
21792   a = a<<14;
21793   a |= *p;
21794   /* a: p0<<14 | p2 (unmasked) */
21795   if (!(a&0x80))
21796   {
21797     a &= SLOT_2_0;
21798     b &= 0x7f;
21799     b = b<<7;
21800     a |= b;
21801     *v = a;
21802     return 3;
21803   }
21804
21805   /* CSE1 from below */
21806   a &= SLOT_2_0;
21807   p++;
21808   b = b<<14;
21809   b |= *p;
21810   /* b: p1<<14 | p3 (unmasked) */
21811   if (!(b&0x80))
21812   {
21813     b &= SLOT_2_0;
21814     /* moved CSE1 up */
21815     /* a &= (0x7f<<14)|(0x7f); */
21816     a = a<<7;
21817     a |= b;
21818     *v = a;
21819     return 4;
21820   }
21821
21822   /* a: p0<<14 | p2 (masked) */
21823   /* b: p1<<14 | p3 (unmasked) */
21824   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21825   /* moved CSE1 up */
21826   /* a &= (0x7f<<14)|(0x7f); */
21827   b &= SLOT_2_0;
21828   s = a;
21829   /* s: p0<<14 | p2 (masked) */
21830
21831   p++;
21832   a = a<<14;
21833   a |= *p;
21834   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21835   if (!(a&0x80))
21836   {
21837     /* we can skip these cause they were (effectively) done above in calc'ing s */
21838     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21839     /* b &= (0x7f<<14)|(0x7f); */
21840     b = b<<7;
21841     a |= b;
21842     s = s>>18;
21843     *v = ((u64)s)<<32 | a;
21844     return 5;
21845   }
21846
21847   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21848   s = s<<7;
21849   s |= b;
21850   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21851
21852   p++;
21853   b = b<<14;
21854   b |= *p;
21855   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
21856   if (!(b&0x80))
21857   {
21858     /* we can skip this cause it was (effectively) done above in calc'ing s */
21859     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21860     a &= SLOT_2_0;
21861     a = a<<7;
21862     a |= b;
21863     s = s>>18;
21864     *v = ((u64)s)<<32 | a;
21865     return 6;
21866   }
21867
21868   p++;
21869   a = a<<14;
21870   a |= *p;
21871   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21872   if (!(a&0x80))
21873   {
21874     a &= SLOT_4_2_0;
21875     b &= SLOT_2_0;
21876     b = b<<7;
21877     a |= b;
21878     s = s>>11;
21879     *v = ((u64)s)<<32 | a;
21880     return 7;
21881   }
21882
21883   /* CSE2 from below */
21884   a &= SLOT_2_0;
21885   p++;
21886   b = b<<14;
21887   b |= *p;
21888   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21889   if (!(b&0x80))
21890   {
21891     b &= SLOT_4_2_0;
21892     /* moved CSE2 up */
21893     /* a &= (0x7f<<14)|(0x7f); */
21894     a = a<<7;
21895     a |= b;
21896     s = s>>4;
21897     *v = ((u64)s)<<32 | a;
21898     return 8;
21899   }
21900
21901   p++;
21902   a = a<<15;
21903   a |= *p;
21904   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21905
21906   /* moved CSE2 up */
21907   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21908   b &= SLOT_2_0;
21909   b = b<<8;
21910   a |= b;
21911
21912   s = s<<4;
21913   b = p[-4];
21914   b &= 0x7f;
21915   b = b>>3;
21916   s |= b;
21917
21918   *v = ((u64)s)<<32 | a;
21919
21920   return 9;
21921 }
21922
21923 /*
21924 ** Read a 32-bit variable-length integer from memory starting at p[0].
21925 ** Return the number of bytes read.  The value is stored in *v.
21926 **
21927 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21928 ** integer, then set *v to 0xffffffff.
21929 **
21930 ** A MACRO version, getVarint32, is provided which inlines the 
21931 ** single-byte case.  All code should use the MACRO version as 
21932 ** this function assumes the single-byte case has already been handled.
21933 */
21934 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21935   u32 a,b;
21936
21937   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
21938   ** by the getVarin32() macro */
21939   a = *p;
21940   /* a: p0 (unmasked) */
21941 #ifndef getVarint32
21942   if (!(a&0x80))
21943   {
21944     /* Values between 0 and 127 */
21945     *v = a;
21946     return 1;
21947   }
21948 #endif
21949
21950   /* The 2-byte case */
21951   p++;
21952   b = *p;
21953   /* b: p1 (unmasked) */
21954   if (!(b&0x80))
21955   {
21956     /* Values between 128 and 16383 */
21957     a &= 0x7f;
21958     a = a<<7;
21959     *v = a | b;
21960     return 2;
21961   }
21962
21963   /* The 3-byte case */
21964   p++;
21965   a = a<<14;
21966   a |= *p;
21967   /* a: p0<<14 | p2 (unmasked) */
21968   if (!(a&0x80))
21969   {
21970     /* Values between 16384 and 2097151 */
21971     a &= (0x7f<<14)|(0x7f);
21972     b &= 0x7f;
21973     b = b<<7;
21974     *v = a | b;
21975     return 3;
21976   }
21977
21978   /* A 32-bit varint is used to store size information in btrees.
21979   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21980   ** A 3-byte varint is sufficient, for example, to record the size
21981   ** of a 1048569-byte BLOB or string.
21982   **
21983   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
21984   ** rare larger cases can be handled by the slower 64-bit varint
21985   ** routine.
21986   */
21987 #if 1
21988   {
21989     u64 v64;
21990     u8 n;
21991
21992     p -= 2;
21993     n = sqlite3GetVarint(p, &v64);
21994     assert( n>3 && n<=9 );
21995     if( (v64 & SQLITE_MAX_U32)!=v64 ){
21996       *v = 0xffffffff;
21997     }else{
21998       *v = (u32)v64;
21999     }
22000     return n;
22001   }
22002
22003 #else
22004   /* For following code (kept for historical record only) shows an
22005   ** unrolling for the 3- and 4-byte varint cases.  This code is
22006   ** slightly faster, but it is also larger and much harder to test.
22007   */
22008   p++;
22009   b = b<<14;
22010   b |= *p;
22011   /* b: p1<<14 | p3 (unmasked) */
22012   if (!(b&0x80))
22013   {
22014     /* Values between 2097152 and 268435455 */
22015     b &= (0x7f<<14)|(0x7f);
22016     a &= (0x7f<<14)|(0x7f);
22017     a = a<<7;
22018     *v = a | b;
22019     return 4;
22020   }
22021
22022   p++;
22023   a = a<<14;
22024   a |= *p;
22025   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
22026   if (!(a&0x80))
22027   {
22028     /* Values  between 268435456 and 34359738367 */
22029     a &= SLOT_4_2_0;
22030     b &= SLOT_4_2_0;
22031     b = b<<7;
22032     *v = a | b;
22033     return 5;
22034   }
22035
22036   /* We can only reach this point when reading a corrupt database
22037   ** file.  In that case we are not in any hurry.  Use the (relatively
22038   ** slow) general-purpose sqlite3GetVarint() routine to extract the
22039   ** value. */
22040   {
22041     u64 v64;
22042     u8 n;
22043
22044     p -= 4;
22045     n = sqlite3GetVarint(p, &v64);
22046     assert( n>5 && n<=9 );
22047     *v = (u32)v64;
22048     return n;
22049   }
22050 #endif
22051 }
22052
22053 /*
22054 ** Return the number of bytes that will be needed to store the given
22055 ** 64-bit integer.
22056 */
22057 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
22058   int i = 0;
22059   do{
22060     i++;
22061     v >>= 7;
22062   }while( v!=0 && ALWAYS(i<9) );
22063   return i;
22064 }
22065
22066
22067 /*
22068 ** Read or write a four-byte big-endian integer value.
22069 */
22070 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
22071   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
22072 }
22073 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
22074   p[0] = (u8)(v>>24);
22075   p[1] = (u8)(v>>16);
22076   p[2] = (u8)(v>>8);
22077   p[3] = (u8)v;
22078 }
22079
22080
22081
22082 /*
22083 ** Translate a single byte of Hex into an integer.
22084 ** This routine only works if h really is a valid hexadecimal
22085 ** character:  0..9a..fA..F
22086 */
22087 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
22088   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
22089 #ifdef SQLITE_ASCII
22090   h += 9*(1&(h>>6));
22091 #endif
22092 #ifdef SQLITE_EBCDIC
22093   h += 9*(1&~(h>>4));
22094 #endif
22095   return (u8)(h & 0xf);
22096 }
22097
22098 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
22099 /*
22100 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
22101 ** value.  Return a pointer to its binary value.  Space to hold the
22102 ** binary value has been obtained from malloc and must be freed by
22103 ** the calling routine.
22104 */
22105 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
22106   char *zBlob;
22107   int i;
22108
22109   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
22110   n--;
22111   if( zBlob ){
22112     for(i=0; i<n; i+=2){
22113       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
22114     }
22115     zBlob[i/2] = 0;
22116   }
22117   return zBlob;
22118 }
22119 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
22120
22121 /*
22122 ** Log an error that is an API call on a connection pointer that should
22123 ** not have been used.  The "type" of connection pointer is given as the
22124 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
22125 */
22126 static void logBadConnection(const char *zType){
22127   sqlite3_log(SQLITE_MISUSE, 
22128      "API call with %s database connection pointer",
22129      zType
22130   );
22131 }
22132
22133 /*
22134 ** Check to make sure we have a valid db pointer.  This test is not
22135 ** foolproof but it does provide some measure of protection against
22136 ** misuse of the interface such as passing in db pointers that are
22137 ** NULL or which have been previously closed.  If this routine returns
22138 ** 1 it means that the db pointer is valid and 0 if it should not be
22139 ** dereferenced for any reason.  The calling function should invoke
22140 ** SQLITE_MISUSE immediately.
22141 **
22142 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
22143 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
22144 ** open properly and is not fit for general use but which can be
22145 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
22146 */
22147 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
22148   u32 magic;
22149   if( db==0 ){
22150     logBadConnection("NULL");
22151     return 0;
22152   }
22153   magic = db->magic;
22154   if( magic!=SQLITE_MAGIC_OPEN ){
22155     if( sqlite3SafetyCheckSickOrOk(db) ){
22156       testcase( sqlite3GlobalConfig.xLog!=0 );
22157       logBadConnection("unopened");
22158     }
22159     return 0;
22160   }else{
22161     return 1;
22162   }
22163 }
22164 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
22165   u32 magic;
22166   magic = db->magic;
22167   if( magic!=SQLITE_MAGIC_SICK &&
22168       magic!=SQLITE_MAGIC_OPEN &&
22169       magic!=SQLITE_MAGIC_BUSY ){
22170     testcase( sqlite3GlobalConfig.xLog!=0 );
22171     logBadConnection("invalid");
22172     return 0;
22173   }else{
22174     return 1;
22175   }
22176 }
22177
22178 /*
22179 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
22180 ** the other 64-bit signed integer at *pA and store the result in *pA.
22181 ** Return 0 on success.  Or if the operation would have resulted in an
22182 ** overflow, leave *pA unchanged and return 1.
22183 */
22184 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
22185   i64 iA = *pA;
22186   testcase( iA==0 ); testcase( iA==1 );
22187   testcase( iB==-1 ); testcase( iB==0 );
22188   if( iB>=0 ){
22189     testcase( iA>0 && LARGEST_INT64 - iA == iB );
22190     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
22191     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
22192     *pA += iB;
22193   }else{
22194     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
22195     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
22196     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
22197     *pA += iB;
22198   }
22199   return 0; 
22200 }
22201 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
22202   testcase( iB==SMALLEST_INT64+1 );
22203   if( iB==SMALLEST_INT64 ){
22204     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
22205     if( (*pA)>=0 ) return 1;
22206     *pA -= iB;
22207     return 0;
22208   }else{
22209     return sqlite3AddInt64(pA, -iB);
22210   }
22211 }
22212 #define TWOPOWER32 (((i64)1)<<32)
22213 #define TWOPOWER31 (((i64)1)<<31)
22214 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
22215   i64 iA = *pA;
22216   i64 iA1, iA0, iB1, iB0, r;
22217
22218   iA1 = iA/TWOPOWER32;
22219   iA0 = iA % TWOPOWER32;
22220   iB1 = iB/TWOPOWER32;
22221   iB0 = iB % TWOPOWER32;
22222   if( iA1*iB1 != 0 ) return 1;
22223   assert( iA1*iB0==0 || iA0*iB1==0 );
22224   r = iA1*iB0 + iA0*iB1;
22225   testcase( r==(-TWOPOWER31)-1 );
22226   testcase( r==(-TWOPOWER31) );
22227   testcase( r==TWOPOWER31 );
22228   testcase( r==TWOPOWER31-1 );
22229   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
22230   r *= TWOPOWER32;
22231   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
22232   *pA = r;
22233   return 0;
22234 }
22235
22236 /*
22237 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
22238 ** if the integer has a value of -2147483648, return +2147483647
22239 */
22240 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
22241   if( x>=0 ) return x;
22242   if( x==(int)0x80000000 ) return 0x7fffffff;
22243   return -x;
22244 }
22245
22246 #ifdef SQLITE_ENABLE_8_3_NAMES
22247 /*
22248 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
22249 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
22250 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
22251 ** three characters, then shorten the suffix on z[] to be the last three
22252 ** characters of the original suffix.
22253 **
22254 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
22255 ** do the suffix shortening regardless of URI parameter.
22256 **
22257 ** Examples:
22258 **
22259 **     test.db-journal    =>   test.nal
22260 **     test.db-wal        =>   test.wal
22261 **     test.db-shm        =>   test.shm
22262 **     test.db-mj7f3319fa =>   test.9fa
22263 */
22264 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
22265 #if SQLITE_ENABLE_8_3_NAMES<2
22266   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
22267 #endif
22268   {
22269     int i, sz;
22270     sz = sqlite3Strlen30(z);
22271     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
22272     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
22273   }
22274 }
22275 #endif
22276
22277 /************** End of util.c ************************************************/
22278 /************** Begin file hash.c ********************************************/
22279 /*
22280 ** 2001 September 22
22281 **
22282 ** The author disclaims copyright to this source code.  In place of
22283 ** a legal notice, here is a blessing:
22284 **
22285 **    May you do good and not evil.
22286 **    May you find forgiveness for yourself and forgive others.
22287 **    May you share freely, never taking more than you give.
22288 **
22289 *************************************************************************
22290 ** This is the implementation of generic hash-tables
22291 ** used in SQLite.
22292 */
22293 /* #include <assert.h> */
22294
22295 /* Turn bulk memory into a hash table object by initializing the
22296 ** fields of the Hash structure.
22297 **
22298 ** "pNew" is a pointer to the hash table that is to be initialized.
22299 */
22300 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
22301   assert( pNew!=0 );
22302   pNew->first = 0;
22303   pNew->count = 0;
22304   pNew->htsize = 0;
22305   pNew->ht = 0;
22306 }
22307
22308 /* Remove all entries from a hash table.  Reclaim all memory.
22309 ** Call this routine to delete a hash table or to reset a hash table
22310 ** to the empty state.
22311 */
22312 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
22313   HashElem *elem;         /* For looping over all elements of the table */
22314
22315   assert( pH!=0 );
22316   elem = pH->first;
22317   pH->first = 0;
22318   sqlite3_free(pH->ht);
22319   pH->ht = 0;
22320   pH->htsize = 0;
22321   while( elem ){
22322     HashElem *next_elem = elem->next;
22323     sqlite3_free(elem);
22324     elem = next_elem;
22325   }
22326   pH->count = 0;
22327 }
22328
22329 /*
22330 ** The hashing function.
22331 */
22332 static unsigned int strHash(const char *z, int nKey){
22333   int h = 0;
22334   assert( nKey>=0 );
22335   while( nKey > 0  ){
22336     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
22337     nKey--;
22338   }
22339   return h;
22340 }
22341
22342
22343 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
22344 ** insert pNew into the pEntry hash bucket.
22345 */
22346 static void insertElement(
22347   Hash *pH,              /* The complete hash table */
22348   struct _ht *pEntry,    /* The entry into which pNew is inserted */
22349   HashElem *pNew         /* The element to be inserted */
22350 ){
22351   HashElem *pHead;       /* First element already in pEntry */
22352   if( pEntry ){
22353     pHead = pEntry->count ? pEntry->chain : 0;
22354     pEntry->count++;
22355     pEntry->chain = pNew;
22356   }else{
22357     pHead = 0;
22358   }
22359   if( pHead ){
22360     pNew->next = pHead;
22361     pNew->prev = pHead->prev;
22362     if( pHead->prev ){ pHead->prev->next = pNew; }
22363     else             { pH->first = pNew; }
22364     pHead->prev = pNew;
22365   }else{
22366     pNew->next = pH->first;
22367     if( pH->first ){ pH->first->prev = pNew; }
22368     pNew->prev = 0;
22369     pH->first = pNew;
22370   }
22371 }
22372
22373
22374 /* Resize the hash table so that it cantains "new_size" buckets.
22375 **
22376 ** The hash table might fail to resize if sqlite3_malloc() fails or
22377 ** if the new size is the same as the prior size.
22378 ** Return TRUE if the resize occurs and false if not.
22379 */
22380 static int rehash(Hash *pH, unsigned int new_size){
22381   struct _ht *new_ht;            /* The new hash table */
22382   HashElem *elem, *next_elem;    /* For looping over existing elements */
22383
22384 #if SQLITE_MALLOC_SOFT_LIMIT>0
22385   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
22386     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
22387   }
22388   if( new_size==pH->htsize ) return 0;
22389 #endif
22390
22391   /* The inability to allocates space for a larger hash table is
22392   ** a performance hit but it is not a fatal error.  So mark the
22393   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of 
22394   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
22395   ** only zeroes the requested number of bytes whereas this module will
22396   ** use the actual amount of space allocated for the hash table (which
22397   ** may be larger than the requested amount).
22398   */
22399   sqlite3BeginBenignMalloc();
22400   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
22401   sqlite3EndBenignMalloc();
22402
22403   if( new_ht==0 ) return 0;
22404   sqlite3_free(pH->ht);
22405   pH->ht = new_ht;
22406   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
22407   memset(new_ht, 0, new_size*sizeof(struct _ht));
22408   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
22409     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
22410     next_elem = elem->next;
22411     insertElement(pH, &new_ht[h], elem);
22412   }
22413   return 1;
22414 }
22415
22416 /* This function (for internal use only) locates an element in an
22417 ** hash table that matches the given key.  The hash for this key has
22418 ** already been computed and is passed as the 4th parameter.
22419 */
22420 static HashElem *findElementGivenHash(
22421   const Hash *pH,     /* The pH to be searched */
22422   const char *pKey,   /* The key we are searching for */
22423   int nKey,           /* Bytes in key (not counting zero terminator) */
22424   unsigned int h      /* The hash for this key. */
22425 ){
22426   HashElem *elem;                /* Used to loop thru the element list */
22427   int count;                     /* Number of elements left to test */
22428
22429   if( pH->ht ){
22430     struct _ht *pEntry = &pH->ht[h];
22431     elem = pEntry->chain;
22432     count = pEntry->count;
22433   }else{
22434     elem = pH->first;
22435     count = pH->count;
22436   }
22437   while( count-- && ALWAYS(elem) ){
22438     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
22439       return elem;
22440     }
22441     elem = elem->next;
22442   }
22443   return 0;
22444 }
22445
22446 /* Remove a single entry from the hash table given a pointer to that
22447 ** element and a hash on the element's key.
22448 */
22449 static void removeElementGivenHash(
22450   Hash *pH,         /* The pH containing "elem" */
22451   HashElem* elem,   /* The element to be removed from the pH */
22452   unsigned int h    /* Hash value for the element */
22453 ){
22454   struct _ht *pEntry;
22455   if( elem->prev ){
22456     elem->prev->next = elem->next; 
22457   }else{
22458     pH->first = elem->next;
22459   }
22460   if( elem->next ){
22461     elem->next->prev = elem->prev;
22462   }
22463   if( pH->ht ){
22464     pEntry = &pH->ht[h];
22465     if( pEntry->chain==elem ){
22466       pEntry->chain = elem->next;
22467     }
22468     pEntry->count--;
22469     assert( pEntry->count>=0 );
22470   }
22471   sqlite3_free( elem );
22472   pH->count--;
22473   if( pH->count==0 ){
22474     assert( pH->first==0 );
22475     assert( pH->count==0 );
22476     sqlite3HashClear(pH);
22477   }
22478 }
22479
22480 /* Attempt to locate an element of the hash table pH with a key
22481 ** that matches pKey,nKey.  Return the data for this element if it is
22482 ** found, or NULL if there is no match.
22483 */
22484 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
22485   HashElem *elem;    /* The element that matches key */
22486   unsigned int h;    /* A hash on key */
22487
22488   assert( pH!=0 );
22489   assert( pKey!=0 );
22490   assert( nKey>=0 );
22491   if( pH->ht ){
22492     h = strHash(pKey, nKey) % pH->htsize;
22493   }else{
22494     h = 0;
22495   }
22496   elem = findElementGivenHash(pH, pKey, nKey, h);
22497   return elem ? elem->data : 0;
22498 }
22499
22500 /* Insert an element into the hash table pH.  The key is pKey,nKey
22501 ** and the data is "data".
22502 **
22503 ** If no element exists with a matching key, then a new
22504 ** element is created and NULL is returned.
22505 **
22506 ** If another element already exists with the same key, then the
22507 ** new data replaces the old data and the old data is returned.
22508 ** The key is not copied in this instance.  If a malloc fails, then
22509 ** the new data is returned and the hash table is unchanged.
22510 **
22511 ** If the "data" parameter to this function is NULL, then the
22512 ** element corresponding to "key" is removed from the hash table.
22513 */
22514 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22515   unsigned int h;       /* the hash of the key modulo hash table size */
22516   HashElem *elem;       /* Used to loop thru the element list */
22517   HashElem *new_elem;   /* New element added to the pH */
22518
22519   assert( pH!=0 );
22520   assert( pKey!=0 );
22521   assert( nKey>=0 );
22522   if( pH->htsize ){
22523     h = strHash(pKey, nKey) % pH->htsize;
22524   }else{
22525     h = 0;
22526   }
22527   elem = findElementGivenHash(pH,pKey,nKey,h);
22528   if( elem ){
22529     void *old_data = elem->data;
22530     if( data==0 ){
22531       removeElementGivenHash(pH,elem,h);
22532     }else{
22533       elem->data = data;
22534       elem->pKey = pKey;
22535       assert(nKey==elem->nKey);
22536     }
22537     return old_data;
22538   }
22539   if( data==0 ) return 0;
22540   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22541   if( new_elem==0 ) return data;
22542   new_elem->pKey = pKey;
22543   new_elem->nKey = nKey;
22544   new_elem->data = data;
22545   pH->count++;
22546   if( pH->count>=10 && pH->count > 2*pH->htsize ){
22547     if( rehash(pH, pH->count*2) ){
22548       assert( pH->htsize>0 );
22549       h = strHash(pKey, nKey) % pH->htsize;
22550     }
22551   }
22552   if( pH->ht ){
22553     insertElement(pH, &pH->ht[h], new_elem);
22554   }else{
22555     insertElement(pH, 0, new_elem);
22556   }
22557   return 0;
22558 }
22559
22560 /************** End of hash.c ************************************************/
22561 /************** Begin file opcodes.c *****************************************/
22562 /* Automatically generated.  Do not edit */
22563 /* See the mkopcodec.awk script for details. */
22564 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
22565 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22566  static const char *const azName[] = { "?",
22567      /*   1 */ "Goto",
22568      /*   2 */ "Gosub",
22569      /*   3 */ "Return",
22570      /*   4 */ "Yield",
22571      /*   5 */ "HaltIfNull",
22572      /*   6 */ "Halt",
22573      /*   7 */ "Integer",
22574      /*   8 */ "Int64",
22575      /*   9 */ "String",
22576      /*  10 */ "Null",
22577      /*  11 */ "Blob",
22578      /*  12 */ "Variable",
22579      /*  13 */ "Move",
22580      /*  14 */ "Copy",
22581      /*  15 */ "SCopy",
22582      /*  16 */ "ResultRow",
22583      /*  17 */ "CollSeq",
22584      /*  18 */ "Function",
22585      /*  19 */ "Not",
22586      /*  20 */ "AddImm",
22587      /*  21 */ "MustBeInt",
22588      /*  22 */ "RealAffinity",
22589      /*  23 */ "Permutation",
22590      /*  24 */ "Compare",
22591      /*  25 */ "Jump",
22592      /*  26 */ "Once",
22593      /*  27 */ "If",
22594      /*  28 */ "IfNot",
22595      /*  29 */ "Column",
22596      /*  30 */ "Affinity",
22597      /*  31 */ "MakeRecord",
22598      /*  32 */ "Count",
22599      /*  33 */ "Savepoint",
22600      /*  34 */ "AutoCommit",
22601      /*  35 */ "Transaction",
22602      /*  36 */ "ReadCookie",
22603      /*  37 */ "SetCookie",
22604      /*  38 */ "VerifyCookie",
22605      /*  39 */ "OpenRead",
22606      /*  40 */ "OpenWrite",
22607      /*  41 */ "OpenAutoindex",
22608      /*  42 */ "OpenEphemeral",
22609      /*  43 */ "SorterOpen",
22610      /*  44 */ "OpenPseudo",
22611      /*  45 */ "Close",
22612      /*  46 */ "SeekLt",
22613      /*  47 */ "SeekLe",
22614      /*  48 */ "SeekGe",
22615      /*  49 */ "SeekGt",
22616      /*  50 */ "Seek",
22617      /*  51 */ "NotFound",
22618      /*  52 */ "Found",
22619      /*  53 */ "IsUnique",
22620      /*  54 */ "NotExists",
22621      /*  55 */ "Sequence",
22622      /*  56 */ "NewRowid",
22623      /*  57 */ "Insert",
22624      /*  58 */ "InsertInt",
22625      /*  59 */ "Delete",
22626      /*  60 */ "ResetCount",
22627      /*  61 */ "SorterCompare",
22628      /*  62 */ "SorterData",
22629      /*  63 */ "RowKey",
22630      /*  64 */ "RowData",
22631      /*  65 */ "Rowid",
22632      /*  66 */ "NullRow",
22633      /*  67 */ "Last",
22634      /*  68 */ "Or",
22635      /*  69 */ "And",
22636      /*  70 */ "SorterSort",
22637      /*  71 */ "Sort",
22638      /*  72 */ "Rewind",
22639      /*  73 */ "IsNull",
22640      /*  74 */ "NotNull",
22641      /*  75 */ "Ne",
22642      /*  76 */ "Eq",
22643      /*  77 */ "Gt",
22644      /*  78 */ "Le",
22645      /*  79 */ "Lt",
22646      /*  80 */ "Ge",
22647      /*  81 */ "SorterNext",
22648      /*  82 */ "BitAnd",
22649      /*  83 */ "BitOr",
22650      /*  84 */ "ShiftLeft",
22651      /*  85 */ "ShiftRight",
22652      /*  86 */ "Add",
22653      /*  87 */ "Subtract",
22654      /*  88 */ "Multiply",
22655      /*  89 */ "Divide",
22656      /*  90 */ "Remainder",
22657      /*  91 */ "Concat",
22658      /*  92 */ "Prev",
22659      /*  93 */ "BitNot",
22660      /*  94 */ "String8",
22661      /*  95 */ "Next",
22662      /*  96 */ "SorterInsert",
22663      /*  97 */ "IdxInsert",
22664      /*  98 */ "IdxDelete",
22665      /*  99 */ "IdxRowid",
22666      /* 100 */ "IdxLT",
22667      /* 101 */ "IdxGE",
22668      /* 102 */ "Destroy",
22669      /* 103 */ "Clear",
22670      /* 104 */ "CreateIndex",
22671      /* 105 */ "CreateTable",
22672      /* 106 */ "ParseSchema",
22673      /* 107 */ "LoadAnalysis",
22674      /* 108 */ "DropTable",
22675      /* 109 */ "DropIndex",
22676      /* 110 */ "DropTrigger",
22677      /* 111 */ "IntegrityCk",
22678      /* 112 */ "RowSetAdd",
22679      /* 113 */ "RowSetRead",
22680      /* 114 */ "RowSetTest",
22681      /* 115 */ "Program",
22682      /* 116 */ "Param",
22683      /* 117 */ "FkCounter",
22684      /* 118 */ "FkIfZero",
22685      /* 119 */ "MemMax",
22686      /* 120 */ "IfPos",
22687      /* 121 */ "IfNeg",
22688      /* 122 */ "IfZero",
22689      /* 123 */ "AggStep",
22690      /* 124 */ "AggFinal",
22691      /* 125 */ "Checkpoint",
22692      /* 126 */ "JournalMode",
22693      /* 127 */ "Vacuum",
22694      /* 128 */ "IncrVacuum",
22695      /* 129 */ "Expire",
22696      /* 130 */ "Real",
22697      /* 131 */ "TableLock",
22698      /* 132 */ "VBegin",
22699      /* 133 */ "VCreate",
22700      /* 134 */ "VDestroy",
22701      /* 135 */ "VOpen",
22702      /* 136 */ "VFilter",
22703      /* 137 */ "VColumn",
22704      /* 138 */ "VNext",
22705      /* 139 */ "VRename",
22706      /* 140 */ "VUpdate",
22707      /* 141 */ "ToText",
22708      /* 142 */ "ToBlob",
22709      /* 143 */ "ToNumeric",
22710      /* 144 */ "ToInt",
22711      /* 145 */ "ToReal",
22712      /* 146 */ "Pagecount",
22713      /* 147 */ "MaxPgcnt",
22714      /* 148 */ "Trace",
22715      /* 149 */ "Noop",
22716      /* 150 */ "Explain",
22717   };
22718   return azName[i];
22719 }
22720 #endif
22721
22722 /************** End of opcodes.c *********************************************/
22723 /************** Begin file os_unix.c *****************************************/
22724 /*
22725 ** 2004 May 22
22726 **
22727 ** The author disclaims copyright to this source code.  In place of
22728 ** a legal notice, here is a blessing:
22729 **
22730 **    May you do good and not evil.
22731 **    May you find forgiveness for yourself and forgive others.
22732 **    May you share freely, never taking more than you give.
22733 **
22734 ******************************************************************************
22735 **
22736 ** This file contains the VFS implementation for unix-like operating systems
22737 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22738 **
22739 ** There are actually several different VFS implementations in this file.
22740 ** The differences are in the way that file locking is done.  The default
22741 ** implementation uses Posix Advisory Locks.  Alternative implementations
22742 ** use flock(), dot-files, various proprietary locking schemas, or simply
22743 ** skip locking all together.
22744 **
22745 ** This source file is organized into divisions where the logic for various
22746 ** subfunctions is contained within the appropriate division.  PLEASE
22747 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22748 ** in the correct division and should be clearly labeled.
22749 **
22750 ** The layout of divisions is as follows:
22751 **
22752 **   *  General-purpose declarations and utility functions.
22753 **   *  Unique file ID logic used by VxWorks.
22754 **   *  Various locking primitive implementations (all except proxy locking):
22755 **      + for Posix Advisory Locks
22756 **      + for no-op locks
22757 **      + for dot-file locks
22758 **      + for flock() locking
22759 **      + for named semaphore locks (VxWorks only)
22760 **      + for AFP filesystem locks (MacOSX only)
22761 **   *  sqlite3_file methods not associated with locking.
22762 **   *  Definitions of sqlite3_io_methods objects for all locking
22763 **      methods plus "finder" functions for each locking method.
22764 **   *  sqlite3_vfs method implementations.
22765 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22766 **   *  Definitions of sqlite3_vfs objects for all locking methods
22767 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22768 */
22769 #if SQLITE_OS_UNIX              /* This file is used on unix only */
22770
22771 /* Use posix_fallocate() if it is available
22772 */
22773 #if !defined(HAVE_POSIX_FALLOCATE) \
22774       && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
22775 # define HAVE_POSIX_FALLOCATE 1
22776 #endif
22777
22778 #ifdef __UCLIBC__
22779   #undef HAVE_POSIX_FALLOCATE
22780 #endif
22781
22782 /*
22783 ** There are various methods for file locking used for concurrency
22784 ** control:
22785 **
22786 **   1. POSIX locking (the default),
22787 **   2. No locking,
22788 **   3. Dot-file locking,
22789 **   4. flock() locking,
22790 **   5. AFP locking (OSX only),
22791 **   6. Named POSIX semaphores (VXWorks only),
22792 **   7. proxy locking. (OSX only)
22793 **
22794 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22795 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22796 ** selection of the appropriate locking style based on the filesystem
22797 ** where the database is located.  
22798 */
22799 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22800 #  if defined(__APPLE__)
22801 #    define SQLITE_ENABLE_LOCKING_STYLE 1
22802 #  else
22803 #    define SQLITE_ENABLE_LOCKING_STYLE 0
22804 #  endif
22805 #endif
22806
22807 /*
22808 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
22809 ** vxworks, or 0 otherwise.
22810 */
22811 #ifndef OS_VXWORKS
22812 #  if defined(__RTP__) || defined(_WRS_KERNEL)
22813 #    define OS_VXWORKS 1
22814 #  else
22815 #    define OS_VXWORKS 0
22816 #  endif
22817 #endif
22818
22819 /*
22820 ** These #defines should enable >2GB file support on Posix if the
22821 ** underlying operating system supports it.  If the OS lacks
22822 ** large file support, these should be no-ops.
22823 **
22824 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22825 ** on the compiler command line.  This is necessary if you are compiling
22826 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
22827 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22828 ** without this option, LFS is enable.  But LFS does not exist in the kernel
22829 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22830 ** portability you should omit LFS.
22831 **
22832 ** The previous paragraph was written in 2005.  (This paragraph is written
22833 ** on 2008-11-28.) These days, all Linux kernels support large files, so
22834 ** you should probably leave LFS enabled.  But some embedded platforms might
22835 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22836 */
22837 #ifndef SQLITE_DISABLE_LFS
22838 # define _LARGE_FILE       1
22839 # ifndef _FILE_OFFSET_BITS
22840 #   define _FILE_OFFSET_BITS 64
22841 # endif
22842 # define _LARGEFILE_SOURCE 1
22843 #endif
22844
22845 /*
22846 ** standard include files.
22847 */
22848 #include <sys/types.h>
22849 #include <sys/stat.h>
22850 #include <fcntl.h>
22851 #include <unistd.h>
22852 /* #include <time.h> */
22853 #include <sys/time.h>
22854 #include <errno.h>
22855 #ifndef SQLITE_OMIT_WAL
22856 #include <sys/mman.h>
22857 #endif
22858
22859
22860 #if SQLITE_ENABLE_LOCKING_STYLE
22861 # include <sys/ioctl.h>
22862 # if OS_VXWORKS
22863 #  include <semaphore.h>
22864 #  include <limits.h>
22865 # else
22866 #  include <sys/file.h>
22867 #  include <sys/param.h>
22868 # endif
22869 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
22870
22871 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
22872 # include <sys/mount.h>
22873 #endif
22874
22875 #ifdef HAVE_UTIME
22876 # include <utime.h>
22877 #endif
22878
22879 /*
22880 ** Allowed values of unixFile.fsFlags
22881 */
22882 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
22883
22884 /*
22885 ** If we are to be thread-safe, include the pthreads header and define
22886 ** the SQLITE_UNIX_THREADS macro.
22887 */
22888 #if SQLITE_THREADSAFE
22889 /* # include <pthread.h> */
22890 # define SQLITE_UNIX_THREADS 1
22891 #endif
22892
22893 /*
22894 ** Default permissions when creating a new file
22895 */
22896 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
22897 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
22898 #endif
22899
22900 /*
22901 ** Default permissions when creating auto proxy dir
22902 */
22903 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
22904 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
22905 #endif
22906
22907 /*
22908 ** Maximum supported path-length.
22909 */
22910 #define MAX_PATHNAME 512
22911
22912 /*
22913 ** Only set the lastErrno if the error code is a real error and not 
22914 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22915 */
22916 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22917
22918 /* Forward references */
22919 typedef struct unixShm unixShm;               /* Connection shared memory */
22920 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
22921 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
22922 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
22923
22924 /*
22925 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
22926 ** cannot be closed immediately. In these cases, instances of the following
22927 ** structure are used to store the file descriptor while waiting for an
22928 ** opportunity to either close or reuse it.
22929 */
22930 struct UnixUnusedFd {
22931   int fd;                   /* File descriptor to close */
22932   int flags;                /* Flags this file descriptor was opened with */
22933   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
22934 };
22935
22936 /*
22937 ** The unixFile structure is subclass of sqlite3_file specific to the unix
22938 ** VFS implementations.
22939 */
22940 typedef struct unixFile unixFile;
22941 struct unixFile {
22942   sqlite3_io_methods const *pMethod;  /* Always the first entry */
22943   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
22944   unixInodeInfo *pInode;              /* Info about locks on this inode */
22945   int h;                              /* The file descriptor */
22946   unsigned char eFileLock;            /* The type of lock held on this fd */
22947   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
22948   int lastErrno;                      /* The unix errno from last I/O error */
22949   void *lockingContext;               /* Locking style specific state */
22950   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
22951   const char *zPath;                  /* Name of the file */
22952   unixShm *pShm;                      /* Shared memory segment information */
22953   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
22954 #ifdef __QNXNTO__
22955   int sectorSize;                     /* Device sector size */
22956   int deviceCharacteristics;          /* Precomputed device characteristics */
22957 #endif
22958 #if SQLITE_ENABLE_LOCKING_STYLE
22959   int openFlags;                      /* The flags specified at open() */
22960 #endif
22961 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
22962   unsigned fsFlags;                   /* cached details from statfs() */
22963 #endif
22964 #if OS_VXWORKS
22965   struct vxworksFileId *pId;          /* Unique file ID */
22966 #endif
22967 #ifdef SQLITE_DEBUG
22968   /* The next group of variables are used to track whether or not the
22969   ** transaction counter in bytes 24-27 of database files are updated
22970   ** whenever any part of the database changes.  An assertion fault will
22971   ** occur if a file is updated without also updating the transaction
22972   ** counter.  This test is made to avoid new problems similar to the
22973   ** one described by ticket #3584. 
22974   */
22975   unsigned char transCntrChng;   /* True if the transaction counter changed */
22976   unsigned char dbUpdate;        /* True if any part of database file changed */
22977   unsigned char inNormalWrite;   /* True if in a normal write operation */
22978 #endif
22979 #ifdef SQLITE_TEST
22980   /* In test mode, increase the size of this structure a bit so that 
22981   ** it is larger than the struct CrashFile defined in test6.c.
22982   */
22983   char aPadding[32];
22984 #endif
22985 };
22986
22987 /*
22988 ** Allowed values for the unixFile.ctrlFlags bitmask:
22989 */
22990 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
22991 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
22992 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
22993 #ifndef SQLITE_DISABLE_DIRSYNC
22994 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
22995 #else
22996 # define UNIXFILE_DIRSYNC    0x00
22997 #endif
22998 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
22999 #define UNIXFILE_DELETE      0x20     /* Delete on close */
23000 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
23001 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
23002
23003 /*
23004 ** Include code that is common to all os_*.c files
23005 */
23006 /************** Include os_common.h in the middle of os_unix.c ***************/
23007 /************** Begin file os_common.h ***************************************/
23008 /*
23009 ** 2004 May 22
23010 **
23011 ** The author disclaims copyright to this source code.  In place of
23012 ** a legal notice, here is a blessing:
23013 **
23014 **    May you do good and not evil.
23015 **    May you find forgiveness for yourself and forgive others.
23016 **    May you share freely, never taking more than you give.
23017 **
23018 ******************************************************************************
23019 **
23020 ** This file contains macros and a little bit of code that is common to
23021 ** all of the platform-specific files (os_*.c) and is #included into those
23022 ** files.
23023 **
23024 ** This file should be #included by the os_*.c files only.  It is not a
23025 ** general purpose header file.
23026 */
23027 #ifndef _OS_COMMON_H_
23028 #define _OS_COMMON_H_
23029
23030 /*
23031 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23032 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23033 ** switch.  The following code should catch this problem at compile-time.
23034 */
23035 #ifdef MEMORY_DEBUG
23036 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
23037 #endif
23038
23039 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23040 # ifndef SQLITE_DEBUG_OS_TRACE
23041 #   define SQLITE_DEBUG_OS_TRACE 0
23042 # endif
23043   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
23044 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
23045 #else
23046 # define OSTRACE(X)
23047 #endif
23048
23049 /*
23050 ** Macros for performance tracing.  Normally turned off.  Only works
23051 ** on i486 hardware.
23052 */
23053 #ifdef SQLITE_PERFORMANCE_TRACE
23054
23055 /* 
23056 ** hwtime.h contains inline assembler code for implementing 
23057 ** high-performance timing routines.
23058 */
23059 /************** Include hwtime.h in the middle of os_common.h ****************/
23060 /************** Begin file hwtime.h ******************************************/
23061 /*
23062 ** 2008 May 27
23063 **
23064 ** The author disclaims copyright to this source code.  In place of
23065 ** a legal notice, here is a blessing:
23066 **
23067 **    May you do good and not evil.
23068 **    May you find forgiveness for yourself and forgive others.
23069 **    May you share freely, never taking more than you give.
23070 **
23071 ******************************************************************************
23072 **
23073 ** This file contains inline asm code for retrieving "high-performance"
23074 ** counters for x86 class CPUs.
23075 */
23076 #ifndef _HWTIME_H_
23077 #define _HWTIME_H_
23078
23079 /*
23080 ** The following routine only works on pentium-class (or newer) processors.
23081 ** It uses the RDTSC opcode to read the cycle count value out of the
23082 ** processor and returns that value.  This can be used for high-res
23083 ** profiling.
23084 */
23085 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23086       (defined(i386) || defined(__i386__) || defined(_M_IX86))
23087
23088   #if defined(__GNUC__)
23089
23090   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23091      unsigned int lo, hi;
23092      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23093      return (sqlite_uint64)hi << 32 | lo;
23094   }
23095
23096   #elif defined(_MSC_VER)
23097
23098   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23099      __asm {
23100         rdtsc
23101         ret       ; return value at EDX:EAX
23102      }
23103   }
23104
23105   #endif
23106
23107 #elif (defined(__GNUC__) && defined(__x86_64__))
23108
23109   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23110       unsigned long val;
23111       __asm__ __volatile__ ("rdtsc" : "=A" (val));
23112       return val;
23113   }
23114  
23115 #elif (defined(__GNUC__) && defined(__ppc__))
23116
23117   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23118       unsigned long long retval;
23119       unsigned long junk;
23120       __asm__ __volatile__ ("\n\
23121           1:      mftbu   %1\n\
23122                   mftb    %L0\n\
23123                   mftbu   %0\n\
23124                   cmpw    %0,%1\n\
23125                   bne     1b"
23126                   : "=r" (retval), "=r" (junk));
23127       return retval;
23128   }
23129
23130 #else
23131
23132   #error Need implementation of sqlite3Hwtime() for your platform.
23133
23134   /*
23135   ** To compile without implementing sqlite3Hwtime() for your platform,
23136   ** you can remove the above #error and use the following
23137   ** stub function.  You will lose timing support for many
23138   ** of the debugging and testing utilities, but it should at
23139   ** least compile and run.
23140   */
23141 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23142
23143 #endif
23144
23145 #endif /* !defined(_HWTIME_H_) */
23146
23147 /************** End of hwtime.h **********************************************/
23148 /************** Continuing where we left off in os_common.h ******************/
23149
23150 static sqlite_uint64 g_start;
23151 static sqlite_uint64 g_elapsed;
23152 #define TIMER_START       g_start=sqlite3Hwtime()
23153 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
23154 #define TIMER_ELAPSED     g_elapsed
23155 #else
23156 #define TIMER_START
23157 #define TIMER_END
23158 #define TIMER_ELAPSED     ((sqlite_uint64)0)
23159 #endif
23160
23161 /*
23162 ** If we compile with the SQLITE_TEST macro set, then the following block
23163 ** of code will give us the ability to simulate a disk I/O error.  This
23164 ** is used for testing the I/O recovery logic.
23165 */
23166 #ifdef SQLITE_TEST
23167 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
23168 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
23169 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
23170 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
23171 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
23172 SQLITE_API int sqlite3_diskfull_pending = 0;
23173 SQLITE_API int sqlite3_diskfull = 0;
23174 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23175 #define SimulateIOError(CODE)  \
23176   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23177        || sqlite3_io_error_pending-- == 1 )  \
23178               { local_ioerr(); CODE; }
23179 static void local_ioerr(){
23180   IOTRACE(("IOERR\n"));
23181   sqlite3_io_error_hit++;
23182   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23183 }
23184 #define SimulateDiskfullError(CODE) \
23185    if( sqlite3_diskfull_pending ){ \
23186      if( sqlite3_diskfull_pending == 1 ){ \
23187        local_ioerr(); \
23188        sqlite3_diskfull = 1; \
23189        sqlite3_io_error_hit = 1; \
23190        CODE; \
23191      }else{ \
23192        sqlite3_diskfull_pending--; \
23193      } \
23194    }
23195 #else
23196 #define SimulateIOErrorBenign(X)
23197 #define SimulateIOError(A)
23198 #define SimulateDiskfullError(A)
23199 #endif
23200
23201 /*
23202 ** When testing, keep a count of the number of open files.
23203 */
23204 #ifdef SQLITE_TEST
23205 SQLITE_API int sqlite3_open_file_count = 0;
23206 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
23207 #else
23208 #define OpenCounter(X)
23209 #endif
23210
23211 #endif /* !defined(_OS_COMMON_H_) */
23212
23213 /************** End of os_common.h *******************************************/
23214 /************** Continuing where we left off in os_unix.c ********************/
23215
23216 /*
23217 ** Define various macros that are missing from some systems.
23218 */
23219 #ifndef O_LARGEFILE
23220 # define O_LARGEFILE 0
23221 #endif
23222 #ifdef SQLITE_DISABLE_LFS
23223 # undef O_LARGEFILE
23224 # define O_LARGEFILE 0
23225 #endif
23226 #ifndef O_NOFOLLOW
23227 # define O_NOFOLLOW 0
23228 #endif
23229 #ifndef O_BINARY
23230 # define O_BINARY 0
23231 #endif
23232
23233 /*
23234 ** The threadid macro resolves to the thread-id or to 0.  Used for
23235 ** testing and debugging only.
23236 */
23237 #if SQLITE_THREADSAFE
23238 #define threadid pthread_self()
23239 #else
23240 #define threadid 0
23241 #endif
23242
23243 /*
23244 ** Different Unix systems declare open() in different ways.  Same use
23245 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
23246 ** The difference is important when using a pointer to the function.
23247 **
23248 ** The safest way to deal with the problem is to always use this wrapper
23249 ** which always has the same well-defined interface.
23250 */
23251 static int posixOpen(const char *zFile, int flags, int mode){
23252   return open(zFile, flags, mode);
23253 }
23254
23255 /*
23256 ** On some systems, calls to fchown() will trigger a message in a security
23257 ** log if they come from non-root processes.  So avoid calling fchown() if
23258 ** we are not running as root.
23259 */
23260 static int posixFchown(int fd, uid_t uid, gid_t gid){
23261   return geteuid() ? 0 : fchown(fd,uid,gid);
23262 }
23263
23264 /* Forward reference */
23265 static int openDirectory(const char*, int*);
23266
23267 /*
23268 ** Many system calls are accessed through pointer-to-functions so that
23269 ** they may be overridden at runtime to facilitate fault injection during
23270 ** testing and sandboxing.  The following array holds the names and pointers
23271 ** to all overrideable system calls.
23272 */
23273 static struct unix_syscall {
23274   const char *zName;            /* Name of the system call */
23275   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
23276   sqlite3_syscall_ptr pDefault; /* Default value */
23277 } aSyscall[] = {
23278   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
23279 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
23280
23281   { "close",        (sqlite3_syscall_ptr)close,      0  },
23282 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
23283
23284   { "access",       (sqlite3_syscall_ptr)access,     0  },
23285 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
23286
23287   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
23288 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
23289
23290   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
23291 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
23292
23293 /*
23294 ** The DJGPP compiler environment looks mostly like Unix, but it
23295 ** lacks the fcntl() system call.  So redefine fcntl() to be something
23296 ** that always succeeds.  This means that locking does not occur under
23297 ** DJGPP.  But it is DOS - what did you expect?
23298 */
23299 #ifdef __DJGPP__
23300   { "fstat",        0,                 0  },
23301 #define osFstat(a,b,c)    0
23302 #else     
23303   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
23304 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
23305 #endif
23306
23307   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
23308 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
23309
23310   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
23311 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
23312
23313   { "read",         (sqlite3_syscall_ptr)read,       0  },
23314 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
23315
23316 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23317   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
23318 #else
23319   { "pread",        (sqlite3_syscall_ptr)0,          0  },
23320 #endif
23321 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
23322
23323 #if defined(USE_PREAD64)
23324   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
23325 #else
23326   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
23327 #endif
23328 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
23329
23330   { "write",        (sqlite3_syscall_ptr)write,      0  },
23331 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
23332
23333 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23334   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
23335 #else
23336   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
23337 #endif
23338 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
23339                     aSyscall[12].pCurrent)
23340
23341 #if defined(USE_PREAD64)
23342   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
23343 #else
23344   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
23345 #endif
23346 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
23347                     aSyscall[13].pCurrent)
23348
23349   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
23350 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
23351
23352 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
23353   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
23354 #else
23355   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
23356 #endif
23357 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
23358
23359   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
23360 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
23361
23362   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
23363 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
23364
23365   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
23366 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
23367
23368   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
23369 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
23370
23371   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
23372 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
23373
23374 }; /* End of the overrideable system calls */
23375
23376 /*
23377 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
23378 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
23379 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
23380 ** system call named zName.
23381 */
23382 static int unixSetSystemCall(
23383   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
23384   const char *zName,            /* Name of system call to override */
23385   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
23386 ){
23387   unsigned int i;
23388   int rc = SQLITE_NOTFOUND;
23389
23390   UNUSED_PARAMETER(pNotUsed);
23391   if( zName==0 ){
23392     /* If no zName is given, restore all system calls to their default
23393     ** settings and return NULL
23394     */
23395     rc = SQLITE_OK;
23396     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23397       if( aSyscall[i].pDefault ){
23398         aSyscall[i].pCurrent = aSyscall[i].pDefault;
23399       }
23400     }
23401   }else{
23402     /* If zName is specified, operate on only the one system call
23403     ** specified.
23404     */
23405     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23406       if( strcmp(zName, aSyscall[i].zName)==0 ){
23407         if( aSyscall[i].pDefault==0 ){
23408           aSyscall[i].pDefault = aSyscall[i].pCurrent;
23409         }
23410         rc = SQLITE_OK;
23411         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
23412         aSyscall[i].pCurrent = pNewFunc;
23413         break;
23414       }
23415     }
23416   }
23417   return rc;
23418 }
23419
23420 /*
23421 ** Return the value of a system call.  Return NULL if zName is not a
23422 ** recognized system call name.  NULL is also returned if the system call
23423 ** is currently undefined.
23424 */
23425 static sqlite3_syscall_ptr unixGetSystemCall(
23426   sqlite3_vfs *pNotUsed,
23427   const char *zName
23428 ){
23429   unsigned int i;
23430
23431   UNUSED_PARAMETER(pNotUsed);
23432   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23433     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
23434   }
23435   return 0;
23436 }
23437
23438 /*
23439 ** Return the name of the first system call after zName.  If zName==NULL
23440 ** then return the name of the first system call.  Return NULL if zName
23441 ** is the last system call or if zName is not the name of a valid
23442 ** system call.
23443 */
23444 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
23445   int i = -1;
23446
23447   UNUSED_PARAMETER(p);
23448   if( zName ){
23449     for(i=0; i<ArraySize(aSyscall)-1; i++){
23450       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
23451     }
23452   }
23453   for(i++; i<ArraySize(aSyscall); i++){
23454     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
23455   }
23456   return 0;
23457 }
23458
23459 /*
23460 ** Invoke open().  Do so multiple times, until it either succeeds or
23461 ** fails for some reason other than EINTR.
23462 **
23463 ** If the file creation mode "m" is 0 then set it to the default for
23464 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
23465 ** 0644) as modified by the system umask.  If m is not 0, then
23466 ** make the file creation mode be exactly m ignoring the umask.
23467 **
23468 ** The m parameter will be non-zero only when creating -wal, -journal,
23469 ** and -shm files.  We want those files to have *exactly* the same
23470 ** permissions as their original database, unadulterated by the umask.
23471 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
23472 ** transaction crashes and leaves behind hot journals, then any
23473 ** process that is able to write to the database will also be able to
23474 ** recover the hot journals.
23475 */
23476 static int robust_open(const char *z, int f, mode_t m){
23477   int fd;
23478   mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
23479   do{
23480 #if defined(O_CLOEXEC)
23481     fd = osOpen(z,f|O_CLOEXEC,m2);
23482 #else
23483     fd = osOpen(z,f,m2);
23484 #endif
23485   }while( fd<0 && errno==EINTR );
23486   if( fd>=0 ){
23487     if( m!=0 ){
23488       struct stat statbuf;
23489       if( osFstat(fd, &statbuf)==0 
23490        && statbuf.st_size==0
23491        && (statbuf.st_mode&0777)!=m 
23492       ){
23493         osFchmod(fd, m);
23494       }
23495     }
23496 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
23497     osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
23498 #endif
23499   }
23500   return fd;
23501 }
23502
23503 /*
23504 ** Helper functions to obtain and relinquish the global mutex. The
23505 ** global mutex is used to protect the unixInodeInfo and
23506 ** vxworksFileId objects used by this file, all of which may be 
23507 ** shared by multiple threads.
23508 **
23509 ** Function unixMutexHeld() is used to assert() that the global mutex 
23510 ** is held when required. This function is only used as part of assert() 
23511 ** statements. e.g.
23512 **
23513 **   unixEnterMutex()
23514 **     assert( unixMutexHeld() );
23515 **   unixEnterLeave()
23516 */
23517 static void unixEnterMutex(void){
23518   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23519 }
23520 static void unixLeaveMutex(void){
23521   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23522 }
23523 #ifdef SQLITE_DEBUG
23524 static int unixMutexHeld(void) {
23525   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23526 }
23527 #endif
23528
23529
23530 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23531 /*
23532 ** Helper function for printing out trace information from debugging
23533 ** binaries. This returns the string represetation of the supplied
23534 ** integer lock-type.
23535 */
23536 static const char *azFileLock(int eFileLock){
23537   switch( eFileLock ){
23538     case NO_LOCK: return "NONE";
23539     case SHARED_LOCK: return "SHARED";
23540     case RESERVED_LOCK: return "RESERVED";
23541     case PENDING_LOCK: return "PENDING";
23542     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
23543   }
23544   return "ERROR";
23545 }
23546 #endif
23547
23548 #ifdef SQLITE_LOCK_TRACE
23549 /*
23550 ** Print out information about all locking operations.
23551 **
23552 ** This routine is used for troubleshooting locks on multithreaded
23553 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
23554 ** command-line option on the compiler.  This code is normally
23555 ** turned off.
23556 */
23557 static int lockTrace(int fd, int op, struct flock *p){
23558   char *zOpName, *zType;
23559   int s;
23560   int savedErrno;
23561   if( op==F_GETLK ){
23562     zOpName = "GETLK";
23563   }else if( op==F_SETLK ){
23564     zOpName = "SETLK";
23565   }else{
23566     s = osFcntl(fd, op, p);
23567     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
23568     return s;
23569   }
23570   if( p->l_type==F_RDLCK ){
23571     zType = "RDLCK";
23572   }else if( p->l_type==F_WRLCK ){
23573     zType = "WRLCK";
23574   }else if( p->l_type==F_UNLCK ){
23575     zType = "UNLCK";
23576   }else{
23577     assert( 0 );
23578   }
23579   assert( p->l_whence==SEEK_SET );
23580   s = osFcntl(fd, op, p);
23581   savedErrno = errno;
23582   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
23583      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
23584      (int)p->l_pid, s);
23585   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
23586     struct flock l2;
23587     l2 = *p;
23588     osFcntl(fd, F_GETLK, &l2);
23589     if( l2.l_type==F_RDLCK ){
23590       zType = "RDLCK";
23591     }else if( l2.l_type==F_WRLCK ){
23592       zType = "WRLCK";
23593     }else if( l2.l_type==F_UNLCK ){
23594       zType = "UNLCK";
23595     }else{
23596       assert( 0 );
23597     }
23598     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
23599        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
23600   }
23601   errno = savedErrno;
23602   return s;
23603 }
23604 #undef osFcntl
23605 #define osFcntl lockTrace
23606 #endif /* SQLITE_LOCK_TRACE */
23607
23608 /*
23609 ** Retry ftruncate() calls that fail due to EINTR
23610 */
23611 static int robust_ftruncate(int h, sqlite3_int64 sz){
23612   int rc;
23613   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
23614   return rc;
23615 }
23616
23617 /*
23618 ** This routine translates a standard POSIX errno code into something
23619 ** useful to the clients of the sqlite3 functions.  Specifically, it is
23620 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
23621 ** and a variety of "please close the file descriptor NOW" errors into 
23622 ** SQLITE_IOERR
23623 ** 
23624 ** Errors during initialization of locks, or file system support for locks,
23625 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
23626 */
23627 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
23628   switch (posixError) {
23629 #if 0
23630   /* At one point this code was not commented out. In theory, this branch
23631   ** should never be hit, as this function should only be called after
23632   ** a locking-related function (i.e. fcntl()) has returned non-zero with
23633   ** the value of errno as the first argument. Since a system call has failed,
23634   ** errno should be non-zero.
23635   **
23636   ** Despite this, if errno really is zero, we still don't want to return
23637   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
23638   ** propagated back to the caller. Commenting this branch out means errno==0
23639   ** will be handled by the "default:" case below.
23640   */
23641   case 0: 
23642     return SQLITE_OK;
23643 #endif
23644
23645   case EAGAIN:
23646   case ETIMEDOUT:
23647   case EBUSY:
23648   case EINTR:
23649   case ENOLCK:  
23650     /* random NFS retry error, unless during file system support 
23651      * introspection, in which it actually means what it says */
23652     return SQLITE_BUSY;
23653     
23654   case EACCES: 
23655     /* EACCES is like EAGAIN during locking operations, but not any other time*/
23656     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
23657         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
23658         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
23659         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
23660       return SQLITE_BUSY;
23661     }
23662     /* else fall through */
23663   case EPERM: 
23664     return SQLITE_PERM;
23665     
23666   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
23667   ** this module never makes such a call. And the code in SQLite itself 
23668   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
23669   ** this case is also commented out. If the system does set errno to EDEADLK,
23670   ** the default SQLITE_IOERR_XXX code will be returned. */
23671 #if 0
23672   case EDEADLK:
23673     return SQLITE_IOERR_BLOCKED;
23674 #endif
23675     
23676 #if EOPNOTSUPP!=ENOTSUP
23677   case EOPNOTSUPP: 
23678     /* something went terribly awry, unless during file system support 
23679      * introspection, in which it actually means what it says */
23680 #endif
23681 #ifdef ENOTSUP
23682   case ENOTSUP: 
23683     /* invalid fd, unless during file system support introspection, in which 
23684      * it actually means what it says */
23685 #endif
23686   case EIO:
23687   case EBADF:
23688   case EINVAL:
23689   case ENOTCONN:
23690   case ENODEV:
23691   case ENXIO:
23692   case ENOENT:
23693 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
23694   case ESTALE:
23695 #endif
23696   case ENOSYS:
23697     /* these should force the client to close the file and reconnect */
23698     
23699   default: 
23700     return sqliteIOErr;
23701   }
23702 }
23703
23704
23705
23706 /******************************************************************************
23707 ****************** Begin Unique File ID Utility Used By VxWorks ***************
23708 **
23709 ** On most versions of unix, we can get a unique ID for a file by concatenating
23710 ** the device number and the inode number.  But this does not work on VxWorks.
23711 ** On VxWorks, a unique file id must be based on the canonical filename.
23712 **
23713 ** A pointer to an instance of the following structure can be used as a
23714 ** unique file ID in VxWorks.  Each instance of this structure contains
23715 ** a copy of the canonical filename.  There is also a reference count.  
23716 ** The structure is reclaimed when the number of pointers to it drops to
23717 ** zero.
23718 **
23719 ** There are never very many files open at one time and lookups are not
23720 ** a performance-critical path, so it is sufficient to put these
23721 ** structures on a linked list.
23722 */
23723 struct vxworksFileId {
23724   struct vxworksFileId *pNext;  /* Next in a list of them all */
23725   int nRef;                     /* Number of references to this one */
23726   int nName;                    /* Length of the zCanonicalName[] string */
23727   char *zCanonicalName;         /* Canonical filename */
23728 };
23729
23730 #if OS_VXWORKS
23731 /* 
23732 ** All unique filenames are held on a linked list headed by this
23733 ** variable:
23734 */
23735 static struct vxworksFileId *vxworksFileList = 0;
23736
23737 /*
23738 ** Simplify a filename into its canonical form
23739 ** by making the following changes:
23740 **
23741 **  * removing any trailing and duplicate /
23742 **  * convert /./ into just /
23743 **  * convert /A/../ where A is any simple name into just /
23744 **
23745 ** Changes are made in-place.  Return the new name length.
23746 **
23747 ** The original filename is in z[0..n-1].  Return the number of
23748 ** characters in the simplified name.
23749 */
23750 static int vxworksSimplifyName(char *z, int n){
23751   int i, j;
23752   while( n>1 && z[n-1]=='/' ){ n--; }
23753   for(i=j=0; i<n; i++){
23754     if( z[i]=='/' ){
23755       if( z[i+1]=='/' ) continue;
23756       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
23757         i += 1;
23758         continue;
23759       }
23760       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
23761         while( j>0 && z[j-1]!='/' ){ j--; }
23762         if( j>0 ){ j--; }
23763         i += 2;
23764         continue;
23765       }
23766     }
23767     z[j++] = z[i];
23768   }
23769   z[j] = 0;
23770   return j;
23771 }
23772
23773 /*
23774 ** Find a unique file ID for the given absolute pathname.  Return
23775 ** a pointer to the vxworksFileId object.  This pointer is the unique
23776 ** file ID.
23777 **
23778 ** The nRef field of the vxworksFileId object is incremented before
23779 ** the object is returned.  A new vxworksFileId object is created
23780 ** and added to the global list if necessary.
23781 **
23782 ** If a memory allocation error occurs, return NULL.
23783 */
23784 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
23785   struct vxworksFileId *pNew;         /* search key and new file ID */
23786   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
23787   int n;                              /* Length of zAbsoluteName string */
23788
23789   assert( zAbsoluteName[0]=='/' );
23790   n = (int)strlen(zAbsoluteName);
23791   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
23792   if( pNew==0 ) return 0;
23793   pNew->zCanonicalName = (char*)&pNew[1];
23794   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23795   n = vxworksSimplifyName(pNew->zCanonicalName, n);
23796
23797   /* Search for an existing entry that matching the canonical name.
23798   ** If found, increment the reference count and return a pointer to
23799   ** the existing file ID.
23800   */
23801   unixEnterMutex();
23802   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23803     if( pCandidate->nName==n 
23804      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23805     ){
23806        sqlite3_free(pNew);
23807        pCandidate->nRef++;
23808        unixLeaveMutex();
23809        return pCandidate;
23810     }
23811   }
23812
23813   /* No match was found.  We will make a new file ID */
23814   pNew->nRef = 1;
23815   pNew->nName = n;
23816   pNew->pNext = vxworksFileList;
23817   vxworksFileList = pNew;
23818   unixLeaveMutex();
23819   return pNew;
23820 }
23821
23822 /*
23823 ** Decrement the reference count on a vxworksFileId object.  Free
23824 ** the object when the reference count reaches zero.
23825 */
23826 static void vxworksReleaseFileId(struct vxworksFileId *pId){
23827   unixEnterMutex();
23828   assert( pId->nRef>0 );
23829   pId->nRef--;
23830   if( pId->nRef==0 ){
23831     struct vxworksFileId **pp;
23832     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
23833     assert( *pp==pId );
23834     *pp = pId->pNext;
23835     sqlite3_free(pId);
23836   }
23837   unixLeaveMutex();
23838 }
23839 #endif /* OS_VXWORKS */
23840 /*************** End of Unique File ID Utility Used By VxWorks ****************
23841 ******************************************************************************/
23842
23843
23844 /******************************************************************************
23845 *************************** Posix Advisory Locking ****************************
23846 **
23847 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
23848 ** section 6.5.2.2 lines 483 through 490 specify that when a process
23849 ** sets or clears a lock, that operation overrides any prior locks set
23850 ** by the same process.  It does not explicitly say so, but this implies
23851 ** that it overrides locks set by the same process using a different
23852 ** file descriptor.  Consider this test case:
23853 **
23854 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
23855 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
23856 **
23857 ** Suppose ./file1 and ./file2 are really the same file (because
23858 ** one is a hard or symbolic link to the other) then if you set
23859 ** an exclusive lock on fd1, then try to get an exclusive lock
23860 ** on fd2, it works.  I would have expected the second lock to
23861 ** fail since there was already a lock on the file due to fd1.
23862 ** But not so.  Since both locks came from the same process, the
23863 ** second overrides the first, even though they were on different
23864 ** file descriptors opened on different file names.
23865 **
23866 ** This means that we cannot use POSIX locks to synchronize file access
23867 ** among competing threads of the same process.  POSIX locks will work fine
23868 ** to synchronize access for threads in separate processes, but not
23869 ** threads within the same process.
23870 **
23871 ** To work around the problem, SQLite has to manage file locks internally
23872 ** on its own.  Whenever a new database is opened, we have to find the
23873 ** specific inode of the database file (the inode is determined by the
23874 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
23875 ** and check for locks already existing on that inode.  When locks are
23876 ** created or removed, we have to look at our own internal record of the
23877 ** locks to see if another thread has previously set a lock on that same
23878 ** inode.
23879 **
23880 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
23881 ** For VxWorks, we have to use the alternative unique ID system based on
23882 ** canonical filename and implemented in the previous division.)
23883 **
23884 ** The sqlite3_file structure for POSIX is no longer just an integer file
23885 ** descriptor.  It is now a structure that holds the integer file
23886 ** descriptor and a pointer to a structure that describes the internal
23887 ** locks on the corresponding inode.  There is one locking structure
23888 ** per inode, so if the same inode is opened twice, both unixFile structures
23889 ** point to the same locking structure.  The locking structure keeps
23890 ** a reference count (so we will know when to delete it) and a "cnt"
23891 ** field that tells us its internal lock status.  cnt==0 means the
23892 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
23893 ** cnt>0 means there are cnt shared locks on the file.
23894 **
23895 ** Any attempt to lock or unlock a file first checks the locking
23896 ** structure.  The fcntl() system call is only invoked to set a 
23897 ** POSIX lock if the internal lock structure transitions between
23898 ** a locked and an unlocked state.
23899 **
23900 ** But wait:  there are yet more problems with POSIX advisory locks.
23901 **
23902 ** If you close a file descriptor that points to a file that has locks,
23903 ** all locks on that file that are owned by the current process are
23904 ** released.  To work around this problem, each unixInodeInfo object
23905 ** maintains a count of the number of pending locks on tha inode.
23906 ** When an attempt is made to close an unixFile, if there are
23907 ** other unixFile open on the same inode that are holding locks, the call
23908 ** to close() the file descriptor is deferred until all of the locks clear.
23909 ** The unixInodeInfo structure keeps a list of file descriptors that need to
23910 ** be closed and that list is walked (and cleared) when the last lock
23911 ** clears.
23912 **
23913 ** Yet another problem:  LinuxThreads do not play well with posix locks.
23914 **
23915 ** Many older versions of linux use the LinuxThreads library which is
23916 ** not posix compliant.  Under LinuxThreads, a lock created by thread
23917 ** A cannot be modified or overridden by a different thread B.
23918 ** Only thread A can modify the lock.  Locking behavior is correct
23919 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
23920 ** on linux - with NPTL a lock created by thread A can override locks
23921 ** in thread B.  But there is no way to know at compile-time which
23922 ** threading library is being used.  So there is no way to know at
23923 ** compile-time whether or not thread A can override locks on thread B.
23924 ** One has to do a run-time check to discover the behavior of the
23925 ** current process.
23926 **
23927 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
23928 ** was dropped beginning with version 3.7.0.  SQLite will still work with
23929 ** LinuxThreads provided that (1) there is no more than one connection 
23930 ** per database file in the same process and (2) database connections
23931 ** do not move across threads.
23932 */
23933
23934 /*
23935 ** An instance of the following structure serves as the key used
23936 ** to locate a particular unixInodeInfo object.
23937 */
23938 struct unixFileId {
23939   dev_t dev;                  /* Device number */
23940 #if OS_VXWORKS
23941   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
23942 #else
23943   ino_t ino;                  /* Inode number */
23944 #endif
23945 };
23946
23947 /*
23948 ** An instance of the following structure is allocated for each open
23949 ** inode.  Or, on LinuxThreads, there is one of these structures for
23950 ** each inode opened by each thread.
23951 **
23952 ** A single inode can have multiple file descriptors, so each unixFile
23953 ** structure contains a pointer to an instance of this object and this
23954 ** object keeps a count of the number of unixFile pointing to it.
23955 */
23956 struct unixInodeInfo {
23957   struct unixFileId fileId;       /* The lookup key */
23958   int nShared;                    /* Number of SHARED locks held */
23959   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
23960   unsigned char bProcessLock;     /* An exclusive process lock is held */
23961   int nRef;                       /* Number of pointers to this structure */
23962   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
23963   int nLock;                      /* Number of outstanding file locks */
23964   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
23965   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
23966   unixInodeInfo *pPrev;           /*    .... doubly linked */
23967 #if SQLITE_ENABLE_LOCKING_STYLE
23968   unsigned long long sharedByte;  /* for AFP simulated shared lock */
23969 #endif
23970 #if OS_VXWORKS
23971   sem_t *pSem;                    /* Named POSIX semaphore */
23972   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
23973 #endif
23974 };
23975
23976 /*
23977 ** A lists of all unixInodeInfo objects.
23978 */
23979 static unixInodeInfo *inodeList = 0;
23980
23981 /*
23982 **
23983 ** This function - unixLogError_x(), is only ever called via the macro
23984 ** unixLogError().
23985 **
23986 ** It is invoked after an error occurs in an OS function and errno has been
23987 ** set. It logs a message using sqlite3_log() containing the current value of
23988 ** errno and, if possible, the human-readable equivalent from strerror() or
23989 ** strerror_r().
23990 **
23991 ** The first argument passed to the macro should be the error code that
23992 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
23993 ** The two subsequent arguments should be the name of the OS function that
23994 ** failed (e.g. "unlink", "open") and the associated file-system path,
23995 ** if any.
23996 */
23997 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
23998 static int unixLogErrorAtLine(
23999   int errcode,                    /* SQLite error code */
24000   const char *zFunc,              /* Name of OS function that failed */
24001   const char *zPath,              /* File path associated with error */
24002   int iLine                       /* Source line number where error occurred */
24003 ){
24004   char *zErr;                     /* Message from strerror() or equivalent */
24005   int iErrno = errno;             /* Saved syscall error number */
24006
24007   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
24008   ** the strerror() function to obtain the human-readable error message
24009   ** equivalent to errno. Otherwise, use strerror_r().
24010   */ 
24011 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
24012   char aErr[80];
24013   memset(aErr, 0, sizeof(aErr));
24014   zErr = aErr;
24015
24016   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
24017   ** assume that the system provides the GNU version of strerror_r() that
24018   ** returns a pointer to a buffer containing the error message. That pointer 
24019   ** may point to aErr[], or it may point to some static storage somewhere. 
24020   ** Otherwise, assume that the system provides the POSIX version of 
24021   ** strerror_r(), which always writes an error message into aErr[].
24022   **
24023   ** If the code incorrectly assumes that it is the POSIX version that is
24024   ** available, the error message will often be an empty string. Not a
24025   ** huge problem. Incorrectly concluding that the GNU version is available 
24026   ** could lead to a segfault though.
24027   */
24028 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
24029   zErr = 
24030 # endif
24031   strerror_r(iErrno, aErr, sizeof(aErr)-1);
24032
24033 #elif SQLITE_THREADSAFE
24034   /* This is a threadsafe build, but strerror_r() is not available. */
24035   zErr = "";
24036 #else
24037   /* Non-threadsafe build, use strerror(). */
24038   zErr = strerror(iErrno);
24039 #endif
24040
24041   assert( errcode!=SQLITE_OK );
24042   if( zPath==0 ) zPath = "";
24043   sqlite3_log(errcode,
24044       "os_unix.c:%d: (%d) %s(%s) - %s",
24045       iLine, iErrno, zFunc, zPath, zErr
24046   );
24047
24048   return errcode;
24049 }
24050
24051 /*
24052 ** Close a file descriptor.
24053 **
24054 ** We assume that close() almost always works, since it is only in a
24055 ** very sick application or on a very sick platform that it might fail.
24056 ** If it does fail, simply leak the file descriptor, but do log the
24057 ** error.
24058 **
24059 ** Note that it is not safe to retry close() after EINTR since the
24060 ** file descriptor might have already been reused by another thread.
24061 ** So we don't even try to recover from an EINTR.  Just log the error
24062 ** and move on.
24063 */
24064 static void robust_close(unixFile *pFile, int h, int lineno){
24065   if( osClose(h) ){
24066     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
24067                        pFile ? pFile->zPath : 0, lineno);
24068   }
24069 }
24070
24071 /*
24072 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
24073 */ 
24074 static void closePendingFds(unixFile *pFile){
24075   unixInodeInfo *pInode = pFile->pInode;
24076   UnixUnusedFd *p;
24077   UnixUnusedFd *pNext;
24078   for(p=pInode->pUnused; p; p=pNext){
24079     pNext = p->pNext;
24080     robust_close(pFile, p->fd, __LINE__);
24081     sqlite3_free(p);
24082   }
24083   pInode->pUnused = 0;
24084 }
24085
24086 /*
24087 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
24088 **
24089 ** The mutex entered using the unixEnterMutex() function must be held
24090 ** when this function is called.
24091 */
24092 static void releaseInodeInfo(unixFile *pFile){
24093   unixInodeInfo *pInode = pFile->pInode;
24094   assert( unixMutexHeld() );
24095   if( ALWAYS(pInode) ){
24096     pInode->nRef--;
24097     if( pInode->nRef==0 ){
24098       assert( pInode->pShmNode==0 );
24099       closePendingFds(pFile);
24100       if( pInode->pPrev ){
24101         assert( pInode->pPrev->pNext==pInode );
24102         pInode->pPrev->pNext = pInode->pNext;
24103       }else{
24104         assert( inodeList==pInode );
24105         inodeList = pInode->pNext;
24106       }
24107       if( pInode->pNext ){
24108         assert( pInode->pNext->pPrev==pInode );
24109         pInode->pNext->pPrev = pInode->pPrev;
24110       }
24111       sqlite3_free(pInode);
24112     }
24113   }
24114 }
24115
24116 /*
24117 ** Given a file descriptor, locate the unixInodeInfo object that
24118 ** describes that file descriptor.  Create a new one if necessary.  The
24119 ** return value might be uninitialized if an error occurs.
24120 **
24121 ** The mutex entered using the unixEnterMutex() function must be held
24122 ** when this function is called.
24123 **
24124 ** Return an appropriate error code.
24125 */
24126 static int findInodeInfo(
24127   unixFile *pFile,               /* Unix file with file desc used in the key */
24128   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
24129 ){
24130   int rc;                        /* System call return code */
24131   int fd;                        /* The file descriptor for pFile */
24132   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
24133   struct stat statbuf;           /* Low-level file information */
24134   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
24135
24136   assert( unixMutexHeld() );
24137
24138   /* Get low-level information about the file that we can used to
24139   ** create a unique name for the file.
24140   */
24141   fd = pFile->h;
24142   rc = osFstat(fd, &statbuf);
24143   if( rc!=0 ){
24144     pFile->lastErrno = errno;
24145 #ifdef EOVERFLOW
24146     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
24147 #endif
24148     return SQLITE_IOERR;
24149   }
24150
24151 #ifdef __APPLE__
24152   /* On OS X on an msdos filesystem, the inode number is reported
24153   ** incorrectly for zero-size files.  See ticket #3260.  To work
24154   ** around this problem (we consider it a bug in OS X, not SQLite)
24155   ** we always increase the file size to 1 by writing a single byte
24156   ** prior to accessing the inode number.  The one byte written is
24157   ** an ASCII 'S' character which also happens to be the first byte
24158   ** in the header of every SQLite database.  In this way, if there
24159   ** is a race condition such that another thread has already populated
24160   ** the first page of the database, no damage is done.
24161   */
24162   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
24163     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
24164     if( rc!=1 ){
24165       pFile->lastErrno = errno;
24166       return SQLITE_IOERR;
24167     }
24168     rc = osFstat(fd, &statbuf);
24169     if( rc!=0 ){
24170       pFile->lastErrno = errno;
24171       return SQLITE_IOERR;
24172     }
24173   }
24174 #endif
24175
24176   memset(&fileId, 0, sizeof(fileId));
24177   fileId.dev = statbuf.st_dev;
24178 #if OS_VXWORKS
24179   fileId.pId = pFile->pId;
24180 #else
24181   fileId.ino = statbuf.st_ino;
24182 #endif
24183   pInode = inodeList;
24184   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
24185     pInode = pInode->pNext;
24186   }
24187   if( pInode==0 ){
24188     pInode = sqlite3_malloc( sizeof(*pInode) );
24189     if( pInode==0 ){
24190       return SQLITE_NOMEM;
24191     }
24192     memset(pInode, 0, sizeof(*pInode));
24193     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
24194     pInode->nRef = 1;
24195     pInode->pNext = inodeList;
24196     pInode->pPrev = 0;
24197     if( inodeList ) inodeList->pPrev = pInode;
24198     inodeList = pInode;
24199   }else{
24200     pInode->nRef++;
24201   }
24202   *ppInode = pInode;
24203   return SQLITE_OK;
24204 }
24205
24206
24207 /*
24208 ** This routine checks if there is a RESERVED lock held on the specified
24209 ** file by this or any other process. If such a lock is held, set *pResOut
24210 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24211 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24212 */
24213 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
24214   int rc = SQLITE_OK;
24215   int reserved = 0;
24216   unixFile *pFile = (unixFile*)id;
24217
24218   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24219
24220   assert( pFile );
24221   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24222
24223   /* Check if a thread in this process holds such a lock */
24224   if( pFile->pInode->eFileLock>SHARED_LOCK ){
24225     reserved = 1;
24226   }
24227
24228   /* Otherwise see if some other process holds it.
24229   */
24230 #ifndef __DJGPP__
24231   if( !reserved && !pFile->pInode->bProcessLock ){
24232     struct flock lock;
24233     lock.l_whence = SEEK_SET;
24234     lock.l_start = RESERVED_BYTE;
24235     lock.l_len = 1;
24236     lock.l_type = F_WRLCK;
24237     if( osFcntl(pFile->h, F_GETLK, &lock) ){
24238       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
24239       pFile->lastErrno = errno;
24240     } else if( lock.l_type!=F_UNLCK ){
24241       reserved = 1;
24242     }
24243   }
24244 #endif
24245   
24246   unixLeaveMutex();
24247   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
24248
24249   *pResOut = reserved;
24250   return rc;
24251 }
24252
24253 /*
24254 ** Attempt to set a system-lock on the file pFile.  The lock is 
24255 ** described by pLock.
24256 **
24257 ** If the pFile was opened read/write from unix-excl, then the only lock
24258 ** ever obtained is an exclusive lock, and it is obtained exactly once
24259 ** the first time any lock is attempted.  All subsequent system locking
24260 ** operations become no-ops.  Locking operations still happen internally,
24261 ** in order to coordinate access between separate database connections
24262 ** within this process, but all of that is handled in memory and the
24263 ** operating system does not participate.
24264 **
24265 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
24266 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
24267 ** and is read-only.
24268 **
24269 ** Zero is returned if the call completes successfully, or -1 if a call
24270 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
24271 */
24272 static int unixFileLock(unixFile *pFile, struct flock *pLock){
24273   int rc;
24274   unixInodeInfo *pInode = pFile->pInode;
24275   assert( unixMutexHeld() );
24276   assert( pInode!=0 );
24277   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
24278    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
24279   ){
24280     if( pInode->bProcessLock==0 ){
24281       struct flock lock;
24282       assert( pInode->nLock==0 );
24283       lock.l_whence = SEEK_SET;
24284       lock.l_start = SHARED_FIRST;
24285       lock.l_len = SHARED_SIZE;
24286       lock.l_type = F_WRLCK;
24287       rc = osFcntl(pFile->h, F_SETLK, &lock);
24288       if( rc<0 ) return rc;
24289       pInode->bProcessLock = 1;
24290       pInode->nLock++;
24291     }else{
24292       rc = 0;
24293     }
24294   }else{
24295     rc = osFcntl(pFile->h, F_SETLK, pLock);
24296   }
24297   return rc;
24298 }
24299
24300 /*
24301 ** Lock the file with the lock specified by parameter eFileLock - one
24302 ** of the following:
24303 **
24304 **     (1) SHARED_LOCK
24305 **     (2) RESERVED_LOCK
24306 **     (3) PENDING_LOCK
24307 **     (4) EXCLUSIVE_LOCK
24308 **
24309 ** Sometimes when requesting one lock state, additional lock states
24310 ** are inserted in between.  The locking might fail on one of the later
24311 ** transitions leaving the lock state different from what it started but
24312 ** still short of its goal.  The following chart shows the allowed
24313 ** transitions and the inserted intermediate states:
24314 **
24315 **    UNLOCKED -> SHARED
24316 **    SHARED -> RESERVED
24317 **    SHARED -> (PENDING) -> EXCLUSIVE
24318 **    RESERVED -> (PENDING) -> EXCLUSIVE
24319 **    PENDING -> EXCLUSIVE
24320 **
24321 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24322 ** routine to lower a locking level.
24323 */
24324 static int unixLock(sqlite3_file *id, int eFileLock){
24325   /* The following describes the implementation of the various locks and
24326   ** lock transitions in terms of the POSIX advisory shared and exclusive
24327   ** lock primitives (called read-locks and write-locks below, to avoid
24328   ** confusion with SQLite lock names). The algorithms are complicated
24329   ** slightly in order to be compatible with windows systems simultaneously
24330   ** accessing the same database file, in case that is ever required.
24331   **
24332   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
24333   ** byte', each single bytes at well known offsets, and the 'shared byte
24334   ** range', a range of 510 bytes at a well known offset.
24335   **
24336   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
24337   ** byte'.  If this is successful, a random byte from the 'shared byte
24338   ** range' is read-locked and the lock on the 'pending byte' released.
24339   **
24340   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
24341   ** A RESERVED lock is implemented by grabbing a write-lock on the
24342   ** 'reserved byte'. 
24343   **
24344   ** A process may only obtain a PENDING lock after it has obtained a
24345   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
24346   ** on the 'pending byte'. This ensures that no new SHARED locks can be
24347   ** obtained, but existing SHARED locks are allowed to persist. A process
24348   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
24349   ** This property is used by the algorithm for rolling back a journal file
24350   ** after a crash.
24351   **
24352   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
24353   ** implemented by obtaining a write-lock on the entire 'shared byte
24354   ** range'. Since all other locks require a read-lock on one of the bytes
24355   ** within this range, this ensures that no other locks are held on the
24356   ** database. 
24357   **
24358   ** The reason a single byte cannot be used instead of the 'shared byte
24359   ** range' is that some versions of windows do not support read-locks. By
24360   ** locking a random byte from a range, concurrent SHARED locks may exist
24361   ** even if the locking primitive used is always a write-lock.
24362   */
24363   int rc = SQLITE_OK;
24364   unixFile *pFile = (unixFile*)id;
24365   unixInodeInfo *pInode;
24366   struct flock lock;
24367   int tErrno = 0;
24368
24369   assert( pFile );
24370   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
24371       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24372       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
24373
24374   /* If there is already a lock of this type or more restrictive on the
24375   ** unixFile, do nothing. Don't use the end_lock: exit path, as
24376   ** unixEnterMutex() hasn't been called yet.
24377   */
24378   if( pFile->eFileLock>=eFileLock ){
24379     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
24380             azFileLock(eFileLock)));
24381     return SQLITE_OK;
24382   }
24383
24384   /* Make sure the locking sequence is correct.
24385   **  (1) We never move from unlocked to anything higher than shared lock.
24386   **  (2) SQLite never explicitly requests a pendig lock.
24387   **  (3) A shared lock is always held when a reserve lock is requested.
24388   */
24389   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24390   assert( eFileLock!=PENDING_LOCK );
24391   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24392
24393   /* This mutex is needed because pFile->pInode is shared across threads
24394   */
24395   unixEnterMutex();
24396   pInode = pFile->pInode;
24397
24398   /* If some thread using this PID has a lock via a different unixFile*
24399   ** handle that precludes the requested lock, return BUSY.
24400   */
24401   if( (pFile->eFileLock!=pInode->eFileLock && 
24402           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24403   ){
24404     rc = SQLITE_BUSY;
24405     goto end_lock;
24406   }
24407
24408   /* If a SHARED lock is requested, and some thread using this PID already
24409   ** has a SHARED or RESERVED lock, then increment reference counts and
24410   ** return SQLITE_OK.
24411   */
24412   if( eFileLock==SHARED_LOCK && 
24413       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24414     assert( eFileLock==SHARED_LOCK );
24415     assert( pFile->eFileLock==0 );
24416     assert( pInode->nShared>0 );
24417     pFile->eFileLock = SHARED_LOCK;
24418     pInode->nShared++;
24419     pInode->nLock++;
24420     goto end_lock;
24421   }
24422
24423
24424   /* A PENDING lock is needed before acquiring a SHARED lock and before
24425   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24426   ** be released.
24427   */
24428   lock.l_len = 1L;
24429   lock.l_whence = SEEK_SET;
24430   if( eFileLock==SHARED_LOCK 
24431       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24432   ){
24433     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
24434     lock.l_start = PENDING_BYTE;
24435     if( unixFileLock(pFile, &lock) ){
24436       tErrno = errno;
24437       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24438       if( rc!=SQLITE_BUSY ){
24439         pFile->lastErrno = tErrno;
24440       }
24441       goto end_lock;
24442     }
24443   }
24444
24445
24446   /* If control gets to this point, then actually go ahead and make
24447   ** operating system calls for the specified lock.
24448   */
24449   if( eFileLock==SHARED_LOCK ){
24450     assert( pInode->nShared==0 );
24451     assert( pInode->eFileLock==0 );
24452     assert( rc==SQLITE_OK );
24453
24454     /* Now get the read-lock */
24455     lock.l_start = SHARED_FIRST;
24456     lock.l_len = SHARED_SIZE;
24457     if( unixFileLock(pFile, &lock) ){
24458       tErrno = errno;
24459       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24460     }
24461
24462     /* Drop the temporary PENDING lock */
24463     lock.l_start = PENDING_BYTE;
24464     lock.l_len = 1L;
24465     lock.l_type = F_UNLCK;
24466     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
24467       /* This could happen with a network mount */
24468       tErrno = errno;
24469       rc = SQLITE_IOERR_UNLOCK; 
24470     }
24471
24472     if( rc ){
24473       if( rc!=SQLITE_BUSY ){
24474         pFile->lastErrno = tErrno;
24475       }
24476       goto end_lock;
24477     }else{
24478       pFile->eFileLock = SHARED_LOCK;
24479       pInode->nLock++;
24480       pInode->nShared = 1;
24481     }
24482   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24483     /* We are trying for an exclusive lock but another thread in this
24484     ** same process is still holding a shared lock. */
24485     rc = SQLITE_BUSY;
24486   }else{
24487     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24488     ** assumed that there is a SHARED or greater lock on the file
24489     ** already.
24490     */
24491     assert( 0!=pFile->eFileLock );
24492     lock.l_type = F_WRLCK;
24493
24494     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
24495     if( eFileLock==RESERVED_LOCK ){
24496       lock.l_start = RESERVED_BYTE;
24497       lock.l_len = 1L;
24498     }else{
24499       lock.l_start = SHARED_FIRST;
24500       lock.l_len = SHARED_SIZE;
24501     }
24502
24503     if( unixFileLock(pFile, &lock) ){
24504       tErrno = errno;
24505       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24506       if( rc!=SQLITE_BUSY ){
24507         pFile->lastErrno = tErrno;
24508       }
24509     }
24510   }
24511   
24512
24513 #ifdef SQLITE_DEBUG
24514   /* Set up the transaction-counter change checking flags when
24515   ** transitioning from a SHARED to a RESERVED lock.  The change
24516   ** from SHARED to RESERVED marks the beginning of a normal
24517   ** write operation (not a hot journal rollback).
24518   */
24519   if( rc==SQLITE_OK
24520    && pFile->eFileLock<=SHARED_LOCK
24521    && eFileLock==RESERVED_LOCK
24522   ){
24523     pFile->transCntrChng = 0;
24524     pFile->dbUpdate = 0;
24525     pFile->inNormalWrite = 1;
24526   }
24527 #endif
24528
24529
24530   if( rc==SQLITE_OK ){
24531     pFile->eFileLock = eFileLock;
24532     pInode->eFileLock = eFileLock;
24533   }else if( eFileLock==EXCLUSIVE_LOCK ){
24534     pFile->eFileLock = PENDING_LOCK;
24535     pInode->eFileLock = PENDING_LOCK;
24536   }
24537
24538 end_lock:
24539   unixLeaveMutex();
24540   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
24541       rc==SQLITE_OK ? "ok" : "failed"));
24542   return rc;
24543 }
24544
24545 /*
24546 ** Add the file descriptor used by file handle pFile to the corresponding
24547 ** pUnused list.
24548 */
24549 static void setPendingFd(unixFile *pFile){
24550   unixInodeInfo *pInode = pFile->pInode;
24551   UnixUnusedFd *p = pFile->pUnused;
24552   p->pNext = pInode->pUnused;
24553   pInode->pUnused = p;
24554   pFile->h = -1;
24555   pFile->pUnused = 0;
24556 }
24557
24558 /*
24559 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24560 ** must be either NO_LOCK or SHARED_LOCK.
24561 **
24562 ** If the locking level of the file descriptor is already at or below
24563 ** the requested locking level, this routine is a no-op.
24564 ** 
24565 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
24566 ** the byte range is divided into 2 parts and the first part is unlocked then
24567 ** set to a read lock, then the other part is simply unlocked.  This works 
24568 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
24569 ** remove the write lock on a region when a read lock is set.
24570 */
24571 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
24572   unixFile *pFile = (unixFile*)id;
24573   unixInodeInfo *pInode;
24574   struct flock lock;
24575   int rc = SQLITE_OK;
24576
24577   assert( pFile );
24578   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
24579       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24580       getpid()));
24581
24582   assert( eFileLock<=SHARED_LOCK );
24583   if( pFile->eFileLock<=eFileLock ){
24584     return SQLITE_OK;
24585   }
24586   unixEnterMutex();
24587   pInode = pFile->pInode;
24588   assert( pInode->nShared!=0 );
24589   if( pFile->eFileLock>SHARED_LOCK ){
24590     assert( pInode->eFileLock==pFile->eFileLock );
24591
24592 #ifdef SQLITE_DEBUG
24593     /* When reducing a lock such that other processes can start
24594     ** reading the database file again, make sure that the
24595     ** transaction counter was updated if any part of the database
24596     ** file changed.  If the transaction counter is not updated,
24597     ** other connections to the same file might not realize that
24598     ** the file has changed and hence might not know to flush their
24599     ** cache.  The use of a stale cache can lead to database corruption.
24600     */
24601     pFile->inNormalWrite = 0;
24602 #endif
24603
24604     /* downgrading to a shared lock on NFS involves clearing the write lock
24605     ** before establishing the readlock - to avoid a race condition we downgrade
24606     ** the lock in 2 blocks, so that part of the range will be covered by a 
24607     ** write lock until the rest is covered by a read lock:
24608     **  1:   [WWWWW]
24609     **  2:   [....W]
24610     **  3:   [RRRRW]
24611     **  4:   [RRRR.]
24612     */
24613     if( eFileLock==SHARED_LOCK ){
24614
24615 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
24616       (void)handleNFSUnlock;
24617       assert( handleNFSUnlock==0 );
24618 #endif
24619 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24620       if( handleNFSUnlock ){
24621         int tErrno;               /* Error code from system call errors */
24622         off_t divSize = SHARED_SIZE - 1;
24623         
24624         lock.l_type = F_UNLCK;
24625         lock.l_whence = SEEK_SET;
24626         lock.l_start = SHARED_FIRST;
24627         lock.l_len = divSize;
24628         if( unixFileLock(pFile, &lock)==(-1) ){
24629           tErrno = errno;
24630           rc = SQLITE_IOERR_UNLOCK;
24631           if( IS_LOCK_ERROR(rc) ){
24632             pFile->lastErrno = tErrno;
24633           }
24634           goto end_unlock;
24635         }
24636         lock.l_type = F_RDLCK;
24637         lock.l_whence = SEEK_SET;
24638         lock.l_start = SHARED_FIRST;
24639         lock.l_len = divSize;
24640         if( unixFileLock(pFile, &lock)==(-1) ){
24641           tErrno = errno;
24642           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24643           if( IS_LOCK_ERROR(rc) ){
24644             pFile->lastErrno = tErrno;
24645           }
24646           goto end_unlock;
24647         }
24648         lock.l_type = F_UNLCK;
24649         lock.l_whence = SEEK_SET;
24650         lock.l_start = SHARED_FIRST+divSize;
24651         lock.l_len = SHARED_SIZE-divSize;
24652         if( unixFileLock(pFile, &lock)==(-1) ){
24653           tErrno = errno;
24654           rc = SQLITE_IOERR_UNLOCK;
24655           if( IS_LOCK_ERROR(rc) ){
24656             pFile->lastErrno = tErrno;
24657           }
24658           goto end_unlock;
24659         }
24660       }else
24661 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24662       {
24663         lock.l_type = F_RDLCK;
24664         lock.l_whence = SEEK_SET;
24665         lock.l_start = SHARED_FIRST;
24666         lock.l_len = SHARED_SIZE;
24667         if( unixFileLock(pFile, &lock) ){
24668           /* In theory, the call to unixFileLock() cannot fail because another
24669           ** process is holding an incompatible lock. If it does, this 
24670           ** indicates that the other process is not following the locking
24671           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
24672           ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
24673           ** an assert to fail). */ 
24674           rc = SQLITE_IOERR_RDLOCK;
24675           pFile->lastErrno = errno;
24676           goto end_unlock;
24677         }
24678       }
24679     }
24680     lock.l_type = F_UNLCK;
24681     lock.l_whence = SEEK_SET;
24682     lock.l_start = PENDING_BYTE;
24683     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
24684     if( unixFileLock(pFile, &lock)==0 ){
24685       pInode->eFileLock = SHARED_LOCK;
24686     }else{
24687       rc = SQLITE_IOERR_UNLOCK;
24688       pFile->lastErrno = errno;
24689       goto end_unlock;
24690     }
24691   }
24692   if( eFileLock==NO_LOCK ){
24693     /* Decrement the shared lock counter.  Release the lock using an
24694     ** OS call only when all threads in this same process have released
24695     ** the lock.
24696     */
24697     pInode->nShared--;
24698     if( pInode->nShared==0 ){
24699       lock.l_type = F_UNLCK;
24700       lock.l_whence = SEEK_SET;
24701       lock.l_start = lock.l_len = 0L;
24702       if( unixFileLock(pFile, &lock)==0 ){
24703         pInode->eFileLock = NO_LOCK;
24704       }else{
24705         rc = SQLITE_IOERR_UNLOCK;
24706         pFile->lastErrno = errno;
24707         pInode->eFileLock = NO_LOCK;
24708         pFile->eFileLock = NO_LOCK;
24709       }
24710     }
24711
24712     /* Decrement the count of locks against this same file.  When the
24713     ** count reaches zero, close any other file descriptors whose close
24714     ** was deferred because of outstanding locks.
24715     */
24716     pInode->nLock--;
24717     assert( pInode->nLock>=0 );
24718     if( pInode->nLock==0 ){
24719       closePendingFds(pFile);
24720     }
24721   }
24722
24723 end_unlock:
24724   unixLeaveMutex();
24725   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24726   return rc;
24727 }
24728
24729 /*
24730 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24731 ** must be either NO_LOCK or SHARED_LOCK.
24732 **
24733 ** If the locking level of the file descriptor is already at or below
24734 ** the requested locking level, this routine is a no-op.
24735 */
24736 static int unixUnlock(sqlite3_file *id, int eFileLock){
24737   return posixUnlock(id, eFileLock, 0);
24738 }
24739
24740 /*
24741 ** This function performs the parts of the "close file" operation 
24742 ** common to all locking schemes. It closes the directory and file
24743 ** handles, if they are valid, and sets all fields of the unixFile
24744 ** structure to 0.
24745 **
24746 ** It is *not* necessary to hold the mutex when this routine is called,
24747 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
24748 ** vxworksReleaseFileId() routine.
24749 */
24750 static int closeUnixFile(sqlite3_file *id){
24751   unixFile *pFile = (unixFile*)id;
24752   if( pFile->h>=0 ){
24753     robust_close(pFile, pFile->h, __LINE__);
24754     pFile->h = -1;
24755   }
24756 #if OS_VXWORKS
24757   if( pFile->pId ){
24758     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
24759       osUnlink(pFile->pId->zCanonicalName);
24760     }
24761     vxworksReleaseFileId(pFile->pId);
24762     pFile->pId = 0;
24763   }
24764 #endif
24765   OSTRACE(("CLOSE   %-3d\n", pFile->h));
24766   OpenCounter(-1);
24767   sqlite3_free(pFile->pUnused);
24768   memset(pFile, 0, sizeof(unixFile));
24769   return SQLITE_OK;
24770 }
24771
24772 /*
24773 ** Close a file.
24774 */
24775 static int unixClose(sqlite3_file *id){
24776   int rc = SQLITE_OK;
24777   unixFile *pFile = (unixFile *)id;
24778   unixUnlock(id, NO_LOCK);
24779   unixEnterMutex();
24780
24781   /* unixFile.pInode is always valid here. Otherwise, a different close
24782   ** routine (e.g. nolockClose()) would be called instead.
24783   */
24784   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
24785   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
24786     /* If there are outstanding locks, do not actually close the file just
24787     ** yet because that would clear those locks.  Instead, add the file
24788     ** descriptor to pInode->pUnused list.  It will be automatically closed 
24789     ** when the last lock is cleared.
24790     */
24791     setPendingFd(pFile);
24792   }
24793   releaseInodeInfo(pFile);
24794   rc = closeUnixFile(id);
24795   unixLeaveMutex();
24796   return rc;
24797 }
24798
24799 /************** End of the posix advisory lock implementation *****************
24800 ******************************************************************************/
24801
24802 /******************************************************************************
24803 ****************************** No-op Locking **********************************
24804 **
24805 ** Of the various locking implementations available, this is by far the
24806 ** simplest:  locking is ignored.  No attempt is made to lock the database
24807 ** file for reading or writing.
24808 **
24809 ** This locking mode is appropriate for use on read-only databases
24810 ** (ex: databases that are burned into CD-ROM, for example.)  It can
24811 ** also be used if the application employs some external mechanism to
24812 ** prevent simultaneous access of the same database by two or more
24813 ** database connections.  But there is a serious risk of database
24814 ** corruption if this locking mode is used in situations where multiple
24815 ** database connections are accessing the same database file at the same
24816 ** time and one or more of those connections are writing.
24817 */
24818
24819 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
24820   UNUSED_PARAMETER(NotUsed);
24821   *pResOut = 0;
24822   return SQLITE_OK;
24823 }
24824 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
24825   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24826   return SQLITE_OK;
24827 }
24828 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
24829   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24830   return SQLITE_OK;
24831 }
24832
24833 /*
24834 ** Close the file.
24835 */
24836 static int nolockClose(sqlite3_file *id) {
24837   return closeUnixFile(id);
24838 }
24839
24840 /******************* End of the no-op lock implementation *********************
24841 ******************************************************************************/
24842
24843 /******************************************************************************
24844 ************************* Begin dot-file Locking ******************************
24845 **
24846 ** The dotfile locking implementation uses the existence of separate lock
24847 ** files (really a directory) to control access to the database.  This works
24848 ** on just about every filesystem imaginable.  But there are serious downsides:
24849 **
24850 **    (1)  There is zero concurrency.  A single reader blocks all other
24851 **         connections from reading or writing the database.
24852 **
24853 **    (2)  An application crash or power loss can leave stale lock files
24854 **         sitting around that need to be cleared manually.
24855 **
24856 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
24857 ** other locking strategy is available.
24858 **
24859 ** Dotfile locking works by creating a subdirectory in the same directory as
24860 ** the database and with the same name but with a ".lock" extension added.
24861 ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
24862 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
24863 */
24864
24865 /*
24866 ** The file suffix added to the data base filename in order to create the
24867 ** lock directory.
24868 */
24869 #define DOTLOCK_SUFFIX ".lock"
24870
24871 /*
24872 ** This routine checks if there is a RESERVED lock held on the specified
24873 ** file by this or any other process. If such a lock is held, set *pResOut
24874 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24875 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24876 **
24877 ** In dotfile locking, either a lock exists or it does not.  So in this
24878 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
24879 ** is held on the file and false if the file is unlocked.
24880 */
24881 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
24882   int rc = SQLITE_OK;
24883   int reserved = 0;
24884   unixFile *pFile = (unixFile*)id;
24885
24886   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24887   
24888   assert( pFile );
24889
24890   /* Check if a thread in this process holds such a lock */
24891   if( pFile->eFileLock>SHARED_LOCK ){
24892     /* Either this connection or some other connection in the same process
24893     ** holds a lock on the file.  No need to check further. */
24894     reserved = 1;
24895   }else{
24896     /* The lock is held if and only if the lockfile exists */
24897     const char *zLockFile = (const char*)pFile->lockingContext;
24898     reserved = osAccess(zLockFile, 0)==0;
24899   }
24900   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
24901   *pResOut = reserved;
24902   return rc;
24903 }
24904
24905 /*
24906 ** Lock the file with the lock specified by parameter eFileLock - one
24907 ** of the following:
24908 **
24909 **     (1) SHARED_LOCK
24910 **     (2) RESERVED_LOCK
24911 **     (3) PENDING_LOCK
24912 **     (4) EXCLUSIVE_LOCK
24913 **
24914 ** Sometimes when requesting one lock state, additional lock states
24915 ** are inserted in between.  The locking might fail on one of the later
24916 ** transitions leaving the lock state different from what it started but
24917 ** still short of its goal.  The following chart shows the allowed
24918 ** transitions and the inserted intermediate states:
24919 **
24920 **    UNLOCKED -> SHARED
24921 **    SHARED -> RESERVED
24922 **    SHARED -> (PENDING) -> EXCLUSIVE
24923 **    RESERVED -> (PENDING) -> EXCLUSIVE
24924 **    PENDING -> EXCLUSIVE
24925 **
24926 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24927 ** routine to lower a locking level.
24928 **
24929 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
24930 ** But we track the other locking levels internally.
24931 */
24932 static int dotlockLock(sqlite3_file *id, int eFileLock) {
24933   unixFile *pFile = (unixFile*)id;
24934   char *zLockFile = (char *)pFile->lockingContext;
24935   int rc = SQLITE_OK;
24936
24937
24938   /* If we have any lock, then the lock file already exists.  All we have
24939   ** to do is adjust our internal record of the lock level.
24940   */
24941   if( pFile->eFileLock > NO_LOCK ){
24942     pFile->eFileLock = eFileLock;
24943     /* Always update the timestamp on the old file */
24944 #ifdef HAVE_UTIME
24945     utime(zLockFile, NULL);
24946 #else
24947     utimes(zLockFile, NULL);
24948 #endif
24949     return SQLITE_OK;
24950   }
24951   
24952   /* grab an exclusive lock */
24953   rc = osMkdir(zLockFile, 0777);
24954   if( rc<0 ){
24955     /* failed to open/create the lock directory */
24956     int tErrno = errno;
24957     if( EEXIST == tErrno ){
24958       rc = SQLITE_BUSY;
24959     } else {
24960       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24961       if( IS_LOCK_ERROR(rc) ){
24962         pFile->lastErrno = tErrno;
24963       }
24964     }
24965     return rc;
24966   } 
24967   
24968   /* got it, set the type and return ok */
24969   pFile->eFileLock = eFileLock;
24970   return rc;
24971 }
24972
24973 /*
24974 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24975 ** must be either NO_LOCK or SHARED_LOCK.
24976 **
24977 ** If the locking level of the file descriptor is already at or below
24978 ** the requested locking level, this routine is a no-op.
24979 **
24980 ** When the locking level reaches NO_LOCK, delete the lock file.
24981 */
24982 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
24983   unixFile *pFile = (unixFile*)id;
24984   char *zLockFile = (char *)pFile->lockingContext;
24985   int rc;
24986
24987   assert( pFile );
24988   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
24989            pFile->eFileLock, getpid()));
24990   assert( eFileLock<=SHARED_LOCK );
24991   
24992   /* no-op if possible */
24993   if( pFile->eFileLock==eFileLock ){
24994     return SQLITE_OK;
24995   }
24996
24997   /* To downgrade to shared, simply update our internal notion of the
24998   ** lock state.  No need to mess with the file on disk.
24999   */
25000   if( eFileLock==SHARED_LOCK ){
25001     pFile->eFileLock = SHARED_LOCK;
25002     return SQLITE_OK;
25003   }
25004   
25005   /* To fully unlock the database, delete the lock file */
25006   assert( eFileLock==NO_LOCK );
25007   rc = osRmdir(zLockFile);
25008   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
25009   if( rc<0 ){
25010     int tErrno = errno;
25011     rc = 0;
25012     if( ENOENT != tErrno ){
25013       rc = SQLITE_IOERR_UNLOCK;
25014     }
25015     if( IS_LOCK_ERROR(rc) ){
25016       pFile->lastErrno = tErrno;
25017     }
25018     return rc; 
25019   }
25020   pFile->eFileLock = NO_LOCK;
25021   return SQLITE_OK;
25022 }
25023
25024 /*
25025 ** Close a file.  Make sure the lock has been released before closing.
25026 */
25027 static int dotlockClose(sqlite3_file *id) {
25028   int rc = SQLITE_OK;
25029   if( id ){
25030     unixFile *pFile = (unixFile*)id;
25031     dotlockUnlock(id, NO_LOCK);
25032     sqlite3_free(pFile->lockingContext);
25033     rc = closeUnixFile(id);
25034   }
25035   return rc;
25036 }
25037 /****************** End of the dot-file lock implementation *******************
25038 ******************************************************************************/
25039
25040 /******************************************************************************
25041 ************************** Begin flock Locking ********************************
25042 **
25043 ** Use the flock() system call to do file locking.
25044 **
25045 ** flock() locking is like dot-file locking in that the various
25046 ** fine-grain locking levels supported by SQLite are collapsed into
25047 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
25048 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
25049 ** still works when you do this, but concurrency is reduced since
25050 ** only a single process can be reading the database at a time.
25051 **
25052 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
25053 ** compiling for VXWORKS.
25054 */
25055 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
25056
25057 /*
25058 ** Retry flock() calls that fail with EINTR
25059 */
25060 #ifdef EINTR
25061 static int robust_flock(int fd, int op){
25062   int rc;
25063   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
25064   return rc;
25065 }
25066 #else
25067 # define robust_flock(a,b) flock(a,b)
25068 #endif
25069      
25070
25071 /*
25072 ** This routine checks if there is a RESERVED lock held on the specified
25073 ** file by this or any other process. If such a lock is held, set *pResOut
25074 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25075 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25076 */
25077 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
25078   int rc = SQLITE_OK;
25079   int reserved = 0;
25080   unixFile *pFile = (unixFile*)id;
25081   
25082   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25083   
25084   assert( pFile );
25085   
25086   /* Check if a thread in this process holds such a lock */
25087   if( pFile->eFileLock>SHARED_LOCK ){
25088     reserved = 1;
25089   }
25090   
25091   /* Otherwise see if some other process holds it. */
25092   if( !reserved ){
25093     /* attempt to get the lock */
25094     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
25095     if( !lrc ){
25096       /* got the lock, unlock it */
25097       lrc = robust_flock(pFile->h, LOCK_UN);
25098       if ( lrc ) {
25099         int tErrno = errno;
25100         /* unlock failed with an error */
25101         lrc = SQLITE_IOERR_UNLOCK; 
25102         if( IS_LOCK_ERROR(lrc) ){
25103           pFile->lastErrno = tErrno;
25104           rc = lrc;
25105         }
25106       }
25107     } else {
25108       int tErrno = errno;
25109       reserved = 1;
25110       /* someone else might have it reserved */
25111       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
25112       if( IS_LOCK_ERROR(lrc) ){
25113         pFile->lastErrno = tErrno;
25114         rc = lrc;
25115       }
25116     }
25117   }
25118   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
25119
25120 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25121   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25122     rc = SQLITE_OK;
25123     reserved=1;
25124   }
25125 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25126   *pResOut = reserved;
25127   return rc;
25128 }
25129
25130 /*
25131 ** Lock the file with the lock specified by parameter eFileLock - one
25132 ** of the following:
25133 **
25134 **     (1) SHARED_LOCK
25135 **     (2) RESERVED_LOCK
25136 **     (3) PENDING_LOCK
25137 **     (4) EXCLUSIVE_LOCK
25138 **
25139 ** Sometimes when requesting one lock state, additional lock states
25140 ** are inserted in between.  The locking might fail on one of the later
25141 ** transitions leaving the lock state different from what it started but
25142 ** still short of its goal.  The following chart shows the allowed
25143 ** transitions and the inserted intermediate states:
25144 **
25145 **    UNLOCKED -> SHARED
25146 **    SHARED -> RESERVED
25147 **    SHARED -> (PENDING) -> EXCLUSIVE
25148 **    RESERVED -> (PENDING) -> EXCLUSIVE
25149 **    PENDING -> EXCLUSIVE
25150 **
25151 ** flock() only really support EXCLUSIVE locks.  We track intermediate
25152 ** lock states in the sqlite3_file structure, but all locks SHARED or
25153 ** above are really EXCLUSIVE locks and exclude all other processes from
25154 ** access the file.
25155 **
25156 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25157 ** routine to lower a locking level.
25158 */
25159 static int flockLock(sqlite3_file *id, int eFileLock) {
25160   int rc = SQLITE_OK;
25161   unixFile *pFile = (unixFile*)id;
25162
25163   assert( pFile );
25164
25165   /* if we already have a lock, it is exclusive.  
25166   ** Just adjust level and punt on outta here. */
25167   if (pFile->eFileLock > NO_LOCK) {
25168     pFile->eFileLock = eFileLock;
25169     return SQLITE_OK;
25170   }
25171   
25172   /* grab an exclusive lock */
25173   
25174   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
25175     int tErrno = errno;
25176     /* didn't get, must be busy */
25177     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25178     if( IS_LOCK_ERROR(rc) ){
25179       pFile->lastErrno = tErrno;
25180     }
25181   } else {
25182     /* got it, set the type and return ok */
25183     pFile->eFileLock = eFileLock;
25184   }
25185   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
25186            rc==SQLITE_OK ? "ok" : "failed"));
25187 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25188   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25189     rc = SQLITE_BUSY;
25190   }
25191 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25192   return rc;
25193 }
25194
25195
25196 /*
25197 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25198 ** must be either NO_LOCK or SHARED_LOCK.
25199 **
25200 ** If the locking level of the file descriptor is already at or below
25201 ** the requested locking level, this routine is a no-op.
25202 */
25203 static int flockUnlock(sqlite3_file *id, int eFileLock) {
25204   unixFile *pFile = (unixFile*)id;
25205   
25206   assert( pFile );
25207   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
25208            pFile->eFileLock, getpid()));
25209   assert( eFileLock<=SHARED_LOCK );
25210   
25211   /* no-op if possible */
25212   if( pFile->eFileLock==eFileLock ){
25213     return SQLITE_OK;
25214   }
25215   
25216   /* shared can just be set because we always have an exclusive */
25217   if (eFileLock==SHARED_LOCK) {
25218     pFile->eFileLock = eFileLock;
25219     return SQLITE_OK;
25220   }
25221   
25222   /* no, really, unlock. */
25223   if( robust_flock(pFile->h, LOCK_UN) ){
25224 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25225     return SQLITE_OK;
25226 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25227     return SQLITE_IOERR_UNLOCK;
25228   }else{
25229     pFile->eFileLock = NO_LOCK;
25230     return SQLITE_OK;
25231   }
25232 }
25233
25234 /*
25235 ** Close a file.
25236 */
25237 static int flockClose(sqlite3_file *id) {
25238   int rc = SQLITE_OK;
25239   if( id ){
25240     flockUnlock(id, NO_LOCK);
25241     rc = closeUnixFile(id);
25242   }
25243   return rc;
25244 }
25245
25246 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
25247
25248 /******************* End of the flock lock implementation *********************
25249 ******************************************************************************/
25250
25251 /******************************************************************************
25252 ************************ Begin Named Semaphore Locking ************************
25253 **
25254 ** Named semaphore locking is only supported on VxWorks.
25255 **
25256 ** Semaphore locking is like dot-lock and flock in that it really only
25257 ** supports EXCLUSIVE locking.  Only a single process can read or write
25258 ** the database file at a time.  This reduces potential concurrency, but
25259 ** makes the lock implementation much easier.
25260 */
25261 #if OS_VXWORKS
25262
25263 /*
25264 ** This routine checks if there is a RESERVED lock held on the specified
25265 ** file by this or any other process. If such a lock is held, set *pResOut
25266 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25267 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25268 */
25269 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
25270   int rc = SQLITE_OK;
25271   int reserved = 0;
25272   unixFile *pFile = (unixFile*)id;
25273
25274   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25275   
25276   assert( pFile );
25277
25278   /* Check if a thread in this process holds such a lock */
25279   if( pFile->eFileLock>SHARED_LOCK ){
25280     reserved = 1;
25281   }
25282   
25283   /* Otherwise see if some other process holds it. */
25284   if( !reserved ){
25285     sem_t *pSem = pFile->pInode->pSem;
25286     struct stat statBuf;
25287
25288     if( sem_trywait(pSem)==-1 ){
25289       int tErrno = errno;
25290       if( EAGAIN != tErrno ){
25291         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
25292         pFile->lastErrno = tErrno;
25293       } else {
25294         /* someone else has the lock when we are in NO_LOCK */
25295         reserved = (pFile->eFileLock < SHARED_LOCK);
25296       }
25297     }else{
25298       /* we could have it if we want it */
25299       sem_post(pSem);
25300     }
25301   }
25302   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
25303
25304   *pResOut = reserved;
25305   return rc;
25306 }
25307
25308 /*
25309 ** Lock the file with the lock specified by parameter eFileLock - one
25310 ** of the following:
25311 **
25312 **     (1) SHARED_LOCK
25313 **     (2) RESERVED_LOCK
25314 **     (3) PENDING_LOCK
25315 **     (4) EXCLUSIVE_LOCK
25316 **
25317 ** Sometimes when requesting one lock state, additional lock states
25318 ** are inserted in between.  The locking might fail on one of the later
25319 ** transitions leaving the lock state different from what it started but
25320 ** still short of its goal.  The following chart shows the allowed
25321 ** transitions and the inserted intermediate states:
25322 **
25323 **    UNLOCKED -> SHARED
25324 **    SHARED -> RESERVED
25325 **    SHARED -> (PENDING) -> EXCLUSIVE
25326 **    RESERVED -> (PENDING) -> EXCLUSIVE
25327 **    PENDING -> EXCLUSIVE
25328 **
25329 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
25330 ** lock states in the sqlite3_file structure, but all locks SHARED or
25331 ** above are really EXCLUSIVE locks and exclude all other processes from
25332 ** access the file.
25333 **
25334 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25335 ** routine to lower a locking level.
25336 */
25337 static int semLock(sqlite3_file *id, int eFileLock) {
25338   unixFile *pFile = (unixFile*)id;
25339   int fd;
25340   sem_t *pSem = pFile->pInode->pSem;
25341   int rc = SQLITE_OK;
25342
25343   /* if we already have a lock, it is exclusive.  
25344   ** Just adjust level and punt on outta here. */
25345   if (pFile->eFileLock > NO_LOCK) {
25346     pFile->eFileLock = eFileLock;
25347     rc = SQLITE_OK;
25348     goto sem_end_lock;
25349   }
25350   
25351   /* lock semaphore now but bail out when already locked. */
25352   if( sem_trywait(pSem)==-1 ){
25353     rc = SQLITE_BUSY;
25354     goto sem_end_lock;
25355   }
25356
25357   /* got it, set the type and return ok */
25358   pFile->eFileLock = eFileLock;
25359
25360  sem_end_lock:
25361   return rc;
25362 }
25363
25364 /*
25365 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25366 ** must be either NO_LOCK or SHARED_LOCK.
25367 **
25368 ** If the locking level of the file descriptor is already at or below
25369 ** the requested locking level, this routine is a no-op.
25370 */
25371 static int semUnlock(sqlite3_file *id, int eFileLock) {
25372   unixFile *pFile = (unixFile*)id;
25373   sem_t *pSem = pFile->pInode->pSem;
25374
25375   assert( pFile );
25376   assert( pSem );
25377   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
25378            pFile->eFileLock, getpid()));
25379   assert( eFileLock<=SHARED_LOCK );
25380   
25381   /* no-op if possible */
25382   if( pFile->eFileLock==eFileLock ){
25383     return SQLITE_OK;
25384   }
25385   
25386   /* shared can just be set because we always have an exclusive */
25387   if (eFileLock==SHARED_LOCK) {
25388     pFile->eFileLock = eFileLock;
25389     return SQLITE_OK;
25390   }
25391   
25392   /* no, really unlock. */
25393   if ( sem_post(pSem)==-1 ) {
25394     int rc, tErrno = errno;
25395     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
25396     if( IS_LOCK_ERROR(rc) ){
25397       pFile->lastErrno = tErrno;
25398     }
25399     return rc; 
25400   }
25401   pFile->eFileLock = NO_LOCK;
25402   return SQLITE_OK;
25403 }
25404
25405 /*
25406  ** Close a file.
25407  */
25408 static int semClose(sqlite3_file *id) {
25409   if( id ){
25410     unixFile *pFile = (unixFile*)id;
25411     semUnlock(id, NO_LOCK);
25412     assert( pFile );
25413     unixEnterMutex();
25414     releaseInodeInfo(pFile);
25415     unixLeaveMutex();
25416     closeUnixFile(id);
25417   }
25418   return SQLITE_OK;
25419 }
25420
25421 #endif /* OS_VXWORKS */
25422 /*
25423 ** Named semaphore locking is only available on VxWorks.
25424 **
25425 *************** End of the named semaphore lock implementation ****************
25426 ******************************************************************************/
25427
25428
25429 /******************************************************************************
25430 *************************** Begin AFP Locking *********************************
25431 **
25432 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
25433 ** on Apple Macintosh computers - both OS9 and OSX.
25434 **
25435 ** Third-party implementations of AFP are available.  But this code here
25436 ** only works on OSX.
25437 */
25438
25439 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25440 /*
25441 ** The afpLockingContext structure contains all afp lock specific state
25442 */
25443 typedef struct afpLockingContext afpLockingContext;
25444 struct afpLockingContext {
25445   int reserved;
25446   const char *dbPath;             /* Name of the open file */
25447 };
25448
25449 struct ByteRangeLockPB2
25450 {
25451   unsigned long long offset;        /* offset to first byte to lock */
25452   unsigned long long length;        /* nbr of bytes to lock */
25453   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
25454   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
25455   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
25456   int fd;                           /* file desc to assoc this lock with */
25457 };
25458
25459 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
25460
25461 /*
25462 ** This is a utility for setting or clearing a bit-range lock on an
25463 ** AFP filesystem.
25464 ** 
25465 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
25466 */
25467 static int afpSetLock(
25468   const char *path,              /* Name of the file to be locked or unlocked */
25469   unixFile *pFile,               /* Open file descriptor on path */
25470   unsigned long long offset,     /* First byte to be locked */
25471   unsigned long long length,     /* Number of bytes to lock */
25472   int setLockFlag                /* True to set lock.  False to clear lock */
25473 ){
25474   struct ByteRangeLockPB2 pb;
25475   int err;
25476   
25477   pb.unLockFlag = setLockFlag ? 0 : 1;
25478   pb.startEndFlag = 0;
25479   pb.offset = offset;
25480   pb.length = length; 
25481   pb.fd = pFile->h;
25482   
25483   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
25484     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
25485     offset, length));
25486   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
25487   if ( err==-1 ) {
25488     int rc;
25489     int tErrno = errno;
25490     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
25491              path, tErrno, strerror(tErrno)));
25492 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
25493     rc = SQLITE_BUSY;
25494 #else
25495     rc = sqliteErrorFromPosixError(tErrno,
25496                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
25497 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
25498     if( IS_LOCK_ERROR(rc) ){
25499       pFile->lastErrno = tErrno;
25500     }
25501     return rc;
25502   } else {
25503     return SQLITE_OK;
25504   }
25505 }
25506
25507 /*
25508 ** This routine checks if there is a RESERVED lock held on the specified
25509 ** file by this or any other process. If such a lock is held, set *pResOut
25510 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25511 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25512 */
25513 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
25514   int rc = SQLITE_OK;
25515   int reserved = 0;
25516   unixFile *pFile = (unixFile*)id;
25517   afpLockingContext *context;
25518   
25519   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25520   
25521   assert( pFile );
25522   context = (afpLockingContext *) pFile->lockingContext;
25523   if( context->reserved ){
25524     *pResOut = 1;
25525     return SQLITE_OK;
25526   }
25527   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25528   
25529   /* Check if a thread in this process holds such a lock */
25530   if( pFile->pInode->eFileLock>SHARED_LOCK ){
25531     reserved = 1;
25532   }
25533   
25534   /* Otherwise see if some other process holds it.
25535    */
25536   if( !reserved ){
25537     /* lock the RESERVED byte */
25538     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
25539     if( SQLITE_OK==lrc ){
25540       /* if we succeeded in taking the reserved lock, unlock it to restore
25541       ** the original state */
25542       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25543     } else {
25544       /* if we failed to get the lock then someone else must have it */
25545       reserved = 1;
25546     }
25547     if( IS_LOCK_ERROR(lrc) ){
25548       rc=lrc;
25549     }
25550   }
25551   
25552   unixLeaveMutex();
25553   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
25554   
25555   *pResOut = reserved;
25556   return rc;
25557 }
25558
25559 /*
25560 ** Lock the file with the lock specified by parameter eFileLock - one
25561 ** of the following:
25562 **
25563 **     (1) SHARED_LOCK
25564 **     (2) RESERVED_LOCK
25565 **     (3) PENDING_LOCK
25566 **     (4) EXCLUSIVE_LOCK
25567 **
25568 ** Sometimes when requesting one lock state, additional lock states
25569 ** are inserted in between.  The locking might fail on one of the later
25570 ** transitions leaving the lock state different from what it started but
25571 ** still short of its goal.  The following chart shows the allowed
25572 ** transitions and the inserted intermediate states:
25573 **
25574 **    UNLOCKED -> SHARED
25575 **    SHARED -> RESERVED
25576 **    SHARED -> (PENDING) -> EXCLUSIVE
25577 **    RESERVED -> (PENDING) -> EXCLUSIVE
25578 **    PENDING -> EXCLUSIVE
25579 **
25580 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25581 ** routine to lower a locking level.
25582 */
25583 static int afpLock(sqlite3_file *id, int eFileLock){
25584   int rc = SQLITE_OK;
25585   unixFile *pFile = (unixFile*)id;
25586   unixInodeInfo *pInode = pFile->pInode;
25587   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25588   
25589   assert( pFile );
25590   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
25591            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25592            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25593
25594   /* If there is already a lock of this type or more restrictive on the
25595   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
25596   ** unixEnterMutex() hasn't been called yet.
25597   */
25598   if( pFile->eFileLock>=eFileLock ){
25599     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
25600            azFileLock(eFileLock)));
25601     return SQLITE_OK;
25602   }
25603
25604   /* Make sure the locking sequence is correct
25605   **  (1) We never move from unlocked to anything higher than shared lock.
25606   **  (2) SQLite never explicitly requests a pendig lock.
25607   **  (3) A shared lock is always held when a reserve lock is requested.
25608   */
25609   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25610   assert( eFileLock!=PENDING_LOCK );
25611   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25612   
25613   /* This mutex is needed because pFile->pInode is shared across threads
25614   */
25615   unixEnterMutex();
25616   pInode = pFile->pInode;
25617
25618   /* If some thread using this PID has a lock via a different unixFile*
25619   ** handle that precludes the requested lock, return BUSY.
25620   */
25621   if( (pFile->eFileLock!=pInode->eFileLock && 
25622        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25623      ){
25624     rc = SQLITE_BUSY;
25625     goto afp_end_lock;
25626   }
25627   
25628   /* If a SHARED lock is requested, and some thread using this PID already
25629   ** has a SHARED or RESERVED lock, then increment reference counts and
25630   ** return SQLITE_OK.
25631   */
25632   if( eFileLock==SHARED_LOCK && 
25633      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25634     assert( eFileLock==SHARED_LOCK );
25635     assert( pFile->eFileLock==0 );
25636     assert( pInode->nShared>0 );
25637     pFile->eFileLock = SHARED_LOCK;
25638     pInode->nShared++;
25639     pInode->nLock++;
25640     goto afp_end_lock;
25641   }
25642     
25643   /* A PENDING lock is needed before acquiring a SHARED lock and before
25644   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25645   ** be released.
25646   */
25647   if( eFileLock==SHARED_LOCK 
25648       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25649   ){
25650     int failed;
25651     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
25652     if (failed) {
25653       rc = failed;
25654       goto afp_end_lock;
25655     }
25656   }
25657   
25658   /* If control gets to this point, then actually go ahead and make
25659   ** operating system calls for the specified lock.
25660   */
25661   if( eFileLock==SHARED_LOCK ){
25662     int lrc1, lrc2, lrc1Errno = 0;
25663     long lk, mask;
25664     
25665     assert( pInode->nShared==0 );
25666     assert( pInode->eFileLock==0 );
25667         
25668     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
25669     /* Now get the read-lock SHARED_LOCK */
25670     /* note that the quality of the randomness doesn't matter that much */
25671     lk = random(); 
25672     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
25673     lrc1 = afpSetLock(context->dbPath, pFile, 
25674           SHARED_FIRST+pInode->sharedByte, 1, 1);
25675     if( IS_LOCK_ERROR(lrc1) ){
25676       lrc1Errno = pFile->lastErrno;
25677     }
25678     /* Drop the temporary PENDING lock */
25679     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25680     
25681     if( IS_LOCK_ERROR(lrc1) ) {
25682       pFile->lastErrno = lrc1Errno;
25683       rc = lrc1;
25684       goto afp_end_lock;
25685     } else if( IS_LOCK_ERROR(lrc2) ){
25686       rc = lrc2;
25687       goto afp_end_lock;
25688     } else if( lrc1 != SQLITE_OK ) {
25689       rc = lrc1;
25690     } else {
25691       pFile->eFileLock = SHARED_LOCK;
25692       pInode->nLock++;
25693       pInode->nShared = 1;
25694     }
25695   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25696     /* We are trying for an exclusive lock but another thread in this
25697      ** same process is still holding a shared lock. */
25698     rc = SQLITE_BUSY;
25699   }else{
25700     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25701     ** assumed that there is a SHARED or greater lock on the file
25702     ** already.
25703     */
25704     int failed = 0;
25705     assert( 0!=pFile->eFileLock );
25706     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
25707         /* Acquire a RESERVED lock */
25708         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25709       if( !failed ){
25710         context->reserved = 1;
25711       }
25712     }
25713     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
25714       /* Acquire an EXCLUSIVE lock */
25715         
25716       /* Remove the shared lock before trying the range.  we'll need to 
25717       ** reestablish the shared lock if we can't get the  afpUnlock
25718       */
25719       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
25720                          pInode->sharedByte, 1, 0)) ){
25721         int failed2 = SQLITE_OK;
25722         /* now attemmpt to get the exclusive lock range */
25723         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
25724                                SHARED_SIZE, 1);
25725         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
25726                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
25727           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
25728           ** a critical I/O error
25729           */
25730           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
25731                SQLITE_IOERR_LOCK;
25732           goto afp_end_lock;
25733         } 
25734       }else{
25735         rc = failed; 
25736       }
25737     }
25738     if( failed ){
25739       rc = failed;
25740     }
25741   }
25742   
25743   if( rc==SQLITE_OK ){
25744     pFile->eFileLock = eFileLock;
25745     pInode->eFileLock = eFileLock;
25746   }else if( eFileLock==EXCLUSIVE_LOCK ){
25747     pFile->eFileLock = PENDING_LOCK;
25748     pInode->eFileLock = PENDING_LOCK;
25749   }
25750   
25751 afp_end_lock:
25752   unixLeaveMutex();
25753   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
25754          rc==SQLITE_OK ? "ok" : "failed"));
25755   return rc;
25756 }
25757
25758 /*
25759 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25760 ** must be either NO_LOCK or SHARED_LOCK.
25761 **
25762 ** If the locking level of the file descriptor is already at or below
25763 ** the requested locking level, this routine is a no-op.
25764 */
25765 static int afpUnlock(sqlite3_file *id, int eFileLock) {
25766   int rc = SQLITE_OK;
25767   unixFile *pFile = (unixFile*)id;
25768   unixInodeInfo *pInode;
25769   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25770   int skipShared = 0;
25771 #ifdef SQLITE_TEST
25772   int h = pFile->h;
25773 #endif
25774
25775   assert( pFile );
25776   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
25777            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25778            getpid()));
25779
25780   assert( eFileLock<=SHARED_LOCK );
25781   if( pFile->eFileLock<=eFileLock ){
25782     return SQLITE_OK;
25783   }
25784   unixEnterMutex();
25785   pInode = pFile->pInode;
25786   assert( pInode->nShared!=0 );
25787   if( pFile->eFileLock>SHARED_LOCK ){
25788     assert( pInode->eFileLock==pFile->eFileLock );
25789     SimulateIOErrorBenign(1);
25790     SimulateIOError( h=(-1) )
25791     SimulateIOErrorBenign(0);
25792     
25793 #ifdef SQLITE_DEBUG
25794     /* When reducing a lock such that other processes can start
25795     ** reading the database file again, make sure that the
25796     ** transaction counter was updated if any part of the database
25797     ** file changed.  If the transaction counter is not updated,
25798     ** other connections to the same file might not realize that
25799     ** the file has changed and hence might not know to flush their
25800     ** cache.  The use of a stale cache can lead to database corruption.
25801     */
25802     assert( pFile->inNormalWrite==0
25803            || pFile->dbUpdate==0
25804            || pFile->transCntrChng==1 );
25805     pFile->inNormalWrite = 0;
25806 #endif
25807     
25808     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
25809       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
25810       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
25811         /* only re-establish the shared lock if necessary */
25812         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25813         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
25814       } else {
25815         skipShared = 1;
25816       }
25817     }
25818     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
25819       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25820     } 
25821     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
25822       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25823       if( !rc ){ 
25824         context->reserved = 0; 
25825       }
25826     }
25827     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
25828       pInode->eFileLock = SHARED_LOCK;
25829     }
25830   }
25831   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
25832
25833     /* Decrement the shared lock counter.  Release the lock using an
25834     ** OS call only when all threads in this same process have released
25835     ** the lock.
25836     */
25837     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25838     pInode->nShared--;
25839     if( pInode->nShared==0 ){
25840       SimulateIOErrorBenign(1);
25841       SimulateIOError( h=(-1) )
25842       SimulateIOErrorBenign(0);
25843       if( !skipShared ){
25844         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
25845       }
25846       if( !rc ){
25847         pInode->eFileLock = NO_LOCK;
25848         pFile->eFileLock = NO_LOCK;
25849       }
25850     }
25851     if( rc==SQLITE_OK ){
25852       pInode->nLock--;
25853       assert( pInode->nLock>=0 );
25854       if( pInode->nLock==0 ){
25855         closePendingFds(pFile);
25856       }
25857     }
25858   }
25859   
25860   unixLeaveMutex();
25861   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25862   return rc;
25863 }
25864
25865 /*
25866 ** Close a file & cleanup AFP specific locking context 
25867 */
25868 static int afpClose(sqlite3_file *id) {
25869   int rc = SQLITE_OK;
25870   if( id ){
25871     unixFile *pFile = (unixFile*)id;
25872     afpUnlock(id, NO_LOCK);
25873     unixEnterMutex();
25874     if( pFile->pInode && pFile->pInode->nLock ){
25875       /* If there are outstanding locks, do not actually close the file just
25876       ** yet because that would clear those locks.  Instead, add the file
25877       ** descriptor to pInode->aPending.  It will be automatically closed when
25878       ** the last lock is cleared.
25879       */
25880       setPendingFd(pFile);
25881     }
25882     releaseInodeInfo(pFile);
25883     sqlite3_free(pFile->lockingContext);
25884     rc = closeUnixFile(id);
25885     unixLeaveMutex();
25886   }
25887   return rc;
25888 }
25889
25890 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25891 /*
25892 ** The code above is the AFP lock implementation.  The code is specific
25893 ** to MacOSX and does not work on other unix platforms.  No alternative
25894 ** is available.  If you don't compile for a mac, then the "unix-afp"
25895 ** VFS is not available.
25896 **
25897 ********************* End of the AFP lock implementation **********************
25898 ******************************************************************************/
25899
25900 /******************************************************************************
25901 *************************** Begin NFS Locking ********************************/
25902
25903 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25904 /*
25905  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25906  ** must be either NO_LOCK or SHARED_LOCK.
25907  **
25908  ** If the locking level of the file descriptor is already at or below
25909  ** the requested locking level, this routine is a no-op.
25910  */
25911 static int nfsUnlock(sqlite3_file *id, int eFileLock){
25912   return posixUnlock(id, eFileLock, 1);
25913 }
25914
25915 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25916 /*
25917 ** The code above is the NFS lock implementation.  The code is specific
25918 ** to MacOSX and does not work on other unix platforms.  No alternative
25919 ** is available.  
25920 **
25921 ********************* End of the NFS lock implementation **********************
25922 ******************************************************************************/
25923
25924 /******************************************************************************
25925 **************** Non-locking sqlite3_file methods *****************************
25926 **
25927 ** The next division contains implementations for all methods of the 
25928 ** sqlite3_file object other than the locking methods.  The locking
25929 ** methods were defined in divisions above (one locking method per
25930 ** division).  Those methods that are common to all locking modes
25931 ** are gather together into this division.
25932 */
25933
25934 /*
25935 ** Seek to the offset passed as the second argument, then read cnt 
25936 ** bytes into pBuf. Return the number of bytes actually read.
25937 **
25938 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
25939 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
25940 ** one system to another.  Since SQLite does not define USE_PREAD
25941 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
25942 ** See tickets #2741 and #2681.
25943 **
25944 ** To avoid stomping the errno value on a failed read the lastErrno value
25945 ** is set before returning.
25946 */
25947 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
25948   int got;
25949   int prior = 0;
25950 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25951   i64 newOffset;
25952 #endif
25953   TIMER_START;
25954   assert( cnt==(cnt&0x1ffff) );
25955   cnt &= 0x1ffff;
25956   do{
25957 #if defined(USE_PREAD)
25958     got = osPread(id->h, pBuf, cnt, offset);
25959     SimulateIOError( got = -1 );
25960 #elif defined(USE_PREAD64)
25961     got = osPread64(id->h, pBuf, cnt, offset);
25962     SimulateIOError( got = -1 );
25963 #else
25964     newOffset = lseek(id->h, offset, SEEK_SET);
25965     SimulateIOError( newOffset-- );
25966     if( newOffset!=offset ){
25967       if( newOffset == -1 ){
25968         ((unixFile*)id)->lastErrno = errno;
25969       }else{
25970         ((unixFile*)id)->lastErrno = 0;
25971       }
25972       return -1;
25973     }
25974     got = osRead(id->h, pBuf, cnt);
25975 #endif
25976     if( got==cnt ) break;
25977     if( got<0 ){
25978       if( errno==EINTR ){ got = 1; continue; }
25979       prior = 0;
25980       ((unixFile*)id)->lastErrno = errno;
25981       break;
25982     }else if( got>0 ){
25983       cnt -= got;
25984       offset += got;
25985       prior += got;
25986       pBuf = (void*)(got + (char*)pBuf);
25987     }
25988   }while( got>0 );
25989   TIMER_END;
25990   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
25991             id->h, got+prior, offset-prior, TIMER_ELAPSED));
25992   return got+prior;
25993 }
25994
25995 /*
25996 ** Read data from a file into a buffer.  Return SQLITE_OK if all
25997 ** bytes were read successfully and SQLITE_IOERR if anything goes
25998 ** wrong.
25999 */
26000 static int unixRead(
26001   sqlite3_file *id, 
26002   void *pBuf, 
26003   int amt,
26004   sqlite3_int64 offset
26005 ){
26006   unixFile *pFile = (unixFile *)id;
26007   int got;
26008   assert( id );
26009
26010   /* If this is a database file (not a journal, master-journal or temp
26011   ** file), the bytes in the locking range should never be read or written. */
26012 #if 0
26013   assert( pFile->pUnused==0
26014        || offset>=PENDING_BYTE+512
26015        || offset+amt<=PENDING_BYTE 
26016   );
26017 #endif
26018
26019   got = seekAndRead(pFile, offset, pBuf, amt);
26020   if( got==amt ){
26021     return SQLITE_OK;
26022   }else if( got<0 ){
26023     /* lastErrno set by seekAndRead */
26024     return SQLITE_IOERR_READ;
26025   }else{
26026     pFile->lastErrno = 0; /* not a system error */
26027     /* Unread parts of the buffer must be zero-filled */
26028     memset(&((char*)pBuf)[got], 0, amt-got);
26029     return SQLITE_IOERR_SHORT_READ;
26030   }
26031 }
26032
26033 /*
26034 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
26035 ** Return the number of bytes actually read.  Update the offset.
26036 **
26037 ** To avoid stomping the errno value on a failed write the lastErrno value
26038 ** is set before returning.
26039 */
26040 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
26041   int got;
26042 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
26043   i64 newOffset;
26044 #endif
26045   assert( cnt==(cnt&0x1ffff) );
26046   cnt &= 0x1ffff;
26047   TIMER_START;
26048 #if defined(USE_PREAD)
26049   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
26050 #elif defined(USE_PREAD64)
26051   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
26052 #else
26053   do{
26054     newOffset = lseek(id->h, offset, SEEK_SET);
26055     SimulateIOError( newOffset-- );
26056     if( newOffset!=offset ){
26057       if( newOffset == -1 ){
26058         ((unixFile*)id)->lastErrno = errno;
26059       }else{
26060         ((unixFile*)id)->lastErrno = 0;
26061       }
26062       return -1;
26063     }
26064     got = osWrite(id->h, pBuf, cnt);
26065   }while( got<0 && errno==EINTR );
26066 #endif
26067   TIMER_END;
26068   if( got<0 ){
26069     ((unixFile*)id)->lastErrno = errno;
26070   }
26071
26072   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
26073   return got;
26074 }
26075
26076
26077 /*
26078 ** Write data from a buffer into a file.  Return SQLITE_OK on success
26079 ** or some other error code on failure.
26080 */
26081 static int unixWrite(
26082   sqlite3_file *id, 
26083   const void *pBuf, 
26084   int amt,
26085   sqlite3_int64 offset 
26086 ){
26087   unixFile *pFile = (unixFile*)id;
26088   int wrote = 0;
26089   assert( id );
26090   assert( amt>0 );
26091
26092   /* If this is a database file (not a journal, master-journal or temp
26093   ** file), the bytes in the locking range should never be read or written. */
26094 #if 0
26095   assert( pFile->pUnused==0
26096        || offset>=PENDING_BYTE+512
26097        || offset+amt<=PENDING_BYTE 
26098   );
26099 #endif
26100
26101 #ifdef SQLITE_DEBUG
26102   /* If we are doing a normal write to a database file (as opposed to
26103   ** doing a hot-journal rollback or a write to some file other than a
26104   ** normal database file) then record the fact that the database
26105   ** has changed.  If the transaction counter is modified, record that
26106   ** fact too.
26107   */
26108   if( pFile->inNormalWrite ){
26109     pFile->dbUpdate = 1;  /* The database has been modified */
26110     if( offset<=24 && offset+amt>=27 ){
26111       int rc;
26112       char oldCntr[4];
26113       SimulateIOErrorBenign(1);
26114       rc = seekAndRead(pFile, 24, oldCntr, 4);
26115       SimulateIOErrorBenign(0);
26116       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
26117         pFile->transCntrChng = 1;  /* The transaction counter has changed */
26118       }
26119     }
26120   }
26121 #endif
26122
26123   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
26124     amt -= wrote;
26125     offset += wrote;
26126     pBuf = &((char*)pBuf)[wrote];
26127   }
26128   SimulateIOError(( wrote=(-1), amt=1 ));
26129   SimulateDiskfullError(( wrote=0, amt=1 ));
26130
26131   if( amt>0 ){
26132     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
26133       /* lastErrno set by seekAndWrite */
26134       return SQLITE_IOERR_WRITE;
26135     }else{
26136       pFile->lastErrno = 0; /* not a system error */
26137       return SQLITE_FULL;
26138     }
26139   }
26140
26141   return SQLITE_OK;
26142 }
26143
26144 #ifdef SQLITE_TEST
26145 /*
26146 ** Count the number of fullsyncs and normal syncs.  This is used to test
26147 ** that syncs and fullsyncs are occurring at the right times.
26148 */
26149 SQLITE_API int sqlite3_sync_count = 0;
26150 SQLITE_API int sqlite3_fullsync_count = 0;
26151 #endif
26152
26153 /*
26154 ** We do not trust systems to provide a working fdatasync().  Some do.
26155 ** Others do no.  To be safe, we will stick with the (slightly slower)
26156 ** fsync(). If you know that your system does support fdatasync() correctly,
26157 ** then simply compile with -Dfdatasync=fdatasync
26158 */
26159 #if !defined(fdatasync)
26160 # define fdatasync fsync
26161 #endif
26162
26163 /*
26164 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
26165 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
26166 ** only available on Mac OS X.  But that could change.
26167 */
26168 #ifdef F_FULLFSYNC
26169 # define HAVE_FULLFSYNC 1
26170 #else
26171 # define HAVE_FULLFSYNC 0
26172 #endif
26173
26174
26175 /*
26176 ** The fsync() system call does not work as advertised on many
26177 ** unix systems.  The following procedure is an attempt to make
26178 ** it work better.
26179 **
26180 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
26181 ** for testing when we want to run through the test suite quickly.
26182 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
26183 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
26184 ** or power failure will likely corrupt the database file.
26185 **
26186 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
26187 ** The idea behind dataOnly is that it should only write the file content
26188 ** to disk, not the inode.  We only set dataOnly if the file size is 
26189 ** unchanged since the file size is part of the inode.  However, 
26190 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
26191 ** file size has changed.  The only real difference between fdatasync()
26192 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
26193 ** inode if the mtime or owner or other inode attributes have changed.
26194 ** We only care about the file size, not the other file attributes, so
26195 ** as far as SQLite is concerned, an fdatasync() is always adequate.
26196 ** So, we always use fdatasync() if it is available, regardless of
26197 ** the value of the dataOnly flag.
26198 */
26199 static int full_fsync(int fd, int fullSync, int dataOnly){
26200   int rc;
26201
26202   /* The following "ifdef/elif/else/" block has the same structure as
26203   ** the one below. It is replicated here solely to avoid cluttering 
26204   ** up the real code with the UNUSED_PARAMETER() macros.
26205   */
26206 #ifdef SQLITE_NO_SYNC
26207   UNUSED_PARAMETER(fd);
26208   UNUSED_PARAMETER(fullSync);
26209   UNUSED_PARAMETER(dataOnly);
26210 #elif HAVE_FULLFSYNC
26211   UNUSED_PARAMETER(dataOnly);
26212 #else
26213   UNUSED_PARAMETER(fullSync);
26214   UNUSED_PARAMETER(dataOnly);
26215 #endif
26216
26217   /* Record the number of times that we do a normal fsync() and 
26218   ** FULLSYNC.  This is used during testing to verify that this procedure
26219   ** gets called with the correct arguments.
26220   */
26221 #ifdef SQLITE_TEST
26222   if( fullSync ) sqlite3_fullsync_count++;
26223   sqlite3_sync_count++;
26224 #endif
26225
26226   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
26227   ** no-op
26228   */
26229 #ifdef SQLITE_NO_SYNC
26230   rc = SQLITE_OK;
26231 #elif HAVE_FULLFSYNC
26232   if( fullSync ){
26233     rc = osFcntl(fd, F_FULLFSYNC, 0);
26234   }else{
26235     rc = 1;
26236   }
26237   /* If the FULLFSYNC failed, fall back to attempting an fsync().
26238   ** It shouldn't be possible for fullfsync to fail on the local 
26239   ** file system (on OSX), so failure indicates that FULLFSYNC
26240   ** isn't supported for this file system. So, attempt an fsync 
26241   ** and (for now) ignore the overhead of a superfluous fcntl call.  
26242   ** It'd be better to detect fullfsync support once and avoid 
26243   ** the fcntl call every time sync is called.
26244   */
26245   if( rc ) rc = fsync(fd);
26246
26247 #elif defined(__APPLE__)
26248   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
26249   ** so currently we default to the macro that redefines fdatasync to fsync
26250   */
26251   rc = fsync(fd);
26252 #else 
26253   rc = fdatasync(fd);
26254 #if OS_VXWORKS
26255   if( rc==-1 && errno==ENOTSUP ){
26256     rc = fsync(fd);
26257   }
26258 #endif /* OS_VXWORKS */
26259 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
26260
26261   if( OS_VXWORKS && rc!= -1 ){
26262     rc = 0;
26263   }
26264   return rc;
26265 }
26266
26267 /*
26268 ** Open a file descriptor to the directory containing file zFilename.
26269 ** If successful, *pFd is set to the opened file descriptor and
26270 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
26271 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
26272 ** value.
26273 **
26274 ** The directory file descriptor is used for only one thing - to
26275 ** fsync() a directory to make sure file creation and deletion events
26276 ** are flushed to disk.  Such fsyncs are not needed on newer
26277 ** journaling filesystems, but are required on older filesystems.
26278 **
26279 ** This routine can be overridden using the xSetSysCall interface.
26280 ** The ability to override this routine was added in support of the
26281 ** chromium sandbox.  Opening a directory is a security risk (we are
26282 ** told) so making it overrideable allows the chromium sandbox to
26283 ** replace this routine with a harmless no-op.  To make this routine
26284 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
26285 ** *pFd set to a negative number.
26286 **
26287 ** If SQLITE_OK is returned, the caller is responsible for closing
26288 ** the file descriptor *pFd using close().
26289 */
26290 static int openDirectory(const char *zFilename, int *pFd){
26291   int ii;
26292   int fd = -1;
26293   char zDirname[MAX_PATHNAME+1];
26294
26295   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
26296   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
26297   if( ii>0 ){
26298     zDirname[ii] = '\0';
26299     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
26300     if( fd>=0 ){
26301       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
26302     }
26303   }
26304   *pFd = fd;
26305   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
26306 }
26307
26308 /*
26309 ** Make sure all writes to a particular file are committed to disk.
26310 **
26311 ** If dataOnly==0 then both the file itself and its metadata (file
26312 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
26313 ** file data is synced.
26314 **
26315 ** Under Unix, also make sure that the directory entry for the file
26316 ** has been created by fsync-ing the directory that contains the file.
26317 ** If we do not do this and we encounter a power failure, the directory
26318 ** entry for the journal might not exist after we reboot.  The next
26319 ** SQLite to access the file will not know that the journal exists (because
26320 ** the directory entry for the journal was never created) and the transaction
26321 ** will not roll back - possibly leading to database corruption.
26322 */
26323 static int unixSync(sqlite3_file *id, int flags){
26324   int rc;
26325   unixFile *pFile = (unixFile*)id;
26326
26327   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
26328   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
26329
26330   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
26331   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
26332       || (flags&0x0F)==SQLITE_SYNC_FULL
26333   );
26334
26335   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
26336   ** line is to test that doing so does not cause any problems.
26337   */
26338   SimulateDiskfullError( return SQLITE_FULL );
26339
26340   assert( pFile );
26341   OSTRACE(("SYNC    %-3d\n", pFile->h));
26342   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
26343   SimulateIOError( rc=1 );
26344   if( rc ){
26345     pFile->lastErrno = errno;
26346     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
26347   }
26348
26349   /* Also fsync the directory containing the file if the DIRSYNC flag
26350   ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
26351   ** are unable to fsync a directory, so ignore errors on the fsync.
26352   */
26353   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
26354     int dirfd;
26355     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
26356             HAVE_FULLFSYNC, isFullsync));
26357     rc = osOpenDirectory(pFile->zPath, &dirfd);
26358     if( rc==SQLITE_OK && dirfd>=0 ){
26359       full_fsync(dirfd, 0, 0);
26360       robust_close(pFile, dirfd, __LINE__);
26361     }else if( rc==SQLITE_CANTOPEN ){
26362       rc = SQLITE_OK;
26363     }
26364     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
26365   }
26366   return rc;
26367 }
26368
26369 /*
26370 ** Truncate an open file to a specified size
26371 */
26372 static int unixTruncate(sqlite3_file *id, i64 nByte){
26373   unixFile *pFile = (unixFile *)id;
26374   int rc;
26375   assert( pFile );
26376   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
26377
26378   /* If the user has configured a chunk-size for this file, truncate the
26379   ** file so that it consists of an integer number of chunks (i.e. the
26380   ** actual file size after the operation may be larger than the requested
26381   ** size).
26382   */
26383   if( pFile->szChunk>0 ){
26384     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
26385   }
26386
26387   rc = robust_ftruncate(pFile->h, (off_t)nByte);
26388   if( rc ){
26389     pFile->lastErrno = errno;
26390     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26391   }else{
26392 #ifdef SQLITE_DEBUG
26393     /* If we are doing a normal write to a database file (as opposed to
26394     ** doing a hot-journal rollback or a write to some file other than a
26395     ** normal database file) and we truncate the file to zero length,
26396     ** that effectively updates the change counter.  This might happen
26397     ** when restoring a database using the backup API from a zero-length
26398     ** source.
26399     */
26400     if( pFile->inNormalWrite && nByte==0 ){
26401       pFile->transCntrChng = 1;
26402     }
26403 #endif
26404
26405     return SQLITE_OK;
26406   }
26407 }
26408
26409 /*
26410 ** Determine the current size of a file in bytes
26411 */
26412 static int unixFileSize(sqlite3_file *id, i64 *pSize){
26413   int rc;
26414   struct stat buf;
26415   assert( id );
26416   rc = osFstat(((unixFile*)id)->h, &buf);
26417   SimulateIOError( rc=1 );
26418   if( rc!=0 ){
26419     ((unixFile*)id)->lastErrno = errno;
26420     return SQLITE_IOERR_FSTAT;
26421   }
26422   *pSize = buf.st_size;
26423
26424   /* When opening a zero-size database, the findInodeInfo() procedure
26425   ** writes a single byte into that file in order to work around a bug
26426   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
26427   ** layers, we need to report this file size as zero even though it is
26428   ** really 1.   Ticket #3260.
26429   */
26430   if( *pSize==1 ) *pSize = 0;
26431
26432
26433   return SQLITE_OK;
26434 }
26435
26436 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26437 /*
26438 ** Handler for proxy-locking file-control verbs.  Defined below in the
26439 ** proxying locking division.
26440 */
26441 static int proxyFileControl(sqlite3_file*,int,void*);
26442 #endif
26443
26444 /* 
26445 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
26446 ** file-control operation.  Enlarge the database to nBytes in size
26447 ** (rounded up to the next chunk-size).  If the database is already
26448 ** nBytes or larger, this routine is a no-op.
26449 */
26450 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
26451   if( pFile->szChunk>0 ){
26452     i64 nSize;                    /* Required file size */
26453     struct stat buf;              /* Used to hold return values of fstat() */
26454    
26455     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
26456
26457     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
26458     if( nSize>(i64)buf.st_size ){
26459
26460 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
26461       /* The code below is handling the return value of osFallocate() 
26462       ** correctly. posix_fallocate() is defined to "returns zero on success, 
26463       ** or an error number on  failure". See the manpage for details. */
26464       int err;
26465       do{
26466         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
26467       }while( err==EINTR );
26468       if( err ) return SQLITE_IOERR_WRITE;
26469 #else
26470       /* If the OS does not have posix_fallocate(), fake it. First use
26471       ** ftruncate() to set the file size, then write a single byte to
26472       ** the last byte in each block within the extended region. This
26473       ** is the same technique used by glibc to implement posix_fallocate()
26474       ** on systems that do not have a real fallocate() system call.
26475       */
26476       int nBlk = buf.st_blksize;  /* File-system block size */
26477       i64 iWrite;                 /* Next offset to write to */
26478
26479       if( robust_ftruncate(pFile->h, nSize) ){
26480         pFile->lastErrno = errno;
26481         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26482       }
26483       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
26484       while( iWrite<nSize ){
26485         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
26486         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
26487         iWrite += nBlk;
26488       }
26489 #endif
26490     }
26491   }
26492
26493   return SQLITE_OK;
26494 }
26495
26496 /*
26497 ** If *pArg is inititially negative then this is a query.  Set *pArg to
26498 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
26499 **
26500 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
26501 */
26502 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
26503   if( *pArg<0 ){
26504     *pArg = (pFile->ctrlFlags & mask)!=0;
26505   }else if( (*pArg)==0 ){
26506     pFile->ctrlFlags &= ~mask;
26507   }else{
26508     pFile->ctrlFlags |= mask;
26509   }
26510 }
26511
26512 /* Forward declaration */
26513 static int unixGetTempname(int nBuf, char *zBuf);
26514
26515 /*
26516 ** Information and control of an open file handle.
26517 */
26518 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
26519   unixFile *pFile = (unixFile*)id;
26520   switch( op ){
26521     case SQLITE_FCNTL_LOCKSTATE: {
26522       *(int*)pArg = pFile->eFileLock;
26523       return SQLITE_OK;
26524     }
26525     case SQLITE_LAST_ERRNO: {
26526       *(int*)pArg = pFile->lastErrno;
26527       return SQLITE_OK;
26528     }
26529     case SQLITE_FCNTL_CHUNK_SIZE: {
26530       pFile->szChunk = *(int *)pArg;
26531       return SQLITE_OK;
26532     }
26533     case SQLITE_FCNTL_SIZE_HINT: {
26534       int rc;
26535       SimulateIOErrorBenign(1);
26536       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
26537       SimulateIOErrorBenign(0);
26538       return rc;
26539     }
26540     case SQLITE_FCNTL_PERSIST_WAL: {
26541       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
26542       return SQLITE_OK;
26543     }
26544     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
26545       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
26546       return SQLITE_OK;
26547     }
26548     case SQLITE_FCNTL_VFSNAME: {
26549       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
26550       return SQLITE_OK;
26551     }
26552     case SQLITE_FCNTL_TEMPFILENAME: {
26553       char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
26554       if( zTFile ){
26555         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
26556         *(char**)pArg = zTFile;
26557       }
26558       return SQLITE_OK;
26559     }
26560 #ifdef SQLITE_DEBUG
26561     /* The pager calls this method to signal that it has done
26562     ** a rollback and that the database is therefore unchanged and
26563     ** it hence it is OK for the transaction change counter to be
26564     ** unchanged.
26565     */
26566     case SQLITE_FCNTL_DB_UNCHANGED: {
26567       ((unixFile*)id)->dbUpdate = 0;
26568       return SQLITE_OK;
26569     }
26570 #endif
26571 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26572     case SQLITE_SET_LOCKPROXYFILE:
26573     case SQLITE_GET_LOCKPROXYFILE: {
26574       return proxyFileControl(id,op,pArg);
26575     }
26576 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
26577   }
26578   return SQLITE_NOTFOUND;
26579 }
26580
26581 /*
26582 ** Return the sector size in bytes of the underlying block device for
26583 ** the specified file. This is almost always 512 bytes, but may be
26584 ** larger for some devices.
26585 **
26586 ** SQLite code assumes this function cannot fail. It also assumes that
26587 ** if two files are created in the same file-system directory (i.e.
26588 ** a database and its journal file) that the sector size will be the
26589 ** same for both.
26590 */
26591 #ifndef __QNXNTO__ 
26592 static int unixSectorSize(sqlite3_file *NotUsed){
26593   UNUSED_PARAMETER(NotUsed);
26594   return SQLITE_DEFAULT_SECTOR_SIZE;
26595 }
26596 #endif
26597
26598 /*
26599 ** The following version of unixSectorSize() is optimized for QNX.
26600 */
26601 #ifdef __QNXNTO__
26602 #include <sys/dcmd_blk.h>
26603 #include <sys/statvfs.h>
26604 static int unixSectorSize(sqlite3_file *id){
26605   unixFile *pFile = (unixFile*)id;
26606   if( pFile->sectorSize == 0 ){
26607     struct statvfs fsInfo;
26608        
26609     /* Set defaults for non-supported filesystems */
26610     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
26611     pFile->deviceCharacteristics = 0;
26612     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
26613       return pFile->sectorSize;
26614     }
26615
26616     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
26617       pFile->sectorSize = fsInfo.f_bsize;
26618       pFile->deviceCharacteristics =
26619         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
26620         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26621                                       ** the write succeeds */
26622         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26623                                       ** so it is ordered */
26624         0;
26625     }else if( strstr(fsInfo.f_basetype, "etfs") ){
26626       pFile->sectorSize = fsInfo.f_bsize;
26627       pFile->deviceCharacteristics =
26628         /* etfs cluster size writes are atomic */
26629         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
26630         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26631                                       ** the write succeeds */
26632         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26633                                       ** so it is ordered */
26634         0;
26635     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
26636       pFile->sectorSize = fsInfo.f_bsize;
26637       pFile->deviceCharacteristics =
26638         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
26639         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26640                                       ** the write succeeds */
26641         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26642                                       ** so it is ordered */
26643         0;
26644     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
26645       pFile->sectorSize = fsInfo.f_bsize;
26646       pFile->deviceCharacteristics =
26647         /* full bitset of atomics from max sector size and smaller */
26648         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
26649         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26650                                       ** so it is ordered */
26651         0;
26652     }else if( strstr(fsInfo.f_basetype, "dos") ){
26653       pFile->sectorSize = fsInfo.f_bsize;
26654       pFile->deviceCharacteristics =
26655         /* full bitset of atomics from max sector size and smaller */
26656         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
26657         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26658                                       ** so it is ordered */
26659         0;
26660     }else{
26661       pFile->deviceCharacteristics =
26662         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
26663         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26664                                       ** the write succeeds */
26665         0;
26666     }
26667   }
26668   /* Last chance verification.  If the sector size isn't a multiple of 512
26669   ** then it isn't valid.*/
26670   if( pFile->sectorSize % 512 != 0 ){
26671     pFile->deviceCharacteristics = 0;
26672     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
26673   }
26674   return pFile->sectorSize;
26675 }
26676 #endif /* __QNXNTO__ */
26677
26678 /*
26679 ** Return the device characteristics for the file.
26680 **
26681 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
26682 ** However, that choice is contraversial since technically the underlying
26683 ** file system does not always provide powersafe overwrites.  (In other
26684 ** words, after a power-loss event, parts of the file that were never
26685 ** written might end up being altered.)  However, non-PSOW behavior is very,
26686 ** very rare.  And asserting PSOW makes a large reduction in the amount
26687 ** of required I/O for journaling, since a lot of padding is eliminated.
26688 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
26689 ** available to turn it off and URI query parameter available to turn it off.
26690 */
26691 static int unixDeviceCharacteristics(sqlite3_file *id){
26692   unixFile *p = (unixFile*)id;
26693   int rc = 0;
26694 #ifdef __QNXNTO__
26695   if( p->sectorSize==0 ) unixSectorSize(id);
26696   rc = p->deviceCharacteristics;
26697 #endif
26698   if( p->ctrlFlags & UNIXFILE_PSOW ){
26699     rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
26700   }
26701   return rc;
26702 }
26703
26704 #ifndef SQLITE_OMIT_WAL
26705
26706
26707 /*
26708 ** Object used to represent an shared memory buffer.  
26709 **
26710 ** When multiple threads all reference the same wal-index, each thread
26711 ** has its own unixShm object, but they all point to a single instance
26712 ** of this unixShmNode object.  In other words, each wal-index is opened
26713 ** only once per process.
26714 **
26715 ** Each unixShmNode object is connected to a single unixInodeInfo object.
26716 ** We could coalesce this object into unixInodeInfo, but that would mean
26717 ** every open file that does not use shared memory (in other words, most
26718 ** open files) would have to carry around this extra information.  So
26719 ** the unixInodeInfo object contains a pointer to this unixShmNode object
26720 ** and the unixShmNode object is created only when needed.
26721 **
26722 ** unixMutexHeld() must be true when creating or destroying
26723 ** this object or while reading or writing the following fields:
26724 **
26725 **      nRef
26726 **
26727 ** The following fields are read-only after the object is created:
26728 ** 
26729 **      fid
26730 **      zFilename
26731 **
26732 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
26733 ** unixMutexHeld() is true when reading or writing any other field
26734 ** in this structure.
26735 */
26736 struct unixShmNode {
26737   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
26738   sqlite3_mutex *mutex;      /* Mutex to access this object */
26739   char *zFilename;           /* Name of the mmapped file */
26740   int h;                     /* Open file descriptor */
26741   int szRegion;              /* Size of shared-memory regions */
26742   u16 nRegion;               /* Size of array apRegion */
26743   u8 isReadonly;             /* True if read-only */
26744   char **apRegion;           /* Array of mapped shared-memory regions */
26745   int nRef;                  /* Number of unixShm objects pointing to this */
26746   unixShm *pFirst;           /* All unixShm objects pointing to this */
26747 #ifdef SQLITE_DEBUG
26748   u8 exclMask;               /* Mask of exclusive locks held */
26749   u8 sharedMask;             /* Mask of shared locks held */
26750   u8 nextShmId;              /* Next available unixShm.id value */
26751 #endif
26752 };
26753
26754 /*
26755 ** Structure used internally by this VFS to record the state of an
26756 ** open shared memory connection.
26757 **
26758 ** The following fields are initialized when this object is created and
26759 ** are read-only thereafter:
26760 **
26761 **    unixShm.pFile
26762 **    unixShm.id
26763 **
26764 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
26765 ** while accessing any read/write fields.
26766 */
26767 struct unixShm {
26768   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
26769   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
26770   u8 hasMutex;               /* True if holding the unixShmNode mutex */
26771   u8 id;                     /* Id of this connection within its unixShmNode */
26772   u16 sharedMask;            /* Mask of shared locks held */
26773   u16 exclMask;              /* Mask of exclusive locks held */
26774 };
26775
26776 /*
26777 ** Constants used for locking
26778 */
26779 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
26780 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
26781
26782 /*
26783 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
26784 **
26785 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
26786 ** otherwise.
26787 */
26788 static int unixShmSystemLock(
26789   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
26790   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
26791   int ofst,              /* First byte of the locking range */
26792   int n                  /* Number of bytes to lock */
26793 ){
26794   struct flock f;       /* The posix advisory locking structure */
26795   int rc = SQLITE_OK;   /* Result code form fcntl() */
26796
26797   /* Access to the unixShmNode object is serialized by the caller */
26798   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
26799
26800   /* Shared locks never span more than one byte */
26801   assert( n==1 || lockType!=F_RDLCK );
26802
26803   /* Locks are within range */
26804   assert( n>=1 && n<SQLITE_SHM_NLOCK );
26805
26806   if( pShmNode->h>=0 ){
26807     /* Initialize the locking parameters */
26808     memset(&f, 0, sizeof(f));
26809     f.l_type = lockType;
26810     f.l_whence = SEEK_SET;
26811     f.l_start = ofst;
26812     f.l_len = n;
26813
26814     rc = osFcntl(pShmNode->h, F_SETLK, &f);
26815     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
26816   }
26817
26818   /* Update the global lock state and do debug tracing */
26819 #ifdef SQLITE_DEBUG
26820   { u16 mask;
26821   OSTRACE(("SHM-LOCK "));
26822   mask = (1<<(ofst+n)) - (1<<ofst);
26823   if( rc==SQLITE_OK ){
26824     if( lockType==F_UNLCK ){
26825       OSTRACE(("unlock %d ok", ofst));
26826       pShmNode->exclMask &= ~mask;
26827       pShmNode->sharedMask &= ~mask;
26828     }else if( lockType==F_RDLCK ){
26829       OSTRACE(("read-lock %d ok", ofst));
26830       pShmNode->exclMask &= ~mask;
26831       pShmNode->sharedMask |= mask;
26832     }else{
26833       assert( lockType==F_WRLCK );
26834       OSTRACE(("write-lock %d ok", ofst));
26835       pShmNode->exclMask |= mask;
26836       pShmNode->sharedMask &= ~mask;
26837     }
26838   }else{
26839     if( lockType==F_UNLCK ){
26840       OSTRACE(("unlock %d failed", ofst));
26841     }else if( lockType==F_RDLCK ){
26842       OSTRACE(("read-lock failed"));
26843     }else{
26844       assert( lockType==F_WRLCK );
26845       OSTRACE(("write-lock %d failed", ofst));
26846     }
26847   }
26848   OSTRACE((" - afterwards %03x,%03x\n",
26849            pShmNode->sharedMask, pShmNode->exclMask));
26850   }
26851 #endif
26852
26853   return rc;        
26854 }
26855
26856
26857 /*
26858 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
26859 **
26860 ** This is not a VFS shared-memory method; it is a utility function called
26861 ** by VFS shared-memory methods.
26862 */
26863 static void unixShmPurge(unixFile *pFd){
26864   unixShmNode *p = pFd->pInode->pShmNode;
26865   assert( unixMutexHeld() );
26866   if( p && p->nRef==0 ){
26867     int i;
26868     assert( p->pInode==pFd->pInode );
26869     sqlite3_mutex_free(p->mutex);
26870     for(i=0; i<p->nRegion; i++){
26871       if( p->h>=0 ){
26872         munmap(p->apRegion[i], p->szRegion);
26873       }else{
26874         sqlite3_free(p->apRegion[i]);
26875       }
26876     }
26877     sqlite3_free(p->apRegion);
26878     if( p->h>=0 ){
26879       robust_close(pFd, p->h, __LINE__);
26880       p->h = -1;
26881     }
26882     p->pInode->pShmNode = 0;
26883     sqlite3_free(p);
26884   }
26885 }
26886
26887 /*
26888 ** Open a shared-memory area associated with open database file pDbFd.  
26889 ** This particular implementation uses mmapped files.
26890 **
26891 ** The file used to implement shared-memory is in the same directory
26892 ** as the open database file and has the same name as the open database
26893 ** file with the "-shm" suffix added.  For example, if the database file
26894 ** is "/home/user1/config.db" then the file that is created and mmapped
26895 ** for shared memory will be called "/home/user1/config.db-shm".  
26896 **
26897 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
26898 ** some other tmpfs mount. But if a file in a different directory
26899 ** from the database file is used, then differing access permissions
26900 ** or a chroot() might cause two different processes on the same
26901 ** database to end up using different files for shared memory - 
26902 ** meaning that their memory would not really be shared - resulting
26903 ** in database corruption.  Nevertheless, this tmpfs file usage
26904 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
26905 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
26906 ** option results in an incompatible build of SQLite;  builds of SQLite
26907 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
26908 ** same database file at the same time, database corruption will likely
26909 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
26910 ** "unsupported" and may go away in a future SQLite release.
26911 **
26912 ** When opening a new shared-memory file, if no other instances of that
26913 ** file are currently open, in this process or in other processes, then
26914 ** the file must be truncated to zero length or have its header cleared.
26915 **
26916 ** If the original database file (pDbFd) is using the "unix-excl" VFS
26917 ** that means that an exclusive lock is held on the database file and
26918 ** that no other processes are able to read or write the database.  In
26919 ** that case, we do not really need shared memory.  No shared memory
26920 ** file is created.  The shared memory will be simulated with heap memory.
26921 */
26922 static int unixOpenSharedMemory(unixFile *pDbFd){
26923   struct unixShm *p = 0;          /* The connection to be opened */
26924   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
26925   int rc;                         /* Result code */
26926   unixInodeInfo *pInode;          /* The inode of fd */
26927   char *zShmFilename;             /* Name of the file used for SHM */
26928   int nShmFilename;               /* Size of the SHM filename in bytes */
26929
26930   /* Allocate space for the new unixShm object. */
26931   p = sqlite3_malloc( sizeof(*p) );
26932   if( p==0 ) return SQLITE_NOMEM;
26933   memset(p, 0, sizeof(*p));
26934   assert( pDbFd->pShm==0 );
26935
26936   /* Check to see if a unixShmNode object already exists. Reuse an existing
26937   ** one if present. Create a new one if necessary.
26938   */
26939   unixEnterMutex();
26940   pInode = pDbFd->pInode;
26941   pShmNode = pInode->pShmNode;
26942   if( pShmNode==0 ){
26943     struct stat sStat;                 /* fstat() info for database file */
26944
26945     /* Call fstat() to figure out the permissions on the database file. If
26946     ** a new *-shm file is created, an attempt will be made to create it
26947     ** with the same permissions.
26948     */
26949     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
26950       rc = SQLITE_IOERR_FSTAT;
26951       goto shm_open_err;
26952     }
26953
26954 #ifdef SQLITE_SHM_DIRECTORY
26955     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
26956 #else
26957     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
26958 #endif
26959     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
26960     if( pShmNode==0 ){
26961       rc = SQLITE_NOMEM;
26962       goto shm_open_err;
26963     }
26964     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
26965     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
26966 #ifdef SQLITE_SHM_DIRECTORY
26967     sqlite3_snprintf(nShmFilename, zShmFilename, 
26968                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
26969                      (u32)sStat.st_ino, (u32)sStat.st_dev);
26970 #else
26971     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
26972     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
26973 #endif
26974     pShmNode->h = -1;
26975     pDbFd->pInode->pShmNode = pShmNode;
26976     pShmNode->pInode = pDbFd->pInode;
26977     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
26978     if( pShmNode->mutex==0 ){
26979       rc = SQLITE_NOMEM;
26980       goto shm_open_err;
26981     }
26982
26983     if( pInode->bProcessLock==0 ){
26984       int openFlags = O_RDWR | O_CREAT;
26985       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
26986         openFlags = O_RDONLY;
26987         pShmNode->isReadonly = 1;
26988       }
26989       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
26990       if( pShmNode->h<0 ){
26991         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
26992         goto shm_open_err;
26993       }
26994
26995       /* If this process is running as root, make sure that the SHM file
26996       ** is owned by the same user that owns the original database.  Otherwise,
26997       ** the original owner will not be able to connect.
26998       */
26999       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
27000   
27001       /* Check to see if another process is holding the dead-man switch.
27002       ** If not, truncate the file to zero length. 
27003       */
27004       rc = SQLITE_OK;
27005       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
27006         if( robust_ftruncate(pShmNode->h, 0) ){
27007           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
27008         }
27009       }
27010       if( rc==SQLITE_OK ){
27011         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
27012       }
27013       if( rc ) goto shm_open_err;
27014     }
27015   }
27016
27017   /* Make the new connection a child of the unixShmNode */
27018   p->pShmNode = pShmNode;
27019 #ifdef SQLITE_DEBUG
27020   p->id = pShmNode->nextShmId++;
27021 #endif
27022   pShmNode->nRef++;
27023   pDbFd->pShm = p;
27024   unixLeaveMutex();
27025
27026   /* The reference count on pShmNode has already been incremented under
27027   ** the cover of the unixEnterMutex() mutex and the pointer from the
27028   ** new (struct unixShm) object to the pShmNode has been set. All that is
27029   ** left to do is to link the new object into the linked list starting
27030   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
27031   ** mutex.
27032   */
27033   sqlite3_mutex_enter(pShmNode->mutex);
27034   p->pNext = pShmNode->pFirst;
27035   pShmNode->pFirst = p;
27036   sqlite3_mutex_leave(pShmNode->mutex);
27037   return SQLITE_OK;
27038
27039   /* Jump here on any error */
27040 shm_open_err:
27041   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
27042   sqlite3_free(p);
27043   unixLeaveMutex();
27044   return rc;
27045 }
27046
27047 /*
27048 ** This function is called to obtain a pointer to region iRegion of the 
27049 ** shared-memory associated with the database file fd. Shared-memory regions 
27050 ** are numbered starting from zero. Each shared-memory region is szRegion 
27051 ** bytes in size.
27052 **
27053 ** If an error occurs, an error code is returned and *pp is set to NULL.
27054 **
27055 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
27056 ** region has not been allocated (by any client, including one running in a
27057 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
27058 ** bExtend is non-zero and the requested shared-memory region has not yet 
27059 ** been allocated, it is allocated by this function.
27060 **
27061 ** If the shared-memory region has already been allocated or is allocated by
27062 ** this call as described above, then it is mapped into this processes 
27063 ** address space (if it is not already), *pp is set to point to the mapped 
27064 ** memory and SQLITE_OK returned.
27065 */
27066 static int unixShmMap(
27067   sqlite3_file *fd,               /* Handle open on database file */
27068   int iRegion,                    /* Region to retrieve */
27069   int szRegion,                   /* Size of regions */
27070   int bExtend,                    /* True to extend file if necessary */
27071   void volatile **pp              /* OUT: Mapped memory */
27072 ){
27073   unixFile *pDbFd = (unixFile*)fd;
27074   unixShm *p;
27075   unixShmNode *pShmNode;
27076   int rc = SQLITE_OK;
27077
27078   /* If the shared-memory file has not yet been opened, open it now. */
27079   if( pDbFd->pShm==0 ){
27080     rc = unixOpenSharedMemory(pDbFd);
27081     if( rc!=SQLITE_OK ) return rc;
27082   }
27083
27084   p = pDbFd->pShm;
27085   pShmNode = p->pShmNode;
27086   sqlite3_mutex_enter(pShmNode->mutex);
27087   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
27088   assert( pShmNode->pInode==pDbFd->pInode );
27089   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27090   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27091
27092   if( pShmNode->nRegion<=iRegion ){
27093     char **apNew;                      /* New apRegion[] array */
27094     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
27095     struct stat sStat;                 /* Used by fstat() */
27096
27097     pShmNode->szRegion = szRegion;
27098
27099     if( pShmNode->h>=0 ){
27100       /* The requested region is not mapped into this processes address space.
27101       ** Check to see if it has been allocated (i.e. if the wal-index file is
27102       ** large enough to contain the requested region).
27103       */
27104       if( osFstat(pShmNode->h, &sStat) ){
27105         rc = SQLITE_IOERR_SHMSIZE;
27106         goto shmpage_out;
27107       }
27108   
27109       if( sStat.st_size<nByte ){
27110         /* The requested memory region does not exist. If bExtend is set to
27111         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
27112         **
27113         ** Alternatively, if bExtend is true, use ftruncate() to allocate
27114         ** the requested memory region.
27115         */
27116         if( !bExtend ) goto shmpage_out;
27117 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27118         if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
27119           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
27120                             pShmNode->zFilename);
27121           goto shmpage_out;
27122         }
27123 #else
27124         if( robust_ftruncate(pShmNode->h, nByte) ){
27125           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
27126                             pShmNode->zFilename);
27127           goto shmpage_out;
27128         }
27129 #endif
27130       }
27131     }
27132
27133     /* Map the requested memory region into this processes address space. */
27134     apNew = (char **)sqlite3_realloc(
27135         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
27136     );
27137     if( !apNew ){
27138       rc = SQLITE_IOERR_NOMEM;
27139       goto shmpage_out;
27140     }
27141     pShmNode->apRegion = apNew;
27142     while(pShmNode->nRegion<=iRegion){
27143       void *pMem;
27144       if( pShmNode->h>=0 ){
27145         pMem = mmap(0, szRegion,
27146             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
27147             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
27148         );
27149         if( pMem==MAP_FAILED ){
27150           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
27151           goto shmpage_out;
27152         }
27153       }else{
27154         pMem = sqlite3_malloc(szRegion);
27155         if( pMem==0 ){
27156           rc = SQLITE_NOMEM;
27157           goto shmpage_out;
27158         }
27159         memset(pMem, 0, szRegion);
27160       }
27161       pShmNode->apRegion[pShmNode->nRegion] = pMem;
27162       pShmNode->nRegion++;
27163     }
27164   }
27165
27166 shmpage_out:
27167   if( pShmNode->nRegion>iRegion ){
27168     *pp = pShmNode->apRegion[iRegion];
27169   }else{
27170     *pp = 0;
27171   }
27172   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
27173   sqlite3_mutex_leave(pShmNode->mutex);
27174   return rc;
27175 }
27176
27177 /*
27178 ** Change the lock state for a shared-memory segment.
27179 **
27180 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
27181 ** different here than in posix.  In xShmLock(), one can go from unlocked
27182 ** to shared and back or from unlocked to exclusive and back.  But one may
27183 ** not go from shared to exclusive or from exclusive to shared.
27184 */
27185 static int unixShmLock(
27186   sqlite3_file *fd,          /* Database file holding the shared memory */
27187   int ofst,                  /* First lock to acquire or release */
27188   int n,                     /* Number of locks to acquire or release */
27189   int flags                  /* What to do with the lock */
27190 ){
27191   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
27192   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
27193   unixShm *pX;                          /* For looping over all siblings */
27194   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
27195   int rc = SQLITE_OK;                   /* Result code */
27196   u16 mask;                             /* Mask of locks to take or release */
27197
27198   assert( pShmNode==pDbFd->pInode->pShmNode );
27199   assert( pShmNode->pInode==pDbFd->pInode );
27200   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
27201   assert( n>=1 );
27202   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
27203        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
27204        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
27205        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
27206   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
27207   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27208   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27209
27210   mask = (1<<(ofst+n)) - (1<<ofst);
27211   assert( n>1 || mask==(1<<ofst) );
27212   sqlite3_mutex_enter(pShmNode->mutex);
27213   if( flags & SQLITE_SHM_UNLOCK ){
27214     u16 allMask = 0; /* Mask of locks held by siblings */
27215
27216     /* See if any siblings hold this same lock */
27217     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27218       if( pX==p ) continue;
27219       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
27220       allMask |= pX->sharedMask;
27221     }
27222
27223     /* Unlock the system-level locks */
27224     if( (mask & allMask)==0 ){
27225       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
27226     }else{
27227       rc = SQLITE_OK;
27228     }
27229
27230     /* Undo the local locks */
27231     if( rc==SQLITE_OK ){
27232       p->exclMask &= ~mask;
27233       p->sharedMask &= ~mask;
27234     } 
27235   }else if( flags & SQLITE_SHM_SHARED ){
27236     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
27237
27238     /* Find out which shared locks are already held by sibling connections.
27239     ** If any sibling already holds an exclusive lock, go ahead and return
27240     ** SQLITE_BUSY.
27241     */
27242     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27243       if( (pX->exclMask & mask)!=0 ){
27244         rc = SQLITE_BUSY;
27245         break;
27246       }
27247       allShared |= pX->sharedMask;
27248     }
27249
27250     /* Get shared locks at the system level, if necessary */
27251     if( rc==SQLITE_OK ){
27252       if( (allShared & mask)==0 ){
27253         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
27254       }else{
27255         rc = SQLITE_OK;
27256       }
27257     }
27258
27259     /* Get the local shared locks */
27260     if( rc==SQLITE_OK ){
27261       p->sharedMask |= mask;
27262     }
27263   }else{
27264     /* Make sure no sibling connections hold locks that will block this
27265     ** lock.  If any do, return SQLITE_BUSY right away.
27266     */
27267     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27268       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
27269         rc = SQLITE_BUSY;
27270         break;
27271       }
27272     }
27273   
27274     /* Get the exclusive locks at the system level.  Then if successful
27275     ** also mark the local connection as being locked.
27276     */
27277     if( rc==SQLITE_OK ){
27278       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
27279       if( rc==SQLITE_OK ){
27280         assert( (p->sharedMask & mask)==0 );
27281         p->exclMask |= mask;
27282       }
27283     }
27284   }
27285   sqlite3_mutex_leave(pShmNode->mutex);
27286   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
27287            p->id, getpid(), p->sharedMask, p->exclMask));
27288   return rc;
27289 }
27290
27291 /*
27292 ** Implement a memory barrier or memory fence on shared memory.  
27293 **
27294 ** All loads and stores begun before the barrier must complete before
27295 ** any load or store begun after the barrier.
27296 */
27297 static void unixShmBarrier(
27298   sqlite3_file *fd                /* Database file holding the shared memory */
27299 ){
27300   UNUSED_PARAMETER(fd);
27301   unixEnterMutex();
27302   unixLeaveMutex();
27303 }
27304
27305 /*
27306 ** Close a connection to shared-memory.  Delete the underlying 
27307 ** storage if deleteFlag is true.
27308 **
27309 ** If there is no shared memory associated with the connection then this
27310 ** routine is a harmless no-op.
27311 */
27312 static int unixShmUnmap(
27313   sqlite3_file *fd,               /* The underlying database file */
27314   int deleteFlag                  /* Delete shared-memory if true */
27315 ){
27316   unixShm *p;                     /* The connection to be closed */
27317   unixShmNode *pShmNode;          /* The underlying shared-memory file */
27318   unixShm **pp;                   /* For looping over sibling connections */
27319   unixFile *pDbFd;                /* The underlying database file */
27320
27321   pDbFd = (unixFile*)fd;
27322   p = pDbFd->pShm;
27323   if( p==0 ) return SQLITE_OK;
27324   pShmNode = p->pShmNode;
27325
27326   assert( pShmNode==pDbFd->pInode->pShmNode );
27327   assert( pShmNode->pInode==pDbFd->pInode );
27328
27329   /* Remove connection p from the set of connections associated
27330   ** with pShmNode */
27331   sqlite3_mutex_enter(pShmNode->mutex);
27332   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
27333   *pp = p->pNext;
27334
27335   /* Free the connection p */
27336   sqlite3_free(p);
27337   pDbFd->pShm = 0;
27338   sqlite3_mutex_leave(pShmNode->mutex);
27339
27340   /* If pShmNode->nRef has reached 0, then close the underlying
27341   ** shared-memory file, too */
27342   unixEnterMutex();
27343   assert( pShmNode->nRef>0 );
27344   pShmNode->nRef--;
27345   if( pShmNode->nRef==0 ){
27346     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
27347     unixShmPurge(pDbFd);
27348   }
27349   unixLeaveMutex();
27350
27351   return SQLITE_OK;
27352 }
27353
27354
27355 #else
27356 # define unixShmMap     0
27357 # define unixShmLock    0
27358 # define unixShmBarrier 0
27359 # define unixShmUnmap   0
27360 #endif /* #ifndef SQLITE_OMIT_WAL */
27361
27362 /*
27363 ** Here ends the implementation of all sqlite3_file methods.
27364 **
27365 ********************** End sqlite3_file Methods *******************************
27366 ******************************************************************************/
27367
27368 /*
27369 ** This division contains definitions of sqlite3_io_methods objects that
27370 ** implement various file locking strategies.  It also contains definitions
27371 ** of "finder" functions.  A finder-function is used to locate the appropriate
27372 ** sqlite3_io_methods object for a particular database file.  The pAppData
27373 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
27374 ** the correct finder-function for that VFS.
27375 **
27376 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
27377 ** object.  The only interesting finder-function is autolockIoFinder, which
27378 ** looks at the filesystem type and tries to guess the best locking
27379 ** strategy from that.
27380 **
27381 ** For finder-funtion F, two objects are created:
27382 **
27383 **    (1) The real finder-function named "FImpt()".
27384 **
27385 **    (2) A constant pointer to this function named just "F".
27386 **
27387 **
27388 ** A pointer to the F pointer is used as the pAppData value for VFS
27389 ** objects.  We have to do this instead of letting pAppData point
27390 ** directly at the finder-function since C90 rules prevent a void*
27391 ** from be cast into a function pointer.
27392 **
27393 **
27394 ** Each instance of this macro generates two objects:
27395 **
27396 **   *  A constant sqlite3_io_methods object call METHOD that has locking
27397 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
27398 **
27399 **   *  An I/O method finder function called FINDER that returns a pointer
27400 **      to the METHOD object in the previous bullet.
27401 */
27402 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
27403 static const sqlite3_io_methods METHOD = {                                   \
27404    VERSION,                    /* iVersion */                                \
27405    CLOSE,                      /* xClose */                                  \
27406    unixRead,                   /* xRead */                                   \
27407    unixWrite,                  /* xWrite */                                  \
27408    unixTruncate,               /* xTruncate */                               \
27409    unixSync,                   /* xSync */                                   \
27410    unixFileSize,               /* xFileSize */                               \
27411    LOCK,                       /* xLock */                                   \
27412    UNLOCK,                     /* xUnlock */                                 \
27413    CKLOCK,                     /* xCheckReservedLock */                      \
27414    unixFileControl,            /* xFileControl */                            \
27415    unixSectorSize,             /* xSectorSize */                             \
27416    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
27417    unixShmMap,                 /* xShmMap */                                 \
27418    unixShmLock,                /* xShmLock */                                \
27419    unixShmBarrier,             /* xShmBarrier */                             \
27420    unixShmUnmap                /* xShmUnmap */                               \
27421 };                                                                           \
27422 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
27423   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
27424   return &METHOD;                                                            \
27425 }                                                                            \
27426 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
27427     = FINDER##Impl;
27428
27429 /*
27430 ** Here are all of the sqlite3_io_methods objects for each of the
27431 ** locking strategies.  Functions that return pointers to these methods
27432 ** are also created.
27433 */
27434 IOMETHODS(
27435   posixIoFinder,            /* Finder function name */
27436   posixIoMethods,           /* sqlite3_io_methods object name */
27437   2,                        /* shared memory is enabled */
27438   unixClose,                /* xClose method */
27439   unixLock,                 /* xLock method */
27440   unixUnlock,               /* xUnlock method */
27441   unixCheckReservedLock     /* xCheckReservedLock method */
27442 )
27443 IOMETHODS(
27444   nolockIoFinder,           /* Finder function name */
27445   nolockIoMethods,          /* sqlite3_io_methods object name */
27446   1,                        /* shared memory is disabled */
27447   nolockClose,              /* xClose method */
27448   nolockLock,               /* xLock method */
27449   nolockUnlock,             /* xUnlock method */
27450   nolockCheckReservedLock   /* xCheckReservedLock method */
27451 )
27452 IOMETHODS(
27453   dotlockIoFinder,          /* Finder function name */
27454   dotlockIoMethods,         /* sqlite3_io_methods object name */
27455   1,                        /* shared memory is disabled */
27456   dotlockClose,             /* xClose method */
27457   dotlockLock,              /* xLock method */
27458   dotlockUnlock,            /* xUnlock method */
27459   dotlockCheckReservedLock  /* xCheckReservedLock method */
27460 )
27461
27462 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
27463 IOMETHODS(
27464   flockIoFinder,            /* Finder function name */
27465   flockIoMethods,           /* sqlite3_io_methods object name */
27466   1,                        /* shared memory is disabled */
27467   flockClose,               /* xClose method */
27468   flockLock,                /* xLock method */
27469   flockUnlock,              /* xUnlock method */
27470   flockCheckReservedLock    /* xCheckReservedLock method */
27471 )
27472 #endif
27473
27474 #if OS_VXWORKS
27475 IOMETHODS(
27476   semIoFinder,              /* Finder function name */
27477   semIoMethods,             /* sqlite3_io_methods object name */
27478   1,                        /* shared memory is disabled */
27479   semClose,                 /* xClose method */
27480   semLock,                  /* xLock method */
27481   semUnlock,                /* xUnlock method */
27482   semCheckReservedLock      /* xCheckReservedLock method */
27483 )
27484 #endif
27485
27486 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27487 IOMETHODS(
27488   afpIoFinder,              /* Finder function name */
27489   afpIoMethods,             /* sqlite3_io_methods object name */
27490   1,                        /* shared memory is disabled */
27491   afpClose,                 /* xClose method */
27492   afpLock,                  /* xLock method */
27493   afpUnlock,                /* xUnlock method */
27494   afpCheckReservedLock      /* xCheckReservedLock method */
27495 )
27496 #endif
27497
27498 /*
27499 ** The proxy locking method is a "super-method" in the sense that it
27500 ** opens secondary file descriptors for the conch and lock files and
27501 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
27502 ** secondary files.  For this reason, the division that implements
27503 ** proxy locking is located much further down in the file.  But we need
27504 ** to go ahead and define the sqlite3_io_methods and finder function
27505 ** for proxy locking here.  So we forward declare the I/O methods.
27506 */
27507 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27508 static int proxyClose(sqlite3_file*);
27509 static int proxyLock(sqlite3_file*, int);
27510 static int proxyUnlock(sqlite3_file*, int);
27511 static int proxyCheckReservedLock(sqlite3_file*, int*);
27512 IOMETHODS(
27513   proxyIoFinder,            /* Finder function name */
27514   proxyIoMethods,           /* sqlite3_io_methods object name */
27515   1,                        /* shared memory is disabled */
27516   proxyClose,               /* xClose method */
27517   proxyLock,                /* xLock method */
27518   proxyUnlock,              /* xUnlock method */
27519   proxyCheckReservedLock    /* xCheckReservedLock method */
27520 )
27521 #endif
27522
27523 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
27524 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27525 IOMETHODS(
27526   nfsIoFinder,               /* Finder function name */
27527   nfsIoMethods,              /* sqlite3_io_methods object name */
27528   1,                         /* shared memory is disabled */
27529   unixClose,                 /* xClose method */
27530   unixLock,                  /* xLock method */
27531   nfsUnlock,                 /* xUnlock method */
27532   unixCheckReservedLock      /* xCheckReservedLock method */
27533 )
27534 #endif
27535
27536 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27537 /* 
27538 ** This "finder" function attempts to determine the best locking strategy 
27539 ** for the database file "filePath".  It then returns the sqlite3_io_methods
27540 ** object that implements that strategy.
27541 **
27542 ** This is for MacOSX only.
27543 */
27544 static const sqlite3_io_methods *autolockIoFinderImpl(
27545   const char *filePath,    /* name of the database file */
27546   unixFile *pNew           /* open file object for the database file */
27547 ){
27548   static const struct Mapping {
27549     const char *zFilesystem;              /* Filesystem type name */
27550     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
27551   } aMap[] = {
27552     { "hfs",    &posixIoMethods },
27553     { "ufs",    &posixIoMethods },
27554     { "afpfs",  &afpIoMethods },
27555     { "smbfs",  &afpIoMethods },
27556     { "webdav", &nolockIoMethods },
27557     { 0, 0 }
27558   };
27559   int i;
27560   struct statfs fsInfo;
27561   struct flock lockInfo;
27562
27563   if( !filePath ){
27564     /* If filePath==NULL that means we are dealing with a transient file
27565     ** that does not need to be locked. */
27566     return &nolockIoMethods;
27567   }
27568   if( statfs(filePath, &fsInfo) != -1 ){
27569     if( fsInfo.f_flags & MNT_RDONLY ){
27570       return &nolockIoMethods;
27571     }
27572     for(i=0; aMap[i].zFilesystem; i++){
27573       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
27574         return aMap[i].pMethods;
27575       }
27576     }
27577   }
27578
27579   /* Default case. Handles, amongst others, "nfs".
27580   ** Test byte-range lock using fcntl(). If the call succeeds, 
27581   ** assume that the file-system supports POSIX style locks. 
27582   */
27583   lockInfo.l_len = 1;
27584   lockInfo.l_start = 0;
27585   lockInfo.l_whence = SEEK_SET;
27586   lockInfo.l_type = F_RDLCK;
27587   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
27588     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
27589       return &nfsIoMethods;
27590     } else {
27591       return &posixIoMethods;
27592     }
27593   }else{
27594     return &dotlockIoMethods;
27595   }
27596 }
27597 static const sqlite3_io_methods 
27598   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
27599
27600 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27601
27602 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
27603 /* 
27604 ** This "finder" function attempts to determine the best locking strategy 
27605 ** for the database file "filePath".  It then returns the sqlite3_io_methods
27606 ** object that implements that strategy.
27607 **
27608 ** This is for VXWorks only.
27609 */
27610 static const sqlite3_io_methods *autolockIoFinderImpl(
27611   const char *filePath,    /* name of the database file */
27612   unixFile *pNew           /* the open file object */
27613 ){
27614   struct flock lockInfo;
27615
27616   if( !filePath ){
27617     /* If filePath==NULL that means we are dealing with a transient file
27618     ** that does not need to be locked. */
27619     return &nolockIoMethods;
27620   }
27621
27622   /* Test if fcntl() is supported and use POSIX style locks.
27623   ** Otherwise fall back to the named semaphore method.
27624   */
27625   lockInfo.l_len = 1;
27626   lockInfo.l_start = 0;
27627   lockInfo.l_whence = SEEK_SET;
27628   lockInfo.l_type = F_RDLCK;
27629   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
27630     return &posixIoMethods;
27631   }else{
27632     return &semIoMethods;
27633   }
27634 }
27635 static const sqlite3_io_methods 
27636   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
27637
27638 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
27639
27640 /*
27641 ** An abstract type for a pointer to a IO method finder function:
27642 */
27643 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
27644
27645
27646 /****************************************************************************
27647 **************************** sqlite3_vfs methods ****************************
27648 **
27649 ** This division contains the implementation of methods on the
27650 ** sqlite3_vfs object.
27651 */
27652
27653 /*
27654 ** Initialize the contents of the unixFile structure pointed to by pId.
27655 */
27656 static int fillInUnixFile(
27657   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
27658   int h,                  /* Open file descriptor of file being opened */
27659   sqlite3_file *pId,      /* Write to the unixFile structure here */
27660   const char *zFilename,  /* Name of the file being opened */
27661   int ctrlFlags           /* Zero or more UNIXFILE_* values */
27662 ){
27663   const sqlite3_io_methods *pLockingStyle;
27664   unixFile *pNew = (unixFile *)pId;
27665   int rc = SQLITE_OK;
27666
27667   assert( pNew->pInode==NULL );
27668
27669   /* Usually the path zFilename should not be a relative pathname. The
27670   ** exception is when opening the proxy "conch" file in builds that
27671   ** include the special Apple locking styles.
27672   */
27673 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27674   assert( zFilename==0 || zFilename[0]=='/' 
27675     || pVfs->pAppData==(void*)&autolockIoFinder );
27676 #else
27677   assert( zFilename==0 || zFilename[0]=='/' );
27678 #endif
27679
27680   /* No locking occurs in temporary files */
27681   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
27682
27683   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
27684   pNew->h = h;
27685   pNew->pVfs = pVfs;
27686   pNew->zPath = zFilename;
27687   pNew->ctrlFlags = (u8)ctrlFlags;
27688   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
27689                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
27690     pNew->ctrlFlags |= UNIXFILE_PSOW;
27691   }
27692   if( strcmp(pVfs->zName,"unix-excl")==0 ){
27693     pNew->ctrlFlags |= UNIXFILE_EXCL;
27694   }
27695
27696 #if OS_VXWORKS
27697   pNew->pId = vxworksFindFileId(zFilename);
27698   if( pNew->pId==0 ){
27699     ctrlFlags |= UNIXFILE_NOLOCK;
27700     rc = SQLITE_NOMEM;
27701   }
27702 #endif
27703
27704   if( ctrlFlags & UNIXFILE_NOLOCK ){
27705     pLockingStyle = &nolockIoMethods;
27706   }else{
27707     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
27708 #if SQLITE_ENABLE_LOCKING_STYLE
27709     /* Cache zFilename in the locking context (AFP and dotlock override) for
27710     ** proxyLock activation is possible (remote proxy is based on db name)
27711     ** zFilename remains valid until file is closed, to support */
27712     pNew->lockingContext = (void*)zFilename;
27713 #endif
27714   }
27715
27716   if( pLockingStyle == &posixIoMethods
27717 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27718     || pLockingStyle == &nfsIoMethods
27719 #endif
27720   ){
27721     unixEnterMutex();
27722     rc = findInodeInfo(pNew, &pNew->pInode);
27723     if( rc!=SQLITE_OK ){
27724       /* If an error occurred in findInodeInfo(), close the file descriptor
27725       ** immediately, before releasing the mutex. findInodeInfo() may fail
27726       ** in two scenarios:
27727       **
27728       **   (a) A call to fstat() failed.
27729       **   (b) A malloc failed.
27730       **
27731       ** Scenario (b) may only occur if the process is holding no other
27732       ** file descriptors open on the same file. If there were other file
27733       ** descriptors on this file, then no malloc would be required by
27734       ** findInodeInfo(). If this is the case, it is quite safe to close
27735       ** handle h - as it is guaranteed that no posix locks will be released
27736       ** by doing so.
27737       **
27738       ** If scenario (a) caused the error then things are not so safe. The
27739       ** implicit assumption here is that if fstat() fails, things are in
27740       ** such bad shape that dropping a lock or two doesn't matter much.
27741       */
27742       robust_close(pNew, h, __LINE__);
27743       h = -1;
27744     }
27745     unixLeaveMutex();
27746   }
27747
27748 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27749   else if( pLockingStyle == &afpIoMethods ){
27750     /* AFP locking uses the file path so it needs to be included in
27751     ** the afpLockingContext.
27752     */
27753     afpLockingContext *pCtx;
27754     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
27755     if( pCtx==0 ){
27756       rc = SQLITE_NOMEM;
27757     }else{
27758       /* NB: zFilename exists and remains valid until the file is closed
27759       ** according to requirement F11141.  So we do not need to make a
27760       ** copy of the filename. */
27761       pCtx->dbPath = zFilename;
27762       pCtx->reserved = 0;
27763       srandomdev();
27764       unixEnterMutex();
27765       rc = findInodeInfo(pNew, &pNew->pInode);
27766       if( rc!=SQLITE_OK ){
27767         sqlite3_free(pNew->lockingContext);
27768         robust_close(pNew, h, __LINE__);
27769         h = -1;
27770       }
27771       unixLeaveMutex();        
27772     }
27773   }
27774 #endif
27775
27776   else if( pLockingStyle == &dotlockIoMethods ){
27777     /* Dotfile locking uses the file path so it needs to be included in
27778     ** the dotlockLockingContext 
27779     */
27780     char *zLockFile;
27781     int nFilename;
27782     assert( zFilename!=0 );
27783     nFilename = (int)strlen(zFilename) + 6;
27784     zLockFile = (char *)sqlite3_malloc(nFilename);
27785     if( zLockFile==0 ){
27786       rc = SQLITE_NOMEM;
27787     }else{
27788       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
27789     }
27790     pNew->lockingContext = zLockFile;
27791   }
27792
27793 #if OS_VXWORKS
27794   else if( pLockingStyle == &semIoMethods ){
27795     /* Named semaphore locking uses the file path so it needs to be
27796     ** included in the semLockingContext
27797     */
27798     unixEnterMutex();
27799     rc = findInodeInfo(pNew, &pNew->pInode);
27800     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
27801       char *zSemName = pNew->pInode->aSemName;
27802       int n;
27803       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
27804                        pNew->pId->zCanonicalName);
27805       for( n=1; zSemName[n]; n++ )
27806         if( zSemName[n]=='/' ) zSemName[n] = '_';
27807       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
27808       if( pNew->pInode->pSem == SEM_FAILED ){
27809         rc = SQLITE_NOMEM;
27810         pNew->pInode->aSemName[0] = '\0';
27811       }
27812     }
27813     unixLeaveMutex();
27814   }
27815 #endif
27816   
27817   pNew->lastErrno = 0;
27818 #if OS_VXWORKS
27819   if( rc!=SQLITE_OK ){
27820     if( h>=0 ) robust_close(pNew, h, __LINE__);
27821     h = -1;
27822     osUnlink(zFilename);
27823     isDelete = 0;
27824   }
27825   if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
27826 #endif
27827   if( rc!=SQLITE_OK ){
27828     if( h>=0 ) robust_close(pNew, h, __LINE__);
27829   }else{
27830     pNew->pMethod = pLockingStyle;
27831     OpenCounter(+1);
27832   }
27833   return rc;
27834 }
27835
27836 /*
27837 ** Return the name of a directory in which to put temporary files.
27838 ** If no suitable temporary file directory can be found, return NULL.
27839 */
27840 static const char *unixTempFileDir(void){
27841   static const char *azDirs[] = {
27842      0,
27843      0,
27844      "/var/tmp",
27845      "/usr/tmp",
27846      "/tmp",
27847      0        /* List terminator */
27848   };
27849   unsigned int i;
27850   struct stat buf;
27851   const char *zDir = 0;
27852
27853   azDirs[0] = sqlite3_temp_directory;
27854   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
27855   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
27856     if( zDir==0 ) continue;
27857     if( osStat(zDir, &buf) ) continue;
27858     if( !S_ISDIR(buf.st_mode) ) continue;
27859     if( osAccess(zDir, 07) ) continue;
27860     break;
27861   }
27862   return zDir;
27863 }
27864
27865 /*
27866 ** Create a temporary file name in zBuf.  zBuf must be allocated
27867 ** by the calling process and must be big enough to hold at least
27868 ** pVfs->mxPathname bytes.
27869 */
27870 static int unixGetTempname(int nBuf, char *zBuf){
27871   static const unsigned char zChars[] =
27872     "abcdefghijklmnopqrstuvwxyz"
27873     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
27874     "0123456789";
27875   unsigned int i, j;
27876   const char *zDir;
27877
27878   /* It's odd to simulate an io-error here, but really this is just
27879   ** using the io-error infrastructure to test that SQLite handles this
27880   ** function failing. 
27881   */
27882   SimulateIOError( return SQLITE_IOERR );
27883
27884   zDir = unixTempFileDir();
27885   if( zDir==0 ) zDir = ".";
27886
27887   /* Check that the output buffer is large enough for the temporary file 
27888   ** name. If it is not, return SQLITE_ERROR.
27889   */
27890   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
27891     return SQLITE_ERROR;
27892   }
27893
27894   do{
27895     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
27896     j = (int)strlen(zBuf);
27897     sqlite3_randomness(15, &zBuf[j]);
27898     for(i=0; i<15; i++, j++){
27899       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
27900     }
27901     zBuf[j] = 0;
27902     zBuf[j+1] = 0;
27903   }while( osAccess(zBuf,0)==0 );
27904   return SQLITE_OK;
27905 }
27906
27907 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27908 /*
27909 ** Routine to transform a unixFile into a proxy-locking unixFile.
27910 ** Implementation in the proxy-lock division, but used by unixOpen()
27911 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
27912 */
27913 static int proxyTransformUnixFile(unixFile*, const char*);
27914 #endif
27915
27916 /*
27917 ** Search for an unused file descriptor that was opened on the database 
27918 ** file (not a journal or master-journal file) identified by pathname
27919 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
27920 ** argument to this function.
27921 **
27922 ** Such a file descriptor may exist if a database connection was closed
27923 ** but the associated file descriptor could not be closed because some
27924 ** other file descriptor open on the same file is holding a file-lock.
27925 ** Refer to comments in the unixClose() function and the lengthy comment
27926 ** describing "Posix Advisory Locking" at the start of this file for 
27927 ** further details. Also, ticket #4018.
27928 **
27929 ** If a suitable file descriptor is found, then it is returned. If no
27930 ** such file descriptor is located, -1 is returned.
27931 */
27932 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
27933   UnixUnusedFd *pUnused = 0;
27934
27935   /* Do not search for an unused file descriptor on vxworks. Not because
27936   ** vxworks would not benefit from the change (it might, we're not sure),
27937   ** but because no way to test it is currently available. It is better 
27938   ** not to risk breaking vxworks support for the sake of such an obscure 
27939   ** feature.  */
27940 #if !OS_VXWORKS
27941   struct stat sStat;                   /* Results of stat() call */
27942
27943   /* A stat() call may fail for various reasons. If this happens, it is
27944   ** almost certain that an open() call on the same path will also fail.
27945   ** For this reason, if an error occurs in the stat() call here, it is
27946   ** ignored and -1 is returned. The caller will try to open a new file
27947   ** descriptor on the same path, fail, and return an error to SQLite.
27948   **
27949   ** Even if a subsequent open() call does succeed, the consequences of
27950   ** not searching for a resusable file descriptor are not dire.  */
27951   if( 0==osStat(zPath, &sStat) ){
27952     unixInodeInfo *pInode;
27953
27954     unixEnterMutex();
27955     pInode = inodeList;
27956     while( pInode && (pInode->fileId.dev!=sStat.st_dev
27957                      || pInode->fileId.ino!=sStat.st_ino) ){
27958        pInode = pInode->pNext;
27959     }
27960     if( pInode ){
27961       UnixUnusedFd **pp;
27962       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
27963       pUnused = *pp;
27964       if( pUnused ){
27965         *pp = pUnused->pNext;
27966       }
27967     }
27968     unixLeaveMutex();
27969   }
27970 #endif    /* if !OS_VXWORKS */
27971   return pUnused;
27972 }
27973
27974 /*
27975 ** This function is called by unixOpen() to determine the unix permissions
27976 ** to create new files with. If no error occurs, then SQLITE_OK is returned
27977 ** and a value suitable for passing as the third argument to open(2) is
27978 ** written to *pMode. If an IO error occurs, an SQLite error code is 
27979 ** returned and the value of *pMode is not modified.
27980 **
27981 ** In most cases cases, this routine sets *pMode to 0, which will become
27982 ** an indication to robust_open() to create the file using
27983 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
27984 ** But if the file being opened is a WAL or regular journal file, then 
27985 ** this function queries the file-system for the permissions on the 
27986 ** corresponding database file and sets *pMode to this value. Whenever 
27987 ** possible, WAL and journal files are created using the same permissions 
27988 ** as the associated database file.
27989 **
27990 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
27991 ** original filename is unavailable.  But 8_3_NAMES is only used for
27992 ** FAT filesystems and permissions do not matter there, so just use
27993 ** the default permissions.
27994 */
27995 static int findCreateFileMode(
27996   const char *zPath,              /* Path of file (possibly) being created */
27997   int flags,                      /* Flags passed as 4th argument to xOpen() */
27998   mode_t *pMode,                  /* OUT: Permissions to open file with */
27999   uid_t *pUid,                    /* OUT: uid to set on the file */
28000   gid_t *pGid                     /* OUT: gid to set on the file */
28001 ){
28002   int rc = SQLITE_OK;             /* Return Code */
28003   *pMode = 0;
28004   *pUid = 0;
28005   *pGid = 0;
28006   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28007     char zDb[MAX_PATHNAME+1];     /* Database file path */
28008     int nDb;                      /* Number of valid bytes in zDb */
28009     struct stat sStat;            /* Output of stat() on database file */
28010
28011     /* zPath is a path to a WAL or journal file. The following block derives
28012     ** the path to the associated database file from zPath. This block handles
28013     ** the following naming conventions:
28014     **
28015     **   "<path to db>-journal"
28016     **   "<path to db>-wal"
28017     **   "<path to db>-journalNN"
28018     **   "<path to db>-walNN"
28019     **
28020     ** where NN is a decimal number. The NN naming schemes are 
28021     ** used by the test_multiplex.c module.
28022     */
28023     nDb = sqlite3Strlen30(zPath) - 1; 
28024 #ifdef SQLITE_ENABLE_8_3_NAMES
28025     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
28026     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
28027 #else
28028     while( zPath[nDb]!='-' ){
28029       assert( nDb>0 );
28030       assert( zPath[nDb]!='\n' );
28031       nDb--;
28032     }
28033 #endif
28034     memcpy(zDb, zPath, nDb);
28035     zDb[nDb] = '\0';
28036
28037     if( 0==osStat(zDb, &sStat) ){
28038       *pMode = sStat.st_mode & 0777;
28039       *pUid = sStat.st_uid;
28040       *pGid = sStat.st_gid;
28041     }else{
28042       rc = SQLITE_IOERR_FSTAT;
28043     }
28044   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28045     *pMode = 0600;
28046   }
28047   return rc;
28048 }
28049
28050 /*
28051 ** Open the file zPath.
28052 ** 
28053 ** Previously, the SQLite OS layer used three functions in place of this
28054 ** one:
28055 **
28056 **     sqlite3OsOpenReadWrite();
28057 **     sqlite3OsOpenReadOnly();
28058 **     sqlite3OsOpenExclusive();
28059 **
28060 ** These calls correspond to the following combinations of flags:
28061 **
28062 **     ReadWrite() ->     (READWRITE | CREATE)
28063 **     ReadOnly()  ->     (READONLY) 
28064 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
28065 **
28066 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
28067 ** true, the file was configured to be automatically deleted when the
28068 ** file handle closed. To achieve the same effect using this new 
28069 ** interface, add the DELETEONCLOSE flag to those specified above for 
28070 ** OpenExclusive().
28071 */
28072 static int unixOpen(
28073   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
28074   const char *zPath,           /* Pathname of file to be opened */
28075   sqlite3_file *pFile,         /* The file descriptor to be filled in */
28076   int flags,                   /* Input flags to control the opening */
28077   int *pOutFlags               /* Output flags returned to SQLite core */
28078 ){
28079   unixFile *p = (unixFile *)pFile;
28080   int fd = -1;                   /* File descriptor returned by open() */
28081   int openFlags = 0;             /* Flags to pass to open() */
28082   int eType = flags&0xFFFFFF00;  /* Type of file to open */
28083   int noLock;                    /* True to omit locking primitives */
28084   int rc = SQLITE_OK;            /* Function Return Code */
28085   int ctrlFlags = 0;             /* UNIXFILE_* flags */
28086
28087   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
28088   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
28089   int isCreate     = (flags & SQLITE_OPEN_CREATE);
28090   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
28091   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
28092 #if SQLITE_ENABLE_LOCKING_STYLE
28093   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
28094 #endif
28095 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28096   struct statfs fsInfo;
28097 #endif
28098
28099   /* If creating a master or main-file journal, this function will open
28100   ** a file-descriptor on the directory too. The first time unixSync()
28101   ** is called the directory file descriptor will be fsync()ed and close()d.
28102   */
28103   int syncDir = (isCreate && (
28104         eType==SQLITE_OPEN_MASTER_JOURNAL 
28105      || eType==SQLITE_OPEN_MAIN_JOURNAL 
28106      || eType==SQLITE_OPEN_WAL
28107   ));
28108
28109   /* If argument zPath is a NULL pointer, this function is required to open
28110   ** a temporary file. Use this buffer to store the file name in.
28111   */
28112   char zTmpname[MAX_PATHNAME+2];
28113   const char *zName = zPath;
28114
28115   /* Check the following statements are true: 
28116   **
28117   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
28118   **   (b) if CREATE is set, then READWRITE must also be set, and
28119   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
28120   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
28121   */
28122   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
28123   assert(isCreate==0 || isReadWrite);
28124   assert(isExclusive==0 || isCreate);
28125   assert(isDelete==0 || isCreate);
28126
28127   /* The main DB, main journal, WAL file and master journal are never 
28128   ** automatically deleted. Nor are they ever temporary files.  */
28129   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
28130   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
28131   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
28132   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
28133
28134   /* Assert that the upper layer has set one of the "file-type" flags. */
28135   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
28136        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
28137        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
28138        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
28139   );
28140
28141   memset(p, 0, sizeof(unixFile));
28142
28143   if( eType==SQLITE_OPEN_MAIN_DB ){
28144     UnixUnusedFd *pUnused;
28145     pUnused = findReusableFd(zName, flags);
28146     if( pUnused ){
28147       fd = pUnused->fd;
28148     }else{
28149       pUnused = sqlite3_malloc(sizeof(*pUnused));
28150       if( !pUnused ){
28151         return SQLITE_NOMEM;
28152       }
28153     }
28154     p->pUnused = pUnused;
28155
28156     /* Database filenames are double-zero terminated if they are not
28157     ** URIs with parameters.  Hence, they can always be passed into
28158     ** sqlite3_uri_parameter(). */
28159     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
28160
28161   }else if( !zName ){
28162     /* If zName is NULL, the upper layer is requesting a temp file. */
28163     assert(isDelete && !syncDir);
28164     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
28165     if( rc!=SQLITE_OK ){
28166       return rc;
28167     }
28168     zName = zTmpname;
28169
28170     /* Generated temporary filenames are always double-zero terminated
28171     ** for use by sqlite3_uri_parameter(). */
28172     assert( zName[strlen(zName)+1]==0 );
28173   }
28174
28175   /* Determine the value of the flags parameter passed to POSIX function
28176   ** open(). These must be calculated even if open() is not called, as
28177   ** they may be stored as part of the file handle and used by the 
28178   ** 'conch file' locking functions later on.  */
28179   if( isReadonly )  openFlags |= O_RDONLY;
28180   if( isReadWrite ) openFlags |= O_RDWR;
28181   if( isCreate )    openFlags |= O_CREAT;
28182   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
28183   openFlags |= (O_LARGEFILE|O_BINARY);
28184
28185   if( fd<0 ){
28186     mode_t openMode;              /* Permissions to create file with */
28187     uid_t uid;                    /* Userid for the file */
28188     gid_t gid;                    /* Groupid for the file */
28189     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
28190     if( rc!=SQLITE_OK ){
28191       assert( !p->pUnused );
28192       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
28193       return rc;
28194     }
28195     fd = robust_open(zName, openFlags, openMode);
28196     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
28197     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
28198       /* Failed to open the file for read/write access. Try read-only. */
28199       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
28200       openFlags &= ~(O_RDWR|O_CREAT);
28201       flags |= SQLITE_OPEN_READONLY;
28202       openFlags |= O_RDONLY;
28203       isReadonly = 1;
28204       fd = robust_open(zName, openFlags, openMode);
28205     }
28206     if( fd<0 ){
28207       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
28208       goto open_finished;
28209     }
28210
28211     /* If this process is running as root and if creating a new rollback
28212     ** journal or WAL file, set the ownership of the journal or WAL to be
28213     ** the same as the original database.
28214     */
28215     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28216       osFchown(fd, uid, gid);
28217     }
28218   }
28219   assert( fd>=0 );
28220   if( pOutFlags ){
28221     *pOutFlags = flags;
28222   }
28223
28224   if( p->pUnused ){
28225     p->pUnused->fd = fd;
28226     p->pUnused->flags = flags;
28227   }
28228
28229   if( isDelete ){
28230 #if OS_VXWORKS
28231     zPath = zName;
28232 #else
28233     osUnlink(zName);
28234 #endif
28235   }
28236 #if SQLITE_ENABLE_LOCKING_STYLE
28237   else{
28238     p->openFlags = openFlags;
28239   }
28240 #endif
28241
28242   noLock = eType!=SQLITE_OPEN_MAIN_DB;
28243
28244   
28245 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28246   if( fstatfs(fd, &fsInfo) == -1 ){
28247     ((unixFile*)pFile)->lastErrno = errno;
28248     robust_close(p, fd, __LINE__);
28249     return SQLITE_IOERR_ACCESS;
28250   }
28251   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
28252     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
28253   }
28254 #endif
28255
28256   /* Set up appropriate ctrlFlags */
28257   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
28258   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
28259   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
28260   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
28261   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
28262
28263 #if SQLITE_ENABLE_LOCKING_STYLE
28264 #if SQLITE_PREFER_PROXY_LOCKING
28265   isAutoProxy = 1;
28266 #endif
28267   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
28268     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
28269     int useProxy = 0;
28270
28271     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
28272     ** never use proxy, NULL means use proxy for non-local files only.  */
28273     if( envforce!=NULL ){
28274       useProxy = atoi(envforce)>0;
28275     }else{
28276       if( statfs(zPath, &fsInfo) == -1 ){
28277         /* In theory, the close(fd) call is sub-optimal. If the file opened
28278         ** with fd is a database file, and there are other connections open
28279         ** on that file that are currently holding advisory locks on it,
28280         ** then the call to close() will cancel those locks. In practice,
28281         ** we're assuming that statfs() doesn't fail very often. At least
28282         ** not while other file descriptors opened by the same process on
28283         ** the same file are working.  */
28284         p->lastErrno = errno;
28285         robust_close(p, fd, __LINE__);
28286         rc = SQLITE_IOERR_ACCESS;
28287         goto open_finished;
28288       }
28289       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
28290     }
28291     if( useProxy ){
28292       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28293       if( rc==SQLITE_OK ){
28294         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
28295         if( rc!=SQLITE_OK ){
28296           /* Use unixClose to clean up the resources added in fillInUnixFile 
28297           ** and clear all the structure's references.  Specifically, 
28298           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
28299           */
28300           unixClose(pFile);
28301           return rc;
28302         }
28303       }
28304       goto open_finished;
28305     }
28306   }
28307 #endif
28308   
28309   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28310
28311 open_finished:
28312   if( rc!=SQLITE_OK ){
28313     sqlite3_free(p->pUnused);
28314   }
28315   return rc;
28316 }
28317
28318
28319 /*
28320 ** Delete the file at zPath. If the dirSync argument is true, fsync()
28321 ** the directory after deleting the file.
28322 */
28323 static int unixDelete(
28324   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
28325   const char *zPath,        /* Name of file to be deleted */
28326   int dirSync               /* If true, fsync() directory after deleting file */
28327 ){
28328   int rc = SQLITE_OK;
28329   UNUSED_PARAMETER(NotUsed);
28330   SimulateIOError(return SQLITE_IOERR_DELETE);
28331   if( osUnlink(zPath)==(-1) ){
28332     if( errno==ENOENT ){
28333       rc = SQLITE_IOERR_DELETE_NOENT;
28334     }else{
28335       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
28336     }
28337     return rc;
28338   }
28339 #ifndef SQLITE_DISABLE_DIRSYNC
28340   if( (dirSync & 1)!=0 ){
28341     int fd;
28342     rc = osOpenDirectory(zPath, &fd);
28343     if( rc==SQLITE_OK ){
28344 #if OS_VXWORKS
28345       if( fsync(fd)==-1 )
28346 #else
28347       if( fsync(fd) )
28348 #endif
28349       {
28350         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
28351       }
28352       robust_close(0, fd, __LINE__);
28353     }else if( rc==SQLITE_CANTOPEN ){
28354       rc = SQLITE_OK;
28355     }
28356   }
28357 #endif
28358   return rc;
28359 }
28360
28361 /*
28362 ** Test the existence of or access permissions of file zPath. The
28363 ** test performed depends on the value of flags:
28364 **
28365 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
28366 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
28367 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
28368 **
28369 ** Otherwise return 0.
28370 */
28371 static int unixAccess(
28372   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
28373   const char *zPath,      /* Path of the file to examine */
28374   int flags,              /* What do we want to learn about the zPath file? */
28375   int *pResOut            /* Write result boolean here */
28376 ){
28377   int amode = 0;
28378   UNUSED_PARAMETER(NotUsed);
28379   SimulateIOError( return SQLITE_IOERR_ACCESS; );
28380   switch( flags ){
28381     case SQLITE_ACCESS_EXISTS:
28382       amode = F_OK;
28383       break;
28384     case SQLITE_ACCESS_READWRITE:
28385       amode = W_OK|R_OK;
28386       break;
28387     case SQLITE_ACCESS_READ:
28388       amode = R_OK;
28389       break;
28390
28391     default:
28392       assert(!"Invalid flags argument");
28393   }
28394   *pResOut = (osAccess(zPath, amode)==0);
28395   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
28396     struct stat buf;
28397     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
28398       *pResOut = 0;
28399     }
28400   }
28401   return SQLITE_OK;
28402 }
28403
28404
28405 /*
28406 ** Turn a relative pathname into a full pathname. The relative path
28407 ** is stored as a nul-terminated string in the buffer pointed to by
28408 ** zPath. 
28409 **
28410 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
28411 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
28412 ** this buffer before returning.
28413 */
28414 static int unixFullPathname(
28415   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
28416   const char *zPath,            /* Possibly relative input path */
28417   int nOut,                     /* Size of output buffer in bytes */
28418   char *zOut                    /* Output buffer */
28419 ){
28420
28421   /* It's odd to simulate an io-error here, but really this is just
28422   ** using the io-error infrastructure to test that SQLite handles this
28423   ** function failing. This function could fail if, for example, the
28424   ** current working directory has been unlinked.
28425   */
28426   SimulateIOError( return SQLITE_ERROR );
28427
28428   assert( pVfs->mxPathname==MAX_PATHNAME );
28429   UNUSED_PARAMETER(pVfs);
28430
28431   zOut[nOut-1] = '\0';
28432   if( zPath[0]=='/' ){
28433     sqlite3_snprintf(nOut, zOut, "%s", zPath);
28434   }else{
28435     int nCwd;
28436     if( osGetcwd(zOut, nOut-1)==0 ){
28437       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
28438     }
28439     nCwd = (int)strlen(zOut);
28440     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
28441   }
28442   return SQLITE_OK;
28443 }
28444
28445
28446 #ifndef SQLITE_OMIT_LOAD_EXTENSION
28447 /*
28448 ** Interfaces for opening a shared library, finding entry points
28449 ** within the shared library, and closing the shared library.
28450 */
28451 #include <dlfcn.h>
28452 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
28453   UNUSED_PARAMETER(NotUsed);
28454   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
28455 }
28456
28457 /*
28458 ** SQLite calls this function immediately after a call to unixDlSym() or
28459 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
28460 ** message is available, it is written to zBufOut. If no error message
28461 ** is available, zBufOut is left unmodified and SQLite uses a default
28462 ** error message.
28463 */
28464 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
28465   const char *zErr;
28466   UNUSED_PARAMETER(NotUsed);
28467   unixEnterMutex();
28468   zErr = dlerror();
28469   if( zErr ){
28470     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
28471   }
28472   unixLeaveMutex();
28473 }
28474 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
28475   /* 
28476   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
28477   ** cast into a pointer to a function.  And yet the library dlsym() routine
28478   ** returns a void* which is really a pointer to a function.  So how do we
28479   ** use dlsym() with -pedantic-errors?
28480   **
28481   ** Variable x below is defined to be a pointer to a function taking
28482   ** parameters void* and const char* and returning a pointer to a function.
28483   ** We initialize x by assigning it a pointer to the dlsym() function.
28484   ** (That assignment requires a cast.)  Then we call the function that
28485   ** x points to.  
28486   **
28487   ** This work-around is unlikely to work correctly on any system where
28488   ** you really cannot cast a function pointer into void*.  But then, on the
28489   ** other hand, dlsym() will not work on such a system either, so we have
28490   ** not really lost anything.
28491   */
28492   void (*(*x)(void*,const char*))(void);
28493   UNUSED_PARAMETER(NotUsed);
28494   x = (void(*(*)(void*,const char*))(void))dlsym;
28495   return (*x)(p, zSym);
28496 }
28497 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
28498   UNUSED_PARAMETER(NotUsed);
28499   dlclose(pHandle);
28500 }
28501 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
28502   #define unixDlOpen  0
28503   #define unixDlError 0
28504   #define unixDlSym   0
28505   #define unixDlClose 0
28506 #endif
28507
28508 /*
28509 ** Write nBuf bytes of random data to the supplied buffer zBuf.
28510 */
28511 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
28512   UNUSED_PARAMETER(NotUsed);
28513   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
28514
28515   /* We have to initialize zBuf to prevent valgrind from reporting
28516   ** errors.  The reports issued by valgrind are incorrect - we would
28517   ** prefer that the randomness be increased by making use of the
28518   ** uninitialized space in zBuf - but valgrind errors tend to worry
28519   ** some users.  Rather than argue, it seems easier just to initialize
28520   ** the whole array and silence valgrind, even if that means less randomness
28521   ** in the random seed.
28522   **
28523   ** When testing, initializing zBuf[] to zero is all we do.  That means
28524   ** that we always use the same random number sequence.  This makes the
28525   ** tests repeatable.
28526   */
28527   memset(zBuf, 0, nBuf);
28528 #if !defined(SQLITE_TEST)
28529   {
28530     int pid, fd, got;
28531     fd = robust_open("/dev/urandom", O_RDONLY, 0);
28532     if( fd<0 ){
28533       time_t t;
28534       time(&t);
28535       memcpy(zBuf, &t, sizeof(t));
28536       pid = getpid();
28537       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
28538       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
28539       nBuf = sizeof(t) + sizeof(pid);
28540     }else{
28541       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
28542       robust_close(0, fd, __LINE__);
28543     }
28544   }
28545 #endif
28546   return nBuf;
28547 }
28548
28549
28550 /*
28551 ** Sleep for a little while.  Return the amount of time slept.
28552 ** The argument is the number of microseconds we want to sleep.
28553 ** The return value is the number of microseconds of sleep actually
28554 ** requested from the underlying operating system, a number which
28555 ** might be greater than or equal to the argument, but not less
28556 ** than the argument.
28557 */
28558 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
28559 #if OS_VXWORKS
28560   struct timespec sp;
28561
28562   sp.tv_sec = microseconds / 1000000;
28563   sp.tv_nsec = (microseconds % 1000000) * 1000;
28564   nanosleep(&sp, NULL);
28565   UNUSED_PARAMETER(NotUsed);
28566   return microseconds;
28567 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
28568   usleep(microseconds);
28569   UNUSED_PARAMETER(NotUsed);
28570   return microseconds;
28571 #else
28572   int seconds = (microseconds+999999)/1000000;
28573   sleep(seconds);
28574   UNUSED_PARAMETER(NotUsed);
28575   return seconds*1000000;
28576 #endif
28577 }
28578
28579 /*
28580 ** The following variable, if set to a non-zero value, is interpreted as
28581 ** the number of seconds since 1970 and is used to set the result of
28582 ** sqlite3OsCurrentTime() during testing.
28583 */
28584 #ifdef SQLITE_TEST
28585 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
28586 #endif
28587
28588 /*
28589 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
28590 ** the current time and date as a Julian Day number times 86_400_000.  In
28591 ** other words, write into *piNow the number of milliseconds since the Julian
28592 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
28593 ** proleptic Gregorian calendar.
28594 **
28595 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
28596 ** cannot be found.
28597 */
28598 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
28599   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
28600   int rc = SQLITE_OK;
28601 #if defined(NO_GETTOD)
28602   time_t t;
28603   time(&t);
28604   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
28605 #elif OS_VXWORKS
28606   struct timespec sNow;
28607   clock_gettime(CLOCK_REALTIME, &sNow);
28608   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
28609 #else
28610   struct timeval sNow;
28611   if( gettimeofday(&sNow, 0)==0 ){
28612     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
28613   }else{
28614     rc = SQLITE_ERROR;
28615   }
28616 #endif
28617
28618 #ifdef SQLITE_TEST
28619   if( sqlite3_current_time ){
28620     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
28621   }
28622 #endif
28623   UNUSED_PARAMETER(NotUsed);
28624   return rc;
28625 }
28626
28627 /*
28628 ** Find the current time (in Universal Coordinated Time).  Write the
28629 ** current time and date as a Julian Day number into *prNow and
28630 ** return 0.  Return 1 if the time and date cannot be found.
28631 */
28632 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
28633   sqlite3_int64 i = 0;
28634   int rc;
28635   UNUSED_PARAMETER(NotUsed);
28636   rc = unixCurrentTimeInt64(0, &i);
28637   *prNow = i/86400000.0;
28638   return rc;
28639 }
28640
28641 /*
28642 ** We added the xGetLastError() method with the intention of providing
28643 ** better low-level error messages when operating-system problems come up
28644 ** during SQLite operation.  But so far, none of that has been implemented
28645 ** in the core.  So this routine is never called.  For now, it is merely
28646 ** a place-holder.
28647 */
28648 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
28649   UNUSED_PARAMETER(NotUsed);
28650   UNUSED_PARAMETER(NotUsed2);
28651   UNUSED_PARAMETER(NotUsed3);
28652   return 0;
28653 }
28654
28655
28656 /*
28657 ************************ End of sqlite3_vfs methods ***************************
28658 ******************************************************************************/
28659
28660 /******************************************************************************
28661 ************************** Begin Proxy Locking ********************************
28662 **
28663 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
28664 ** other locking methods on secondary lock files.  Proxy locking is a
28665 ** meta-layer over top of the primitive locking implemented above.  For
28666 ** this reason, the division that implements of proxy locking is deferred
28667 ** until late in the file (here) after all of the other I/O methods have
28668 ** been defined - so that the primitive locking methods are available
28669 ** as services to help with the implementation of proxy locking.
28670 **
28671 ****
28672 **
28673 ** The default locking schemes in SQLite use byte-range locks on the
28674 ** database file to coordinate safe, concurrent access by multiple readers
28675 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
28676 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
28677 ** as POSIX read & write locks over fixed set of locations (via fsctl),
28678 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
28679 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
28680 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
28681 ** address in the shared range is taken for a SHARED lock, the entire
28682 ** shared range is taken for an EXCLUSIVE lock):
28683 **
28684 **      PENDING_BYTE        0x40000000
28685 **      RESERVED_BYTE       0x40000001
28686 **      SHARED_RANGE        0x40000002 -> 0x40000200
28687 **
28688 ** This works well on the local file system, but shows a nearly 100x
28689 ** slowdown in read performance on AFP because the AFP client disables
28690 ** the read cache when byte-range locks are present.  Enabling the read
28691 ** cache exposes a cache coherency problem that is present on all OS X
28692 ** supported network file systems.  NFS and AFP both observe the
28693 ** close-to-open semantics for ensuring cache coherency
28694 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
28695 ** address the requirements for concurrent database access by multiple
28696 ** readers and writers
28697 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
28698 **
28699 ** To address the performance and cache coherency issues, proxy file locking
28700 ** changes the way database access is controlled by limiting access to a
28701 ** single host at a time and moving file locks off of the database file
28702 ** and onto a proxy file on the local file system.  
28703 **
28704 **
28705 ** Using proxy locks
28706 ** -----------------
28707 **
28708 ** C APIs
28709 **
28710 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
28711 **                       <proxy_path> | ":auto:");
28712 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
28713 **
28714 **
28715 ** SQL pragmas
28716 **
28717 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
28718 **  PRAGMA [database.]lock_proxy_file
28719 **
28720 ** Specifying ":auto:" means that if there is a conch file with a matching
28721 ** host ID in it, the proxy path in the conch file will be used, otherwise
28722 ** a proxy path based on the user's temp dir
28723 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
28724 ** actual proxy file name is generated from the name and path of the
28725 ** database file.  For example:
28726 **
28727 **       For database path "/Users/me/foo.db" 
28728 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
28729 **
28730 ** Once a lock proxy is configured for a database connection, it can not
28731 ** be removed, however it may be switched to a different proxy path via
28732 ** the above APIs (assuming the conch file is not being held by another
28733 ** connection or process). 
28734 **
28735 **
28736 ** How proxy locking works
28737 ** -----------------------
28738 **
28739 ** Proxy file locking relies primarily on two new supporting files: 
28740 **
28741 **   *  conch file to limit access to the database file to a single host
28742 **      at a time
28743 **
28744 **   *  proxy file to act as a proxy for the advisory locks normally
28745 **      taken on the database
28746 **
28747 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
28748 ** by taking an sqlite-style shared lock on the conch file, reading the
28749 ** contents and comparing the host's unique host ID (see below) and lock
28750 ** proxy path against the values stored in the conch.  The conch file is
28751 ** stored in the same directory as the database file and the file name
28752 ** is patterned after the database file name as ".<databasename>-conch".
28753 ** If the conch file does not exist, or it's contents do not match the
28754 ** host ID and/or proxy path, then the lock is escalated to an exclusive
28755 ** lock and the conch file contents is updated with the host ID and proxy
28756 ** path and the lock is downgraded to a shared lock again.  If the conch
28757 ** is held by another process (with a shared lock), the exclusive lock
28758 ** will fail and SQLITE_BUSY is returned.
28759 **
28760 ** The proxy file - a single-byte file used for all advisory file locks
28761 ** normally taken on the database file.   This allows for safe sharing
28762 ** of the database file for multiple readers and writers on the same
28763 ** host (the conch ensures that they all use the same local lock file).
28764 **
28765 ** Requesting the lock proxy does not immediately take the conch, it is
28766 ** only taken when the first request to lock database file is made.  
28767 ** This matches the semantics of the traditional locking behavior, where
28768 ** opening a connection to a database file does not take a lock on it.
28769 ** The shared lock and an open file descriptor are maintained until 
28770 ** the connection to the database is closed. 
28771 **
28772 ** The proxy file and the lock file are never deleted so they only need
28773 ** to be created the first time they are used.
28774 **
28775 ** Configuration options
28776 ** ---------------------
28777 **
28778 **  SQLITE_PREFER_PROXY_LOCKING
28779 **
28780 **       Database files accessed on non-local file systems are
28781 **       automatically configured for proxy locking, lock files are
28782 **       named automatically using the same logic as
28783 **       PRAGMA lock_proxy_file=":auto:"
28784 **    
28785 **  SQLITE_PROXY_DEBUG
28786 **
28787 **       Enables the logging of error messages during host id file
28788 **       retrieval and creation
28789 **
28790 **  LOCKPROXYDIR
28791 **
28792 **       Overrides the default directory used for lock proxy files that
28793 **       are named automatically via the ":auto:" setting
28794 **
28795 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
28796 **
28797 **       Permissions to use when creating a directory for storing the
28798 **       lock proxy files, only used when LOCKPROXYDIR is not set.
28799 **    
28800 **    
28801 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
28802 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
28803 ** force proxy locking to be used for every database file opened, and 0
28804 ** will force automatic proxy locking to be disabled for all database
28805 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
28806 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
28807 */
28808
28809 /*
28810 ** Proxy locking is only available on MacOSX 
28811 */
28812 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28813
28814 /*
28815 ** The proxyLockingContext has the path and file structures for the remote 
28816 ** and local proxy files in it
28817 */
28818 typedef struct proxyLockingContext proxyLockingContext;
28819 struct proxyLockingContext {
28820   unixFile *conchFile;         /* Open conch file */
28821   char *conchFilePath;         /* Name of the conch file */
28822   unixFile *lockProxy;         /* Open proxy lock file */
28823   char *lockProxyPath;         /* Name of the proxy lock file */
28824   char *dbPath;                /* Name of the open file */
28825   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
28826   void *oldLockingContext;     /* Original lockingcontext to restore on close */
28827   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
28828 };
28829
28830 /* 
28831 ** The proxy lock file path for the database at dbPath is written into lPath, 
28832 ** which must point to valid, writable memory large enough for a maxLen length
28833 ** file path. 
28834 */
28835 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
28836   int len;
28837   int dbLen;
28838   int i;
28839
28840 #ifdef LOCKPROXYDIR
28841   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
28842 #else
28843 # ifdef _CS_DARWIN_USER_TEMP_DIR
28844   {
28845     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
28846       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
28847                lPath, errno, getpid()));
28848       return SQLITE_IOERR_LOCK;
28849     }
28850     len = strlcat(lPath, "sqliteplocks", maxLen);    
28851   }
28852 # else
28853   len = strlcpy(lPath, "/tmp/", maxLen);
28854 # endif
28855 #endif
28856
28857   if( lPath[len-1]!='/' ){
28858     len = strlcat(lPath, "/", maxLen);
28859   }
28860   
28861   /* transform the db path to a unique cache name */
28862   dbLen = (int)strlen(dbPath);
28863   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
28864     char c = dbPath[i];
28865     lPath[i+len] = (c=='/')?'_':c;
28866   }
28867   lPath[i+len]='\0';
28868   strlcat(lPath, ":auto:", maxLen);
28869   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
28870   return SQLITE_OK;
28871 }
28872
28873 /* 
28874  ** Creates the lock file and any missing directories in lockPath
28875  */
28876 static int proxyCreateLockPath(const char *lockPath){
28877   int i, len;
28878   char buf[MAXPATHLEN];
28879   int start = 0;
28880   
28881   assert(lockPath!=NULL);
28882   /* try to create all the intermediate directories */
28883   len = (int)strlen(lockPath);
28884   buf[0] = lockPath[0];
28885   for( i=1; i<len; i++ ){
28886     if( lockPath[i] == '/' && (i - start > 0) ){
28887       /* only mkdir if leaf dir != "." or "/" or ".." */
28888       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
28889          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
28890         buf[i]='\0';
28891         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
28892           int err=errno;
28893           if( err!=EEXIST ) {
28894             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
28895                      "'%s' proxy lock path=%s pid=%d\n",
28896                      buf, strerror(err), lockPath, getpid()));
28897             return err;
28898           }
28899         }
28900       }
28901       start=i+1;
28902     }
28903     buf[i] = lockPath[i];
28904   }
28905   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
28906   return 0;
28907 }
28908
28909 /*
28910 ** Create a new VFS file descriptor (stored in memory obtained from
28911 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
28912 **
28913 ** The caller is responsible not only for closing the file descriptor
28914 ** but also for freeing the memory associated with the file descriptor.
28915 */
28916 static int proxyCreateUnixFile(
28917     const char *path,        /* path for the new unixFile */
28918     unixFile **ppFile,       /* unixFile created and returned by ref */
28919     int islockfile           /* if non zero missing dirs will be created */
28920 ) {
28921   int fd = -1;
28922   unixFile *pNew;
28923   int rc = SQLITE_OK;
28924   int openFlags = O_RDWR | O_CREAT;
28925   sqlite3_vfs dummyVfs;
28926   int terrno = 0;
28927   UnixUnusedFd *pUnused = NULL;
28928
28929   /* 1. first try to open/create the file
28930   ** 2. if that fails, and this is a lock file (not-conch), try creating
28931   ** the parent directories and then try again.
28932   ** 3. if that fails, try to open the file read-only
28933   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
28934   */
28935   pUnused = findReusableFd(path, openFlags);
28936   if( pUnused ){
28937     fd = pUnused->fd;
28938   }else{
28939     pUnused = sqlite3_malloc(sizeof(*pUnused));
28940     if( !pUnused ){
28941       return SQLITE_NOMEM;
28942     }
28943   }
28944   if( fd<0 ){
28945     fd = robust_open(path, openFlags, 0);
28946     terrno = errno;
28947     if( fd<0 && errno==ENOENT && islockfile ){
28948       if( proxyCreateLockPath(path) == SQLITE_OK ){
28949         fd = robust_open(path, openFlags, 0);
28950       }
28951     }
28952   }
28953   if( fd<0 ){
28954     openFlags = O_RDONLY;
28955     fd = robust_open(path, openFlags, 0);
28956     terrno = errno;
28957   }
28958   if( fd<0 ){
28959     if( islockfile ){
28960       return SQLITE_BUSY;
28961     }
28962     switch (terrno) {
28963       case EACCES:
28964         return SQLITE_PERM;
28965       case EIO: 
28966         return SQLITE_IOERR_LOCK; /* even though it is the conch */
28967       default:
28968         return SQLITE_CANTOPEN_BKPT;
28969     }
28970   }
28971   
28972   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
28973   if( pNew==NULL ){
28974     rc = SQLITE_NOMEM;
28975     goto end_create_proxy;
28976   }
28977   memset(pNew, 0, sizeof(unixFile));
28978   pNew->openFlags = openFlags;
28979   memset(&dummyVfs, 0, sizeof(dummyVfs));
28980   dummyVfs.pAppData = (void*)&autolockIoFinder;
28981   dummyVfs.zName = "dummy";
28982   pUnused->fd = fd;
28983   pUnused->flags = openFlags;
28984   pNew->pUnused = pUnused;
28985   
28986   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
28987   if( rc==SQLITE_OK ){
28988     *ppFile = pNew;
28989     return SQLITE_OK;
28990   }
28991 end_create_proxy:    
28992   robust_close(pNew, fd, __LINE__);
28993   sqlite3_free(pNew);
28994   sqlite3_free(pUnused);
28995   return rc;
28996 }
28997
28998 #ifdef SQLITE_TEST
28999 /* simulate multiple hosts by creating unique hostid file paths */
29000 SQLITE_API int sqlite3_hostid_num = 0;
29001 #endif
29002
29003 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
29004
29005 /* Not always defined in the headers as it ought to be */
29006 extern int gethostuuid(uuid_t id, const struct timespec *wait);
29007
29008 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
29009 ** bytes of writable memory.
29010 */
29011 static int proxyGetHostID(unsigned char *pHostID, int *pError){
29012   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
29013   memset(pHostID, 0, PROXY_HOSTIDLEN);
29014 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
29015                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
29016   {
29017     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
29018     if( gethostuuid(pHostID, &timeout) ){
29019       int err = errno;
29020       if( pError ){
29021         *pError = err;
29022       }
29023       return SQLITE_IOERR;
29024     }
29025   }
29026 #else
29027   UNUSED_PARAMETER(pError);
29028 #endif
29029 #ifdef SQLITE_TEST
29030   /* simulate multiple hosts by creating unique hostid file paths */
29031   if( sqlite3_hostid_num != 0){
29032     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
29033   }
29034 #endif
29035   
29036   return SQLITE_OK;
29037 }
29038
29039 /* The conch file contains the header, host id and lock file path
29040  */
29041 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
29042 #define PROXY_HEADERLEN    1   /* conch file header length */
29043 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
29044 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
29045
29046 /* 
29047 ** Takes an open conch file, copies the contents to a new path and then moves 
29048 ** it back.  The newly created file's file descriptor is assigned to the
29049 ** conch file structure and finally the original conch file descriptor is 
29050 ** closed.  Returns zero if successful.
29051 */
29052 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
29053   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29054   unixFile *conchFile = pCtx->conchFile;
29055   char tPath[MAXPATHLEN];
29056   char buf[PROXY_MAXCONCHLEN];
29057   char *cPath = pCtx->conchFilePath;
29058   size_t readLen = 0;
29059   size_t pathLen = 0;
29060   char errmsg[64] = "";
29061   int fd = -1;
29062   int rc = -1;
29063   UNUSED_PARAMETER(myHostID);
29064
29065   /* create a new path by replace the trailing '-conch' with '-break' */
29066   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
29067   if( pathLen>MAXPATHLEN || pathLen<6 || 
29068      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
29069     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
29070     goto end_breaklock;
29071   }
29072   /* read the conch content */
29073   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
29074   if( readLen<PROXY_PATHINDEX ){
29075     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
29076     goto end_breaklock;
29077   }
29078   /* write it out to the temporary break file */
29079   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
29080   if( fd<0 ){
29081     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
29082     goto end_breaklock;
29083   }
29084   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
29085     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
29086     goto end_breaklock;
29087   }
29088   if( rename(tPath, cPath) ){
29089     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
29090     goto end_breaklock;
29091   }
29092   rc = 0;
29093   fprintf(stderr, "broke stale lock on %s\n", cPath);
29094   robust_close(pFile, conchFile->h, __LINE__);
29095   conchFile->h = fd;
29096   conchFile->openFlags = O_RDWR | O_CREAT;
29097
29098 end_breaklock:
29099   if( rc ){
29100     if( fd>=0 ){
29101       osUnlink(tPath);
29102       robust_close(pFile, fd, __LINE__);
29103     }
29104     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
29105   }
29106   return rc;
29107 }
29108
29109 /* Take the requested lock on the conch file and break a stale lock if the 
29110 ** host id matches.
29111 */
29112 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
29113   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29114   unixFile *conchFile = pCtx->conchFile;
29115   int rc = SQLITE_OK;
29116   int nTries = 0;
29117   struct timespec conchModTime;
29118   
29119   memset(&conchModTime, 0, sizeof(conchModTime));
29120   do {
29121     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29122     nTries ++;
29123     if( rc==SQLITE_BUSY ){
29124       /* If the lock failed (busy):
29125        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
29126        * 2nd try: fail if the mod time changed or host id is different, wait 
29127        *           10 sec and try again
29128        * 3rd try: break the lock unless the mod time has changed.
29129        */
29130       struct stat buf;
29131       if( osFstat(conchFile->h, &buf) ){
29132         pFile->lastErrno = errno;
29133         return SQLITE_IOERR_LOCK;
29134       }
29135       
29136       if( nTries==1 ){
29137         conchModTime = buf.st_mtimespec;
29138         usleep(500000); /* wait 0.5 sec and try the lock again*/
29139         continue;  
29140       }
29141
29142       assert( nTries>1 );
29143       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
29144          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
29145         return SQLITE_BUSY;
29146       }
29147       
29148       if( nTries==2 ){  
29149         char tBuf[PROXY_MAXCONCHLEN];
29150         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
29151         if( len<0 ){
29152           pFile->lastErrno = errno;
29153           return SQLITE_IOERR_LOCK;
29154         }
29155         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
29156           /* don't break the lock if the host id doesn't match */
29157           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
29158             return SQLITE_BUSY;
29159           }
29160         }else{
29161           /* don't break the lock on short read or a version mismatch */
29162           return SQLITE_BUSY;
29163         }
29164         usleep(10000000); /* wait 10 sec and try the lock again */
29165         continue; 
29166       }
29167       
29168       assert( nTries==3 );
29169       if( 0==proxyBreakConchLock(pFile, myHostID) ){
29170         rc = SQLITE_OK;
29171         if( lockType==EXCLUSIVE_LOCK ){
29172           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
29173         }
29174         if( !rc ){
29175           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29176         }
29177       }
29178     }
29179   } while( rc==SQLITE_BUSY && nTries<3 );
29180   
29181   return rc;
29182 }
29183
29184 /* Takes the conch by taking a shared lock and read the contents conch, if 
29185 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
29186 ** lockPath means that the lockPath in the conch file will be used if the 
29187 ** host IDs match, or a new lock path will be generated automatically 
29188 ** and written to the conch file.
29189 */
29190 static int proxyTakeConch(unixFile *pFile){
29191   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29192   
29193   if( pCtx->conchHeld!=0 ){
29194     return SQLITE_OK;
29195   }else{
29196     unixFile *conchFile = pCtx->conchFile;
29197     uuid_t myHostID;
29198     int pError = 0;
29199     char readBuf[PROXY_MAXCONCHLEN];
29200     char lockPath[MAXPATHLEN];
29201     char *tempLockPath = NULL;
29202     int rc = SQLITE_OK;
29203     int createConch = 0;
29204     int hostIdMatch = 0;
29205     int readLen = 0;
29206     int tryOldLockPath = 0;
29207     int forceNewLockPath = 0;
29208     
29209     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
29210              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
29211
29212     rc = proxyGetHostID(myHostID, &pError);
29213     if( (rc&0xff)==SQLITE_IOERR ){
29214       pFile->lastErrno = pError;
29215       goto end_takeconch;
29216     }
29217     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
29218     if( rc!=SQLITE_OK ){
29219       goto end_takeconch;
29220     }
29221     /* read the existing conch file */
29222     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
29223     if( readLen<0 ){
29224       /* I/O error: lastErrno set by seekAndRead */
29225       pFile->lastErrno = conchFile->lastErrno;
29226       rc = SQLITE_IOERR_READ;
29227       goto end_takeconch;
29228     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
29229              readBuf[0]!=(char)PROXY_CONCHVERSION ){
29230       /* a short read or version format mismatch means we need to create a new 
29231       ** conch file. 
29232       */
29233       createConch = 1;
29234     }
29235     /* if the host id matches and the lock path already exists in the conch
29236     ** we'll try to use the path there, if we can't open that path, we'll 
29237     ** retry with a new auto-generated path 
29238     */
29239     do { /* in case we need to try again for an :auto: named lock file */
29240
29241       if( !createConch && !forceNewLockPath ){
29242         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
29243                                   PROXY_HOSTIDLEN);
29244         /* if the conch has data compare the contents */
29245         if( !pCtx->lockProxyPath ){
29246           /* for auto-named local lock file, just check the host ID and we'll
29247            ** use the local lock file path that's already in there
29248            */
29249           if( hostIdMatch ){
29250             size_t pathLen = (readLen - PROXY_PATHINDEX);
29251             
29252             if( pathLen>=MAXPATHLEN ){
29253               pathLen=MAXPATHLEN-1;
29254             }
29255             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
29256             lockPath[pathLen] = 0;
29257             tempLockPath = lockPath;
29258             tryOldLockPath = 1;
29259             /* create a copy of the lock path if the conch is taken */
29260             goto end_takeconch;
29261           }
29262         }else if( hostIdMatch
29263                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
29264                            readLen-PROXY_PATHINDEX)
29265         ){
29266           /* conch host and lock path match */
29267           goto end_takeconch; 
29268         }
29269       }
29270       
29271       /* if the conch isn't writable and doesn't match, we can't take it */
29272       if( (conchFile->openFlags&O_RDWR) == 0 ){
29273         rc = SQLITE_BUSY;
29274         goto end_takeconch;
29275       }
29276       
29277       /* either the conch didn't match or we need to create a new one */
29278       if( !pCtx->lockProxyPath ){
29279         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
29280         tempLockPath = lockPath;
29281         /* create a copy of the lock path _only_ if the conch is taken */
29282       }
29283       
29284       /* update conch with host and path (this will fail if other process
29285       ** has a shared lock already), if the host id matches, use the big
29286       ** stick.
29287       */
29288       futimes(conchFile->h, NULL);
29289       if( hostIdMatch && !createConch ){
29290         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
29291           /* We are trying for an exclusive lock but another thread in this
29292            ** same process is still holding a shared lock. */
29293           rc = SQLITE_BUSY;
29294         } else {          
29295           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
29296         }
29297       }else{
29298         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
29299       }
29300       if( rc==SQLITE_OK ){
29301         char writeBuffer[PROXY_MAXCONCHLEN];
29302         int writeSize = 0;
29303         
29304         writeBuffer[0] = (char)PROXY_CONCHVERSION;
29305         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
29306         if( pCtx->lockProxyPath!=NULL ){
29307           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
29308         }else{
29309           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
29310         }
29311         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
29312         robust_ftruncate(conchFile->h, writeSize);
29313         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
29314         fsync(conchFile->h);
29315         /* If we created a new conch file (not just updated the contents of a 
29316          ** valid conch file), try to match the permissions of the database 
29317          */
29318         if( rc==SQLITE_OK && createConch ){
29319           struct stat buf;
29320           int err = osFstat(pFile->h, &buf);
29321           if( err==0 ){
29322             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
29323                                         S_IROTH|S_IWOTH);
29324             /* try to match the database file R/W permissions, ignore failure */
29325 #ifndef SQLITE_PROXY_DEBUG
29326             osFchmod(conchFile->h, cmode);
29327 #else
29328             do{
29329               rc = osFchmod(conchFile->h, cmode);
29330             }while( rc==(-1) && errno==EINTR );
29331             if( rc!=0 ){
29332               int code = errno;
29333               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
29334                       cmode, code, strerror(code));
29335             } else {
29336               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
29337             }
29338           }else{
29339             int code = errno;
29340             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
29341                     err, code, strerror(code));
29342 #endif
29343           }
29344         }
29345       }
29346       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
29347       
29348     end_takeconch:
29349       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
29350       if( rc==SQLITE_OK && pFile->openFlags ){
29351         int fd;
29352         if( pFile->h>=0 ){
29353           robust_close(pFile, pFile->h, __LINE__);
29354         }
29355         pFile->h = -1;
29356         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
29357         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
29358         if( fd>=0 ){
29359           pFile->h = fd;
29360         }else{
29361           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
29362            during locking */
29363         }
29364       }
29365       if( rc==SQLITE_OK && !pCtx->lockProxy ){
29366         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
29367         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
29368         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
29369           /* we couldn't create the proxy lock file with the old lock file path
29370            ** so try again via auto-naming 
29371            */
29372           forceNewLockPath = 1;
29373           tryOldLockPath = 0;
29374           continue; /* go back to the do {} while start point, try again */
29375         }
29376       }
29377       if( rc==SQLITE_OK ){
29378         /* Need to make a copy of path if we extracted the value
29379          ** from the conch file or the path was allocated on the stack
29380          */
29381         if( tempLockPath ){
29382           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
29383           if( !pCtx->lockProxyPath ){
29384             rc = SQLITE_NOMEM;
29385           }
29386         }
29387       }
29388       if( rc==SQLITE_OK ){
29389         pCtx->conchHeld = 1;
29390         
29391         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
29392           afpLockingContext *afpCtx;
29393           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
29394           afpCtx->dbPath = pCtx->lockProxyPath;
29395         }
29396       } else {
29397         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29398       }
29399       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
29400                rc==SQLITE_OK?"ok":"failed"));
29401       return rc;
29402     } while (1); /* in case we need to retry the :auto: lock file - 
29403                  ** we should never get here except via the 'continue' call. */
29404   }
29405 }
29406
29407 /*
29408 ** If pFile holds a lock on a conch file, then release that lock.
29409 */
29410 static int proxyReleaseConch(unixFile *pFile){
29411   int rc = SQLITE_OK;         /* Subroutine return code */
29412   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
29413   unixFile *conchFile;        /* Name of the conch file */
29414
29415   pCtx = (proxyLockingContext *)pFile->lockingContext;
29416   conchFile = pCtx->conchFile;
29417   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
29418            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
29419            getpid()));
29420   if( pCtx->conchHeld>0 ){
29421     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29422   }
29423   pCtx->conchHeld = 0;
29424   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
29425            (rc==SQLITE_OK ? "ok" : "failed")));
29426   return rc;
29427 }
29428
29429 /*
29430 ** Given the name of a database file, compute the name of its conch file.
29431 ** Store the conch filename in memory obtained from sqlite3_malloc().
29432 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
29433 ** or SQLITE_NOMEM if unable to obtain memory.
29434 **
29435 ** The caller is responsible for ensuring that the allocated memory
29436 ** space is eventually freed.
29437 **
29438 ** *pConchPath is set to NULL if a memory allocation error occurs.
29439 */
29440 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
29441   int i;                        /* Loop counter */
29442   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
29443   char *conchPath;              /* buffer in which to construct conch name */
29444
29445   /* Allocate space for the conch filename and initialize the name to
29446   ** the name of the original database file. */  
29447   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
29448   if( conchPath==0 ){
29449     return SQLITE_NOMEM;
29450   }
29451   memcpy(conchPath, dbPath, len+1);
29452   
29453   /* now insert a "." before the last / character */
29454   for( i=(len-1); i>=0; i-- ){
29455     if( conchPath[i]=='/' ){
29456       i++;
29457       break;
29458     }
29459   }
29460   conchPath[i]='.';
29461   while ( i<len ){
29462     conchPath[i+1]=dbPath[i];
29463     i++;
29464   }
29465
29466   /* append the "-conch" suffix to the file */
29467   memcpy(&conchPath[i+1], "-conch", 7);
29468   assert( (int)strlen(conchPath) == len+7 );
29469
29470   return SQLITE_OK;
29471 }
29472
29473
29474 /* Takes a fully configured proxy locking-style unix file and switches
29475 ** the local lock file path 
29476 */
29477 static int switchLockProxyPath(unixFile *pFile, const char *path) {
29478   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
29479   char *oldPath = pCtx->lockProxyPath;
29480   int rc = SQLITE_OK;
29481
29482   if( pFile->eFileLock!=NO_LOCK ){
29483     return SQLITE_BUSY;
29484   }  
29485
29486   /* nothing to do if the path is NULL, :auto: or matches the existing path */
29487   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
29488     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
29489     return SQLITE_OK;
29490   }else{
29491     unixFile *lockProxy = pCtx->lockProxy;
29492     pCtx->lockProxy=NULL;
29493     pCtx->conchHeld = 0;
29494     if( lockProxy!=NULL ){
29495       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
29496       if( rc ) return rc;
29497       sqlite3_free(lockProxy);
29498     }
29499     sqlite3_free(oldPath);
29500     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
29501   }
29502   
29503   return rc;
29504 }
29505
29506 /*
29507 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
29508 ** is a string buffer at least MAXPATHLEN+1 characters in size.
29509 **
29510 ** This routine find the filename associated with pFile and writes it
29511 ** int dbPath.
29512 */
29513 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
29514 #if defined(__APPLE__)
29515   if( pFile->pMethod == &afpIoMethods ){
29516     /* afp style keeps a reference to the db path in the filePath field 
29517     ** of the struct */
29518     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
29519     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
29520   } else
29521 #endif
29522   if( pFile->pMethod == &dotlockIoMethods ){
29523     /* dot lock style uses the locking context to store the dot lock
29524     ** file path */
29525     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
29526     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
29527   }else{
29528     /* all other styles use the locking context to store the db file path */
29529     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
29530     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
29531   }
29532   return SQLITE_OK;
29533 }
29534
29535 /*
29536 ** Takes an already filled in unix file and alters it so all file locking 
29537 ** will be performed on the local proxy lock file.  The following fields
29538 ** are preserved in the locking context so that they can be restored and 
29539 ** the unix structure properly cleaned up at close time:
29540 **  ->lockingContext
29541 **  ->pMethod
29542 */
29543 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
29544   proxyLockingContext *pCtx;
29545   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
29546   char *lockPath=NULL;
29547   int rc = SQLITE_OK;
29548   
29549   if( pFile->eFileLock!=NO_LOCK ){
29550     return SQLITE_BUSY;
29551   }
29552   proxyGetDbPathForUnixFile(pFile, dbPath);
29553   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
29554     lockPath=NULL;
29555   }else{
29556     lockPath=(char *)path;
29557   }
29558   
29559   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
29560            (lockPath ? lockPath : ":auto:"), getpid()));
29561
29562   pCtx = sqlite3_malloc( sizeof(*pCtx) );
29563   if( pCtx==0 ){
29564     return SQLITE_NOMEM;
29565   }
29566   memset(pCtx, 0, sizeof(*pCtx));
29567
29568   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
29569   if( rc==SQLITE_OK ){
29570     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
29571     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
29572       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
29573       ** (c) the file system is read-only, then enable no-locking access.
29574       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
29575       ** that openFlags will have only one of O_RDONLY or O_RDWR.
29576       */
29577       struct statfs fsInfo;
29578       struct stat conchInfo;
29579       int goLockless = 0;
29580
29581       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
29582         int err = errno;
29583         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
29584           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
29585         }
29586       }
29587       if( goLockless ){
29588         pCtx->conchHeld = -1; /* read only FS/ lockless */
29589         rc = SQLITE_OK;
29590       }
29591     }
29592   }  
29593   if( rc==SQLITE_OK && lockPath ){
29594     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
29595   }
29596
29597   if( rc==SQLITE_OK ){
29598     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
29599     if( pCtx->dbPath==NULL ){
29600       rc = SQLITE_NOMEM;
29601     }
29602   }
29603   if( rc==SQLITE_OK ){
29604     /* all memory is allocated, proxys are created and assigned, 
29605     ** switch the locking context and pMethod then return.
29606     */
29607     pCtx->oldLockingContext = pFile->lockingContext;
29608     pFile->lockingContext = pCtx;
29609     pCtx->pOldMethod = pFile->pMethod;
29610     pFile->pMethod = &proxyIoMethods;
29611   }else{
29612     if( pCtx->conchFile ){ 
29613       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
29614       sqlite3_free(pCtx->conchFile);
29615     }
29616     sqlite3DbFree(0, pCtx->lockProxyPath);
29617     sqlite3_free(pCtx->conchFilePath); 
29618     sqlite3_free(pCtx);
29619   }
29620   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
29621            (rc==SQLITE_OK ? "ok" : "failed")));
29622   return rc;
29623 }
29624
29625
29626 /*
29627 ** This routine handles sqlite3_file_control() calls that are specific
29628 ** to proxy locking.
29629 */
29630 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
29631   switch( op ){
29632     case SQLITE_GET_LOCKPROXYFILE: {
29633       unixFile *pFile = (unixFile*)id;
29634       if( pFile->pMethod == &proxyIoMethods ){
29635         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
29636         proxyTakeConch(pFile);
29637         if( pCtx->lockProxyPath ){
29638           *(const char **)pArg = pCtx->lockProxyPath;
29639         }else{
29640           *(const char **)pArg = ":auto: (not held)";
29641         }
29642       } else {
29643         *(const char **)pArg = NULL;
29644       }
29645       return SQLITE_OK;
29646     }
29647     case SQLITE_SET_LOCKPROXYFILE: {
29648       unixFile *pFile = (unixFile*)id;
29649       int rc = SQLITE_OK;
29650       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
29651       if( pArg==NULL || (const char *)pArg==0 ){
29652         if( isProxyStyle ){
29653           /* turn off proxy locking - not supported */
29654           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
29655         }else{
29656           /* turn off proxy locking - already off - NOOP */
29657           rc = SQLITE_OK;
29658         }
29659       }else{
29660         const char *proxyPath = (const char *)pArg;
29661         if( isProxyStyle ){
29662           proxyLockingContext *pCtx = 
29663             (proxyLockingContext*)pFile->lockingContext;
29664           if( !strcmp(pArg, ":auto:") 
29665            || (pCtx->lockProxyPath &&
29666                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
29667           ){
29668             rc = SQLITE_OK;
29669           }else{
29670             rc = switchLockProxyPath(pFile, proxyPath);
29671           }
29672         }else{
29673           /* turn on proxy file locking */
29674           rc = proxyTransformUnixFile(pFile, proxyPath);
29675         }
29676       }
29677       return rc;
29678     }
29679     default: {
29680       assert( 0 );  /* The call assures that only valid opcodes are sent */
29681     }
29682   }
29683   /*NOTREACHED*/
29684   return SQLITE_ERROR;
29685 }
29686
29687 /*
29688 ** Within this division (the proxying locking implementation) the procedures
29689 ** above this point are all utilities.  The lock-related methods of the
29690 ** proxy-locking sqlite3_io_method object follow.
29691 */
29692
29693
29694 /*
29695 ** This routine checks if there is a RESERVED lock held on the specified
29696 ** file by this or any other process. If such a lock is held, set *pResOut
29697 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
29698 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
29699 */
29700 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
29701   unixFile *pFile = (unixFile*)id;
29702   int rc = proxyTakeConch(pFile);
29703   if( rc==SQLITE_OK ){
29704     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29705     if( pCtx->conchHeld>0 ){
29706       unixFile *proxy = pCtx->lockProxy;
29707       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
29708     }else{ /* conchHeld < 0 is lockless */
29709       pResOut=0;
29710     }
29711   }
29712   return rc;
29713 }
29714
29715 /*
29716 ** Lock the file with the lock specified by parameter eFileLock - one
29717 ** of the following:
29718 **
29719 **     (1) SHARED_LOCK
29720 **     (2) RESERVED_LOCK
29721 **     (3) PENDING_LOCK
29722 **     (4) EXCLUSIVE_LOCK
29723 **
29724 ** Sometimes when requesting one lock state, additional lock states
29725 ** are inserted in between.  The locking might fail on one of the later
29726 ** transitions leaving the lock state different from what it started but
29727 ** still short of its goal.  The following chart shows the allowed
29728 ** transitions and the inserted intermediate states:
29729 **
29730 **    UNLOCKED -> SHARED
29731 **    SHARED -> RESERVED
29732 **    SHARED -> (PENDING) -> EXCLUSIVE
29733 **    RESERVED -> (PENDING) -> EXCLUSIVE
29734 **    PENDING -> EXCLUSIVE
29735 **
29736 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
29737 ** routine to lower a locking level.
29738 */
29739 static int proxyLock(sqlite3_file *id, int eFileLock) {
29740   unixFile *pFile = (unixFile*)id;
29741   int rc = proxyTakeConch(pFile);
29742   if( rc==SQLITE_OK ){
29743     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29744     if( pCtx->conchHeld>0 ){
29745       unixFile *proxy = pCtx->lockProxy;
29746       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
29747       pFile->eFileLock = proxy->eFileLock;
29748     }else{
29749       /* conchHeld < 0 is lockless */
29750     }
29751   }
29752   return rc;
29753 }
29754
29755
29756 /*
29757 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29758 ** must be either NO_LOCK or SHARED_LOCK.
29759 **
29760 ** If the locking level of the file descriptor is already at or below
29761 ** the requested locking level, this routine is a no-op.
29762 */
29763 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
29764   unixFile *pFile = (unixFile*)id;
29765   int rc = proxyTakeConch(pFile);
29766   if( rc==SQLITE_OK ){
29767     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29768     if( pCtx->conchHeld>0 ){
29769       unixFile *proxy = pCtx->lockProxy;
29770       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
29771       pFile->eFileLock = proxy->eFileLock;
29772     }else{
29773       /* conchHeld < 0 is lockless */
29774     }
29775   }
29776   return rc;
29777 }
29778
29779 /*
29780 ** Close a file that uses proxy locks.
29781 */
29782 static int proxyClose(sqlite3_file *id) {
29783   if( id ){
29784     unixFile *pFile = (unixFile*)id;
29785     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29786     unixFile *lockProxy = pCtx->lockProxy;
29787     unixFile *conchFile = pCtx->conchFile;
29788     int rc = SQLITE_OK;
29789     
29790     if( lockProxy ){
29791       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
29792       if( rc ) return rc;
29793       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
29794       if( rc ) return rc;
29795       sqlite3_free(lockProxy);
29796       pCtx->lockProxy = 0;
29797     }
29798     if( conchFile ){
29799       if( pCtx->conchHeld ){
29800         rc = proxyReleaseConch(pFile);
29801         if( rc ) return rc;
29802       }
29803       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
29804       if( rc ) return rc;
29805       sqlite3_free(conchFile);
29806     }
29807     sqlite3DbFree(0, pCtx->lockProxyPath);
29808     sqlite3_free(pCtx->conchFilePath);
29809     sqlite3DbFree(0, pCtx->dbPath);
29810     /* restore the original locking context and pMethod then close it */
29811     pFile->lockingContext = pCtx->oldLockingContext;
29812     pFile->pMethod = pCtx->pOldMethod;
29813     sqlite3_free(pCtx);
29814     return pFile->pMethod->xClose(id);
29815   }
29816   return SQLITE_OK;
29817 }
29818
29819
29820
29821 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29822 /*
29823 ** The proxy locking style is intended for use with AFP filesystems.
29824 ** And since AFP is only supported on MacOSX, the proxy locking is also
29825 ** restricted to MacOSX.
29826 ** 
29827 **
29828 ******************* End of the proxy lock implementation **********************
29829 ******************************************************************************/
29830
29831 /*
29832 ** Initialize the operating system interface.
29833 **
29834 ** This routine registers all VFS implementations for unix-like operating
29835 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
29836 ** should be the only routines in this file that are visible from other
29837 ** files.
29838 **
29839 ** This routine is called once during SQLite initialization and by a
29840 ** single thread.  The memory allocation and mutex subsystems have not
29841 ** necessarily been initialized when this routine is called, and so they
29842 ** should not be used.
29843 */
29844 SQLITE_API int sqlite3_os_init(void){ 
29845   /* 
29846   ** The following macro defines an initializer for an sqlite3_vfs object.
29847   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
29848   ** to the "finder" function.  (pAppData is a pointer to a pointer because
29849   ** silly C90 rules prohibit a void* from being cast to a function pointer
29850   ** and so we have to go through the intermediate pointer to avoid problems
29851   ** when compiling with -pedantic-errors on GCC.)
29852   **
29853   ** The FINDER parameter to this macro is the name of the pointer to the
29854   ** finder-function.  The finder-function returns a pointer to the
29855   ** sqlite_io_methods object that implements the desired locking
29856   ** behaviors.  See the division above that contains the IOMETHODS
29857   ** macro for addition information on finder-functions.
29858   **
29859   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
29860   ** object.  But the "autolockIoFinder" available on MacOSX does a little
29861   ** more than that; it looks at the filesystem type that hosts the 
29862   ** database file and tries to choose an locking method appropriate for
29863   ** that filesystem time.
29864   */
29865   #define UNIXVFS(VFSNAME, FINDER) {                        \
29866     3,                    /* iVersion */                    \
29867     sizeof(unixFile),     /* szOsFile */                    \
29868     MAX_PATHNAME,         /* mxPathname */                  \
29869     0,                    /* pNext */                       \
29870     VFSNAME,              /* zName */                       \
29871     (void*)&FINDER,       /* pAppData */                    \
29872     unixOpen,             /* xOpen */                       \
29873     unixDelete,           /* xDelete */                     \
29874     unixAccess,           /* xAccess */                     \
29875     unixFullPathname,     /* xFullPathname */               \
29876     unixDlOpen,           /* xDlOpen */                     \
29877     unixDlError,          /* xDlError */                    \
29878     unixDlSym,            /* xDlSym */                      \
29879     unixDlClose,          /* xDlClose */                    \
29880     unixRandomness,       /* xRandomness */                 \
29881     unixSleep,            /* xSleep */                      \
29882     unixCurrentTime,      /* xCurrentTime */                \
29883     unixGetLastError,     /* xGetLastError */               \
29884     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
29885     unixSetSystemCall,    /* xSetSystemCall */              \
29886     unixGetSystemCall,    /* xGetSystemCall */              \
29887     unixNextSystemCall,   /* xNextSystemCall */             \
29888   }
29889
29890   /*
29891   ** All default VFSes for unix are contained in the following array.
29892   **
29893   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
29894   ** by the SQLite core when the VFS is registered.  So the following
29895   ** array cannot be const.
29896   */
29897   static sqlite3_vfs aVfs[] = {
29898 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
29899     UNIXVFS("unix",          autolockIoFinder ),
29900 #else
29901     UNIXVFS("unix",          posixIoFinder ),
29902 #endif
29903     UNIXVFS("unix-none",     nolockIoFinder ),
29904     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
29905     UNIXVFS("unix-excl",     posixIoFinder ),
29906 #if OS_VXWORKS
29907     UNIXVFS("unix-namedsem", semIoFinder ),
29908 #endif
29909 #if SQLITE_ENABLE_LOCKING_STYLE
29910     UNIXVFS("unix-posix",    posixIoFinder ),
29911 #if !OS_VXWORKS
29912     UNIXVFS("unix-flock",    flockIoFinder ),
29913 #endif
29914 #endif
29915 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29916     UNIXVFS("unix-afp",      afpIoFinder ),
29917     UNIXVFS("unix-nfs",      nfsIoFinder ),
29918     UNIXVFS("unix-proxy",    proxyIoFinder ),
29919 #endif
29920   };
29921   unsigned int i;          /* Loop counter */
29922
29923   /* Double-check that the aSyscall[] array has been constructed
29924   ** correctly.  See ticket [bb3a86e890c8e96ab] */
29925   assert( ArraySize(aSyscall)==21 );
29926
29927   /* Register all VFSes defined in the aVfs[] array */
29928   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
29929     sqlite3_vfs_register(&aVfs[i], i==0);
29930   }
29931   return SQLITE_OK; 
29932 }
29933
29934 /*
29935 ** Shutdown the operating system interface.
29936 **
29937 ** Some operating systems might need to do some cleanup in this routine,
29938 ** to release dynamically allocated objects.  But not on unix.
29939 ** This routine is a no-op for unix.
29940 */
29941 SQLITE_API int sqlite3_os_end(void){ 
29942   return SQLITE_OK; 
29943 }
29944  
29945 #endif /* SQLITE_OS_UNIX */
29946
29947 /************** End of os_unix.c *********************************************/
29948 /************** Begin file os_win.c ******************************************/
29949 /*
29950 ** 2004 May 22
29951 **
29952 ** The author disclaims copyright to this source code.  In place of
29953 ** a legal notice, here is a blessing:
29954 **
29955 **    May you do good and not evil.
29956 **    May you find forgiveness for yourself and forgive others.
29957 **    May you share freely, never taking more than you give.
29958 **
29959 ******************************************************************************
29960 **
29961 ** This file contains code that is specific to Windows.
29962 */
29963 #if SQLITE_OS_WIN               /* This file is used for Windows only */
29964
29965 #ifdef __CYGWIN__
29966 # include <sys/cygwin.h>
29967 #endif
29968
29969 /*
29970 ** Include code that is common to all os_*.c files
29971 */
29972 /************** Include os_common.h in the middle of os_win.c ****************/
29973 /************** Begin file os_common.h ***************************************/
29974 /*
29975 ** 2004 May 22
29976 **
29977 ** The author disclaims copyright to this source code.  In place of
29978 ** a legal notice, here is a blessing:
29979 **
29980 **    May you do good and not evil.
29981 **    May you find forgiveness for yourself and forgive others.
29982 **    May you share freely, never taking more than you give.
29983 **
29984 ******************************************************************************
29985 **
29986 ** This file contains macros and a little bit of code that is common to
29987 ** all of the platform-specific files (os_*.c) and is #included into those
29988 ** files.
29989 **
29990 ** This file should be #included by the os_*.c files only.  It is not a
29991 ** general purpose header file.
29992 */
29993 #ifndef _OS_COMMON_H_
29994 #define _OS_COMMON_H_
29995
29996 /*
29997 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29998 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29999 ** switch.  The following code should catch this problem at compile-time.
30000 */
30001 #ifdef MEMORY_DEBUG
30002 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
30003 #endif
30004
30005 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
30006 # ifndef SQLITE_DEBUG_OS_TRACE
30007 #   define SQLITE_DEBUG_OS_TRACE 0
30008 # endif
30009   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
30010 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
30011 #else
30012 # define OSTRACE(X)
30013 #endif
30014
30015 /*
30016 ** Macros for performance tracing.  Normally turned off.  Only works
30017 ** on i486 hardware.
30018 */
30019 #ifdef SQLITE_PERFORMANCE_TRACE
30020
30021 /* 
30022 ** hwtime.h contains inline assembler code for implementing 
30023 ** high-performance timing routines.
30024 */
30025 /************** Include hwtime.h in the middle of os_common.h ****************/
30026 /************** Begin file hwtime.h ******************************************/
30027 /*
30028 ** 2008 May 27
30029 **
30030 ** The author disclaims copyright to this source code.  In place of
30031 ** a legal notice, here is a blessing:
30032 **
30033 **    May you do good and not evil.
30034 **    May you find forgiveness for yourself and forgive others.
30035 **    May you share freely, never taking more than you give.
30036 **
30037 ******************************************************************************
30038 **
30039 ** This file contains inline asm code for retrieving "high-performance"
30040 ** counters for x86 class CPUs.
30041 */
30042 #ifndef _HWTIME_H_
30043 #define _HWTIME_H_
30044
30045 /*
30046 ** The following routine only works on pentium-class (or newer) processors.
30047 ** It uses the RDTSC opcode to read the cycle count value out of the
30048 ** processor and returns that value.  This can be used for high-res
30049 ** profiling.
30050 */
30051 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
30052       (defined(i386) || defined(__i386__) || defined(_M_IX86))
30053
30054   #if defined(__GNUC__)
30055
30056   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30057      unsigned int lo, hi;
30058      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
30059      return (sqlite_uint64)hi << 32 | lo;
30060   }
30061
30062   #elif defined(_MSC_VER)
30063
30064   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
30065      __asm {
30066         rdtsc
30067         ret       ; return value at EDX:EAX
30068      }
30069   }
30070
30071   #endif
30072
30073 #elif (defined(__GNUC__) && defined(__x86_64__))
30074
30075   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30076       unsigned long val;
30077       __asm__ __volatile__ ("rdtsc" : "=A" (val));
30078       return val;
30079   }
30080  
30081 #elif (defined(__GNUC__) && defined(__ppc__))
30082
30083   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30084       unsigned long long retval;
30085       unsigned long junk;
30086       __asm__ __volatile__ ("\n\
30087           1:      mftbu   %1\n\
30088                   mftb    %L0\n\
30089                   mftbu   %0\n\
30090                   cmpw    %0,%1\n\
30091                   bne     1b"
30092                   : "=r" (retval), "=r" (junk));
30093       return retval;
30094   }
30095
30096 #else
30097
30098   #error Need implementation of sqlite3Hwtime() for your platform.
30099
30100   /*
30101   ** To compile without implementing sqlite3Hwtime() for your platform,
30102   ** you can remove the above #error and use the following
30103   ** stub function.  You will lose timing support for many
30104   ** of the debugging and testing utilities, but it should at
30105   ** least compile and run.
30106   */
30107 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
30108
30109 #endif
30110
30111 #endif /* !defined(_HWTIME_H_) */
30112
30113 /************** End of hwtime.h **********************************************/
30114 /************** Continuing where we left off in os_common.h ******************/
30115
30116 static sqlite_uint64 g_start;
30117 static sqlite_uint64 g_elapsed;
30118 #define TIMER_START       g_start=sqlite3Hwtime()
30119 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
30120 #define TIMER_ELAPSED     g_elapsed
30121 #else
30122 #define TIMER_START
30123 #define TIMER_END
30124 #define TIMER_ELAPSED     ((sqlite_uint64)0)
30125 #endif
30126
30127 /*
30128 ** If we compile with the SQLITE_TEST macro set, then the following block
30129 ** of code will give us the ability to simulate a disk I/O error.  This
30130 ** is used for testing the I/O recovery logic.
30131 */
30132 #ifdef SQLITE_TEST
30133 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
30134 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
30135 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
30136 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
30137 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
30138 SQLITE_API int sqlite3_diskfull_pending = 0;
30139 SQLITE_API int sqlite3_diskfull = 0;
30140 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
30141 #define SimulateIOError(CODE)  \
30142   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
30143        || sqlite3_io_error_pending-- == 1 )  \
30144               { local_ioerr(); CODE; }
30145 static void local_ioerr(){
30146   IOTRACE(("IOERR\n"));
30147   sqlite3_io_error_hit++;
30148   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
30149 }
30150 #define SimulateDiskfullError(CODE) \
30151    if( sqlite3_diskfull_pending ){ \
30152      if( sqlite3_diskfull_pending == 1 ){ \
30153        local_ioerr(); \
30154        sqlite3_diskfull = 1; \
30155        sqlite3_io_error_hit = 1; \
30156        CODE; \
30157      }else{ \
30158        sqlite3_diskfull_pending--; \
30159      } \
30160    }
30161 #else
30162 #define SimulateIOErrorBenign(X)
30163 #define SimulateIOError(A)
30164 #define SimulateDiskfullError(A)
30165 #endif
30166
30167 /*
30168 ** When testing, keep a count of the number of open files.
30169 */
30170 #ifdef SQLITE_TEST
30171 SQLITE_API int sqlite3_open_file_count = 0;
30172 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
30173 #else
30174 #define OpenCounter(X)
30175 #endif
30176
30177 #endif /* !defined(_OS_COMMON_H_) */
30178
30179 /************** End of os_common.h *******************************************/
30180 /************** Continuing where we left off in os_win.c *********************/
30181
30182 /*
30183 ** Compiling and using WAL mode requires several APIs that are only
30184 ** available in Windows platforms based on the NT kernel.
30185 */
30186 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
30187 # error "WAL mode requires support from the Windows NT kernel, compile\
30188  with SQLITE_OMIT_WAL."
30189 #endif
30190
30191 /*
30192 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
30193 ** based on the sub-platform)?
30194 */
30195 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30196 #  define SQLITE_WIN32_HAS_ANSI
30197 #endif
30198
30199 /*
30200 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
30201 ** based on the sub-platform)?
30202 */
30203 #if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT
30204 #  define SQLITE_WIN32_HAS_WIDE
30205 #endif
30206
30207 /*
30208 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
30209 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
30210 ** are not present in the header file)?
30211 */
30212 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
30213 /*
30214 ** Two of the file mapping APIs are different under WinRT.  Figure out which
30215 ** set we need.
30216 */
30217 #if SQLITE_OS_WINRT
30218 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
30219         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
30220
30221 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
30222 #else
30223 #if defined(SQLITE_WIN32_HAS_ANSI)
30224 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
30225         DWORD, DWORD, DWORD, LPCSTR);
30226 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
30227
30228 #if defined(SQLITE_WIN32_HAS_WIDE)
30229 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
30230         DWORD, DWORD, DWORD, LPCWSTR);
30231 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
30232
30233 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
30234 #endif /* SQLITE_OS_WINRT */
30235
30236 /*
30237 ** This file mapping API is common to both Win32 and WinRT.
30238 */
30239 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
30240 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
30241
30242 /*
30243 ** Macro to find the minimum of two numeric values.
30244 */
30245 #ifndef MIN
30246 # define MIN(x,y) ((x)<(y)?(x):(y))
30247 #endif
30248
30249 /*
30250 ** Some Microsoft compilers lack this definition.
30251 */
30252 #ifndef INVALID_FILE_ATTRIBUTES
30253 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
30254 #endif
30255
30256 #ifndef FILE_FLAG_MASK
30257 # define FILE_FLAG_MASK          (0xFF3C0000)
30258 #endif
30259
30260 #ifndef FILE_ATTRIBUTE_MASK
30261 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
30262 #endif
30263
30264 #ifndef SQLITE_OMIT_WAL
30265 /* Forward references */
30266 typedef struct winShm winShm;           /* A connection to shared-memory */
30267 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
30268 #endif
30269
30270 /*
30271 ** WinCE lacks native support for file locking so we have to fake it
30272 ** with some code of our own.
30273 */
30274 #if SQLITE_OS_WINCE
30275 typedef struct winceLock {
30276   int nReaders;       /* Number of reader locks obtained */
30277   BOOL bPending;      /* Indicates a pending lock has been obtained */
30278   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
30279   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
30280 } winceLock;
30281 #endif
30282
30283 /*
30284 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
30285 ** portability layer.
30286 */
30287 typedef struct winFile winFile;
30288 struct winFile {
30289   const sqlite3_io_methods *pMethod; /*** Must be first ***/
30290   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
30291   HANDLE h;               /* Handle for accessing the file */
30292   u8 locktype;            /* Type of lock currently held on this file */
30293   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
30294   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
30295   DWORD lastErrno;        /* The Windows errno from the last I/O error */
30296 #ifndef SQLITE_OMIT_WAL
30297   winShm *pShm;           /* Instance of shared memory on this file */
30298 #endif
30299   const char *zPath;      /* Full pathname of this file */
30300   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
30301 #if SQLITE_OS_WINCE
30302   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
30303   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
30304   HANDLE hShared;         /* Shared memory segment used for locking */
30305   winceLock local;        /* Locks obtained by this instance of winFile */
30306   winceLock *shared;      /* Global shared lock memory for the file  */
30307 #endif
30308 };
30309
30310 /*
30311 ** Allowed values for winFile.ctrlFlags
30312 */
30313 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
30314 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
30315
30316 /*
30317  * The size of the buffer used by sqlite3_win32_write_debug().
30318  */
30319 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
30320 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
30321 #endif
30322
30323 /*
30324  * The value used with sqlite3_win32_set_directory() to specify that
30325  * the data directory should be changed.
30326  */
30327 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
30328 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
30329 #endif
30330
30331 /*
30332  * The value used with sqlite3_win32_set_directory() to specify that
30333  * the temporary directory should be changed.
30334  */
30335 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
30336 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
30337 #endif
30338
30339 /*
30340  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
30341  * various Win32 API heap functions instead of our own.
30342  */
30343 #ifdef SQLITE_WIN32_MALLOC
30344
30345 /*
30346  * If this is non-zero, an isolated heap will be created by the native Win32
30347  * allocator subsystem; otherwise, the default process heap will be used.  This
30348  * setting has no effect when compiling for WinRT.  By default, this is enabled
30349  * and an isolated heap will be created to store all allocated data.
30350  *
30351  ******************************************************************************
30352  * WARNING: It is important to note that when this setting is non-zero and the
30353  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
30354  *          function), all data that was allocated using the isolated heap will
30355  *          be freed immediately and any attempt to access any of that freed
30356  *          data will almost certainly result in an immediate access violation.
30357  ******************************************************************************
30358  */
30359 #ifndef SQLITE_WIN32_HEAP_CREATE
30360 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
30361 #endif
30362
30363 /*
30364  * The initial size of the Win32-specific heap.  This value may be zero.
30365  */
30366 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
30367 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
30368                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
30369 #endif
30370
30371 /*
30372  * The maximum size of the Win32-specific heap.  This value may be zero.
30373  */
30374 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
30375 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
30376 #endif
30377
30378 /*
30379  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
30380  * zero for the default behavior.
30381  */
30382 #ifndef SQLITE_WIN32_HEAP_FLAGS
30383 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
30384 #endif
30385
30386 /*
30387 ** The winMemData structure stores information required by the Win32-specific
30388 ** sqlite3_mem_methods implementation.
30389 */
30390 typedef struct winMemData winMemData;
30391 struct winMemData {
30392 #ifndef NDEBUG
30393   u32 magic;    /* Magic number to detect structure corruption. */
30394 #endif
30395   HANDLE hHeap; /* The handle to our heap. */
30396   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
30397 };
30398
30399 #ifndef NDEBUG
30400 #define WINMEM_MAGIC     0x42b2830b
30401 #endif
30402
30403 static struct winMemData win_mem_data = {
30404 #ifndef NDEBUG
30405   WINMEM_MAGIC,
30406 #endif
30407   NULL, FALSE
30408 };
30409
30410 #ifndef NDEBUG
30411 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
30412 #else
30413 #define winMemAssertMagic()
30414 #endif
30415
30416 #define winMemGetHeap() win_mem_data.hHeap
30417
30418 static void *winMemMalloc(int nBytes);
30419 static void winMemFree(void *pPrior);
30420 static void *winMemRealloc(void *pPrior, int nBytes);
30421 static int winMemSize(void *p);
30422 static int winMemRoundup(int n);
30423 static int winMemInit(void *pAppData);
30424 static void winMemShutdown(void *pAppData);
30425
30426 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
30427 #endif /* SQLITE_WIN32_MALLOC */
30428
30429 /*
30430 ** The following variable is (normally) set once and never changes
30431 ** thereafter.  It records whether the operating system is Win9x
30432 ** or WinNT.
30433 **
30434 ** 0:   Operating system unknown.
30435 ** 1:   Operating system is Win9x.
30436 ** 2:   Operating system is WinNT.
30437 **
30438 ** In order to facilitate testing on a WinNT system, the test fixture
30439 ** can manually set this value to 1 to emulate Win98 behavior.
30440 */
30441 #ifdef SQLITE_TEST
30442 SQLITE_API int sqlite3_os_type = 0;
30443 #else
30444 static int sqlite3_os_type = 0;
30445 #endif
30446
30447 #ifndef SYSCALL
30448 #  define SYSCALL sqlite3_syscall_ptr
30449 #endif
30450
30451 /*
30452 ** This function is not available on Windows CE or WinRT.
30453  */
30454
30455 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
30456 #  define osAreFileApisANSI()       1
30457 #endif
30458
30459 /*
30460 ** Many system calls are accessed through pointer-to-functions so that
30461 ** they may be overridden at runtime to facilitate fault injection during
30462 ** testing and sandboxing.  The following array holds the names and pointers
30463 ** to all overrideable system calls.
30464 */
30465 static struct win_syscall {
30466   const char *zName;            /* Name of the system call */
30467   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
30468   sqlite3_syscall_ptr pDefault; /* Default value */
30469 } aSyscall[] = {
30470 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30471   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
30472 #else
30473   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
30474 #endif
30475
30476 #ifndef osAreFileApisANSI
30477 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
30478 #endif
30479
30480 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
30481   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
30482 #else
30483   { "CharLowerW",              (SYSCALL)0,                       0 },
30484 #endif
30485
30486 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
30487
30488 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
30489   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
30490 #else
30491   { "CharUpperW",              (SYSCALL)0,                       0 },
30492 #endif
30493
30494 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
30495
30496   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
30497
30498 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
30499
30500 #if defined(SQLITE_WIN32_HAS_ANSI)
30501   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
30502 #else
30503   { "CreateFileA",             (SYSCALL)0,                       0 },
30504 #endif
30505
30506 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
30507         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
30508
30509 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30510   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
30511 #else
30512   { "CreateFileW",             (SYSCALL)0,                       0 },
30513 #endif
30514
30515 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
30516         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
30517
30518 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
30519         !defined(SQLITE_OMIT_WAL))
30520   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
30521 #else
30522   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
30523 #endif
30524
30525 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
30526         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
30527
30528 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
30529         !defined(SQLITE_OMIT_WAL))
30530   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
30531 #else
30532   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
30533 #endif
30534
30535 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
30536         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
30537
30538 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30539   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
30540 #else
30541   { "CreateMutexW",            (SYSCALL)0,                       0 },
30542 #endif
30543
30544 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
30545         LPCWSTR))aSyscall[8].pCurrent)
30546
30547 #if defined(SQLITE_WIN32_HAS_ANSI)
30548   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
30549 #else
30550   { "DeleteFileA",             (SYSCALL)0,                       0 },
30551 #endif
30552
30553 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
30554
30555 #if defined(SQLITE_WIN32_HAS_WIDE)
30556   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
30557 #else
30558   { "DeleteFileW",             (SYSCALL)0,                       0 },
30559 #endif
30560
30561 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
30562
30563 #if SQLITE_OS_WINCE
30564   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
30565 #else
30566   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
30567 #endif
30568
30569 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
30570         LPFILETIME))aSyscall[11].pCurrent)
30571
30572 #if SQLITE_OS_WINCE
30573   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
30574 #else
30575   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
30576 #endif
30577
30578 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
30579         LPSYSTEMTIME))aSyscall[12].pCurrent)
30580
30581   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
30582
30583 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
30584
30585 #if defined(SQLITE_WIN32_HAS_ANSI)
30586   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
30587 #else
30588   { "FormatMessageA",          (SYSCALL)0,                       0 },
30589 #endif
30590
30591 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
30592         DWORD,va_list*))aSyscall[14].pCurrent)
30593
30594 #if defined(SQLITE_WIN32_HAS_WIDE)
30595   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
30596 #else
30597   { "FormatMessageW",          (SYSCALL)0,                       0 },
30598 #endif
30599
30600 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
30601         DWORD,va_list*))aSyscall[15].pCurrent)
30602
30603 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
30604   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
30605 #else
30606   { "FreeLibrary",             (SYSCALL)0,                       0 },
30607 #endif
30608
30609 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
30610
30611   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
30612
30613 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
30614
30615 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
30616   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
30617 #else
30618   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
30619 #endif
30620
30621 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
30622         LPDWORD))aSyscall[18].pCurrent)
30623
30624 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30625   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
30626 #else
30627   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
30628 #endif
30629
30630 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
30631         LPDWORD))aSyscall[19].pCurrent)
30632
30633 #if defined(SQLITE_WIN32_HAS_ANSI)
30634   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
30635 #else
30636   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
30637 #endif
30638
30639 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
30640
30641 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30642   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
30643 #else
30644   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
30645 #endif
30646
30647 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
30648
30649 #if defined(SQLITE_WIN32_HAS_WIDE)
30650   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
30651 #else
30652   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
30653 #endif
30654
30655 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
30656         LPVOID))aSyscall[22].pCurrent)
30657
30658 #if !SQLITE_OS_WINRT
30659   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
30660 #else
30661   { "GetFileSize",             (SYSCALL)0,                       0 },
30662 #endif
30663
30664 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
30665
30666 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
30667   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
30668 #else
30669   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
30670 #endif
30671
30672 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
30673         LPSTR*))aSyscall[24].pCurrent)
30674
30675 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30676   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
30677 #else
30678   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
30679 #endif
30680
30681 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
30682         LPWSTR*))aSyscall[25].pCurrent)
30683
30684   { "GetLastError",            (SYSCALL)GetLastError,            0 },
30685
30686 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
30687
30688 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
30689 #if SQLITE_OS_WINCE
30690   /* The GetProcAddressA() routine is only available on Windows CE. */
30691   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
30692 #else
30693   /* All other Windows platforms expect GetProcAddress() to take
30694   ** an ANSI string regardless of the _UNICODE setting */
30695   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
30696 #endif
30697 #else
30698   { "GetProcAddressA",         (SYSCALL)0,                       0 },
30699 #endif
30700
30701 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
30702         LPCSTR))aSyscall[27].pCurrent)
30703
30704 #if !SQLITE_OS_WINRT
30705   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
30706 #else
30707   { "GetSystemInfo",           (SYSCALL)0,                       0 },
30708 #endif
30709
30710 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
30711
30712   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
30713
30714 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
30715
30716 #if !SQLITE_OS_WINCE
30717   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
30718 #else
30719   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
30720 #endif
30721
30722 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
30723         LPFILETIME))aSyscall[30].pCurrent)
30724
30725 #if defined(SQLITE_WIN32_HAS_ANSI)
30726   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
30727 #else
30728   { "GetTempPathA",            (SYSCALL)0,                       0 },
30729 #endif
30730
30731 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
30732
30733 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30734   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
30735 #else
30736   { "GetTempPathW",            (SYSCALL)0,                       0 },
30737 #endif
30738
30739 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
30740
30741 #if !SQLITE_OS_WINRT
30742   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
30743 #else
30744   { "GetTickCount",            (SYSCALL)0,                       0 },
30745 #endif
30746
30747 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
30748
30749 #if defined(SQLITE_WIN32_HAS_ANSI)
30750   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
30751 #else
30752   { "GetVersionExA",           (SYSCALL)0,                       0 },
30753 #endif
30754
30755 #define osGetVersionExA ((BOOL(WINAPI*)( \
30756         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
30757
30758   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
30759
30760 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
30761         SIZE_T))aSyscall[35].pCurrent)
30762
30763 #if !SQLITE_OS_WINRT
30764   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
30765 #else
30766   { "HeapCreate",              (SYSCALL)0,                       0 },
30767 #endif
30768
30769 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
30770         SIZE_T))aSyscall[36].pCurrent)
30771
30772 #if !SQLITE_OS_WINRT
30773   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
30774 #else
30775   { "HeapDestroy",             (SYSCALL)0,                       0 },
30776 #endif
30777
30778 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
30779
30780   { "HeapFree",                (SYSCALL)HeapFree,                0 },
30781
30782 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
30783
30784   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
30785
30786 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
30787         SIZE_T))aSyscall[39].pCurrent)
30788
30789   { "HeapSize",                (SYSCALL)HeapSize,                0 },
30790
30791 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
30792         LPCVOID))aSyscall[40].pCurrent)
30793
30794 #if !SQLITE_OS_WINRT
30795   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
30796 #else
30797   { "HeapValidate",            (SYSCALL)0,                       0 },
30798 #endif
30799
30800 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
30801         LPCVOID))aSyscall[41].pCurrent)
30802
30803 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
30804   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
30805 #else
30806   { "LoadLibraryA",            (SYSCALL)0,                       0 },
30807 #endif
30808
30809 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
30810
30811 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
30812         !defined(SQLITE_OMIT_LOAD_EXTENSION)
30813   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
30814 #else
30815   { "LoadLibraryW",            (SYSCALL)0,                       0 },
30816 #endif
30817
30818 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
30819
30820 #if !SQLITE_OS_WINRT
30821   { "LocalFree",               (SYSCALL)LocalFree,               0 },
30822 #else
30823   { "LocalFree",               (SYSCALL)0,                       0 },
30824 #endif
30825
30826 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
30827
30828 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30829   { "LockFile",                (SYSCALL)LockFile,                0 },
30830 #else
30831   { "LockFile",                (SYSCALL)0,                       0 },
30832 #endif
30833
30834 #ifndef osLockFile
30835 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30836         DWORD))aSyscall[45].pCurrent)
30837 #endif
30838
30839 #if !SQLITE_OS_WINCE
30840   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
30841 #else
30842   { "LockFileEx",              (SYSCALL)0,                       0 },
30843 #endif
30844
30845 #ifndef osLockFileEx
30846 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
30847         LPOVERLAPPED))aSyscall[46].pCurrent)
30848 #endif
30849
30850 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
30851   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
30852 #else
30853   { "MapViewOfFile",           (SYSCALL)0,                       0 },
30854 #endif
30855
30856 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30857         SIZE_T))aSyscall[47].pCurrent)
30858
30859   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
30860
30861 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
30862         int))aSyscall[48].pCurrent)
30863
30864   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
30865
30866 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
30867         LARGE_INTEGER*))aSyscall[49].pCurrent)
30868
30869   { "ReadFile",                (SYSCALL)ReadFile,                0 },
30870
30871 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
30872         LPOVERLAPPED))aSyscall[50].pCurrent)
30873
30874   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
30875
30876 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
30877
30878 #if !SQLITE_OS_WINRT
30879   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
30880 #else
30881   { "SetFilePointer",          (SYSCALL)0,                       0 },
30882 #endif
30883
30884 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
30885         DWORD))aSyscall[52].pCurrent)
30886
30887 #if !SQLITE_OS_WINRT
30888   { "Sleep",                   (SYSCALL)Sleep,                   0 },
30889 #else
30890   { "Sleep",                   (SYSCALL)0,                       0 },
30891 #endif
30892
30893 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
30894
30895   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
30896
30897 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
30898         LPFILETIME))aSyscall[54].pCurrent)
30899
30900 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30901   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
30902 #else
30903   { "UnlockFile",              (SYSCALL)0,                       0 },
30904 #endif
30905
30906 #ifndef osUnlockFile
30907 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30908         DWORD))aSyscall[55].pCurrent)
30909 #endif
30910
30911 #if !SQLITE_OS_WINCE
30912   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
30913 #else
30914   { "UnlockFileEx",            (SYSCALL)0,                       0 },
30915 #endif
30916
30917 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30918         LPOVERLAPPED))aSyscall[56].pCurrent)
30919
30920 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
30921   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
30922 #else
30923   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
30924 #endif
30925
30926 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
30927
30928   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
30929
30930 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
30931         LPCSTR,LPBOOL))aSyscall[58].pCurrent)
30932
30933   { "WriteFile",               (SYSCALL)WriteFile,               0 },
30934
30935 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
30936         LPOVERLAPPED))aSyscall[59].pCurrent)
30937
30938 #if SQLITE_OS_WINRT
30939   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
30940 #else
30941   { "CreateEventExW",          (SYSCALL)0,                       0 },
30942 #endif
30943
30944 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
30945         DWORD,DWORD))aSyscall[60].pCurrent)
30946
30947 #if !SQLITE_OS_WINRT
30948   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
30949 #else
30950   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
30951 #endif
30952
30953 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
30954         DWORD))aSyscall[61].pCurrent)
30955
30956 #if SQLITE_OS_WINRT
30957   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
30958 #else
30959   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
30960 #endif
30961
30962 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
30963         BOOL))aSyscall[62].pCurrent)
30964
30965 #if SQLITE_OS_WINRT
30966   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
30967 #else
30968   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
30969 #endif
30970
30971 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
30972         PLARGE_INTEGER,DWORD))aSyscall[63].pCurrent)
30973
30974 #if SQLITE_OS_WINRT
30975   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
30976 #else
30977   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
30978 #endif
30979
30980 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
30981         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[64].pCurrent)
30982
30983 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
30984   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
30985 #else
30986   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
30987 #endif
30988
30989 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
30990         SIZE_T))aSyscall[65].pCurrent)
30991
30992 #if SQLITE_OS_WINRT
30993   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
30994 #else
30995   { "CreateFile2",             (SYSCALL)0,                       0 },
30996 #endif
30997
30998 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
30999         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[66].pCurrent)
31000
31001 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
31002   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
31003 #else
31004   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
31005 #endif
31006
31007 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
31008         DWORD))aSyscall[67].pCurrent)
31009
31010 #if SQLITE_OS_WINRT
31011   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
31012 #else
31013   { "GetTickCount64",          (SYSCALL)0,                       0 },
31014 #endif
31015
31016 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[68].pCurrent)
31017
31018 #if SQLITE_OS_WINRT
31019   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
31020 #else
31021   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
31022 #endif
31023
31024 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
31025         LPSYSTEM_INFO))aSyscall[69].pCurrent)
31026
31027 #if defined(SQLITE_WIN32_HAS_ANSI)
31028   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
31029 #else
31030   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
31031 #endif
31032
31033 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[70].pCurrent)
31034
31035 #if defined(SQLITE_WIN32_HAS_WIDE)
31036   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
31037 #else
31038   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
31039 #endif
31040
31041 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[71].pCurrent)
31042
31043   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
31044
31045 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[72].pCurrent)
31046
31047 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
31048   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
31049 #else
31050   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
31051 #endif
31052
31053 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
31054         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[73].pCurrent)
31055
31056 }; /* End of the overrideable system calls */
31057
31058 /*
31059 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
31060 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
31061 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
31062 ** system call named zName.
31063 */
31064 static int winSetSystemCall(
31065   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
31066   const char *zName,            /* Name of system call to override */
31067   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
31068 ){
31069   unsigned int i;
31070   int rc = SQLITE_NOTFOUND;
31071
31072   UNUSED_PARAMETER(pNotUsed);
31073   if( zName==0 ){
31074     /* If no zName is given, restore all system calls to their default
31075     ** settings and return NULL
31076     */
31077     rc = SQLITE_OK;
31078     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31079       if( aSyscall[i].pDefault ){
31080         aSyscall[i].pCurrent = aSyscall[i].pDefault;
31081       }
31082     }
31083   }else{
31084     /* If zName is specified, operate on only the one system call
31085     ** specified.
31086     */
31087     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31088       if( strcmp(zName, aSyscall[i].zName)==0 ){
31089         if( aSyscall[i].pDefault==0 ){
31090           aSyscall[i].pDefault = aSyscall[i].pCurrent;
31091         }
31092         rc = SQLITE_OK;
31093         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
31094         aSyscall[i].pCurrent = pNewFunc;
31095         break;
31096       }
31097     }
31098   }
31099   return rc;
31100 }
31101
31102 /*
31103 ** Return the value of a system call.  Return NULL if zName is not a
31104 ** recognized system call name.  NULL is also returned if the system call
31105 ** is currently undefined.
31106 */
31107 static sqlite3_syscall_ptr winGetSystemCall(
31108   sqlite3_vfs *pNotUsed,
31109   const char *zName
31110 ){
31111   unsigned int i;
31112
31113   UNUSED_PARAMETER(pNotUsed);
31114   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31115     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
31116   }
31117   return 0;
31118 }
31119
31120 /*
31121 ** Return the name of the first system call after zName.  If zName==NULL
31122 ** then return the name of the first system call.  Return NULL if zName
31123 ** is the last system call or if zName is not the name of a valid
31124 ** system call.
31125 */
31126 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
31127   int i = -1;
31128
31129   UNUSED_PARAMETER(p);
31130   if( zName ){
31131     for(i=0; i<ArraySize(aSyscall)-1; i++){
31132       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
31133     }
31134   }
31135   for(i++; i<ArraySize(aSyscall); i++){
31136     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
31137   }
31138   return 0;
31139 }
31140
31141 /*
31142 ** This function outputs the specified (ANSI) string to the Win32 debugger
31143 ** (if available).
31144 */
31145
31146 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
31147   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
31148   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
31149   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
31150   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
31151 #if defined(SQLITE_WIN32_HAS_ANSI)
31152   if( nMin>0 ){
31153     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31154     memcpy(zDbgBuf, zBuf, nMin);
31155     osOutputDebugStringA(zDbgBuf);
31156   }else{
31157     osOutputDebugStringA(zBuf);
31158   }
31159 #elif defined(SQLITE_WIN32_HAS_WIDE)
31160   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31161   if ( osMultiByteToWideChar(
31162           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
31163           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
31164     return;
31165   }
31166   osOutputDebugStringW((LPCWSTR)zDbgBuf);
31167 #else
31168   if( nMin>0 ){
31169     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31170     memcpy(zDbgBuf, zBuf, nMin);
31171     fprintf(stderr, "%s", zDbgBuf);
31172   }else{
31173     fprintf(stderr, "%s", zBuf);
31174   }
31175 #endif
31176 }
31177
31178 /*
31179 ** The following routine suspends the current thread for at least ms
31180 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
31181 */
31182 #if SQLITE_OS_WINRT
31183 static HANDLE sleepObj = NULL;
31184 #endif
31185
31186 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
31187 #if SQLITE_OS_WINRT
31188   if ( sleepObj==NULL ){
31189     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
31190                                 SYNCHRONIZE);
31191   }
31192   assert( sleepObj!=NULL );
31193   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
31194 #else
31195   osSleep(milliseconds);
31196 #endif
31197 }
31198
31199 /*
31200 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31201 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
31202 **
31203 ** Here is an interesting observation:  Win95, Win98, and WinME lack
31204 ** the LockFileEx() API.  But we can still statically link against that
31205 ** API as long as we don't call it when running Win95/98/ME.  A call to
31206 ** this routine is used to determine if the host is Win95/98/ME or
31207 ** WinNT/2K/XP so that we will know whether or not we can safely call
31208 ** the LockFileEx() API.
31209 */
31210 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
31211 # define isNT()  (1)
31212 #elif !defined(SQLITE_WIN32_HAS_WIDE)
31213 # define isNT()  (0)
31214 #else
31215   static int isNT(void){
31216     if( sqlite3_os_type==0 ){
31217       OSVERSIONINFOA sInfo;
31218       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31219       osGetVersionExA(&sInfo);
31220       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31221     }
31222     return sqlite3_os_type==2;
31223   }
31224 #endif
31225
31226 #ifdef SQLITE_WIN32_MALLOC
31227 /*
31228 ** Allocate nBytes of memory.
31229 */
31230 static void *winMemMalloc(int nBytes){
31231   HANDLE hHeap;
31232   void *p;
31233
31234   winMemAssertMagic();
31235   hHeap = winMemGetHeap();
31236   assert( hHeap!=0 );
31237   assert( hHeap!=INVALID_HANDLE_VALUE );
31238 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31239   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31240 #endif
31241   assert( nBytes>=0 );
31242   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31243   if( !p ){
31244     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
31245                 nBytes, osGetLastError(), (void*)hHeap);
31246   }
31247   return p;
31248 }
31249
31250 /*
31251 ** Free memory.
31252 */
31253 static void winMemFree(void *pPrior){
31254   HANDLE hHeap;
31255
31256   winMemAssertMagic();
31257   hHeap = winMemGetHeap();
31258   assert( hHeap!=0 );
31259   assert( hHeap!=INVALID_HANDLE_VALUE );
31260 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31261   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31262 #endif
31263   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
31264   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
31265     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
31266                 pPrior, osGetLastError(), (void*)hHeap);
31267   }
31268 }
31269
31270 /*
31271 ** Change the size of an existing memory allocation
31272 */
31273 static void *winMemRealloc(void *pPrior, int nBytes){
31274   HANDLE hHeap;
31275   void *p;
31276
31277   winMemAssertMagic();
31278   hHeap = winMemGetHeap();
31279   assert( hHeap!=0 );
31280   assert( hHeap!=INVALID_HANDLE_VALUE );
31281 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31282   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31283 #endif
31284   assert( nBytes>=0 );
31285   if( !pPrior ){
31286     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31287   }else{
31288     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
31289   }
31290   if( !p ){
31291     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
31292                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
31293                 (void*)hHeap);
31294   }
31295   return p;
31296 }
31297
31298 /*
31299 ** Return the size of an outstanding allocation, in bytes.
31300 */
31301 static int winMemSize(void *p){
31302   HANDLE hHeap;
31303   SIZE_T n;
31304
31305   winMemAssertMagic();
31306   hHeap = winMemGetHeap();
31307   assert( hHeap!=0 );
31308   assert( hHeap!=INVALID_HANDLE_VALUE );
31309 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31310   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31311 #endif
31312   if( !p ) return 0;
31313   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
31314   if( n==(SIZE_T)-1 ){
31315     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
31316                 p, osGetLastError(), (void*)hHeap);
31317     return 0;
31318   }
31319   return (int)n;
31320 }
31321
31322 /*
31323 ** Round up a request size to the next valid allocation size.
31324 */
31325 static int winMemRoundup(int n){
31326   return n;
31327 }
31328
31329 /*
31330 ** Initialize this module.
31331 */
31332 static int winMemInit(void *pAppData){
31333   winMemData *pWinMemData = (winMemData *)pAppData;
31334
31335   if( !pWinMemData ) return SQLITE_ERROR;
31336   assert( pWinMemData->magic==WINMEM_MAGIC );
31337
31338 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
31339   if( !pWinMemData->hHeap ){
31340     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
31341                                       SQLITE_WIN32_HEAP_INIT_SIZE,
31342                                       SQLITE_WIN32_HEAP_MAX_SIZE);
31343     if( !pWinMemData->hHeap ){
31344       sqlite3_log(SQLITE_NOMEM,
31345           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
31346           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
31347           SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
31348       return SQLITE_NOMEM;
31349     }
31350     pWinMemData->bOwned = TRUE;
31351     assert( pWinMemData->bOwned );
31352   }
31353 #else
31354   pWinMemData->hHeap = osGetProcessHeap();
31355   if( !pWinMemData->hHeap ){
31356     sqlite3_log(SQLITE_NOMEM,
31357         "failed to GetProcessHeap (%d)", osGetLastError());
31358     return SQLITE_NOMEM;
31359   }
31360   pWinMemData->bOwned = FALSE;
31361   assert( !pWinMemData->bOwned );
31362 #endif
31363   assert( pWinMemData->hHeap!=0 );
31364   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31365 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31366   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31367 #endif
31368   return SQLITE_OK;
31369 }
31370
31371 /*
31372 ** Deinitialize this module.
31373 */
31374 static void winMemShutdown(void *pAppData){
31375   winMemData *pWinMemData = (winMemData *)pAppData;
31376
31377   if( !pWinMemData ) return;
31378   if( pWinMemData->hHeap ){
31379     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31380 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31381     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31382 #endif
31383     if( pWinMemData->bOwned ){
31384       if( !osHeapDestroy(pWinMemData->hHeap) ){
31385         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
31386                     osGetLastError(), (void*)pWinMemData->hHeap);
31387       }
31388       pWinMemData->bOwned = FALSE;
31389     }
31390     pWinMemData->hHeap = NULL;
31391   }
31392 }
31393
31394 /*
31395 ** Populate the low-level memory allocation function pointers in
31396 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
31397 ** arguments specify the block of memory to manage.
31398 **
31399 ** This routine is only called by sqlite3_config(), and therefore
31400 ** is not required to be threadsafe (it is not).
31401 */
31402 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
31403   static const sqlite3_mem_methods winMemMethods = {
31404     winMemMalloc,
31405     winMemFree,
31406     winMemRealloc,
31407     winMemSize,
31408     winMemRoundup,
31409     winMemInit,
31410     winMemShutdown,
31411     &win_mem_data
31412   };
31413   return &winMemMethods;
31414 }
31415
31416 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
31417   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
31418 }
31419 #endif /* SQLITE_WIN32_MALLOC */
31420
31421 /*
31422 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?). 
31423 **
31424 ** Space to hold the returned string is obtained from malloc.
31425 */
31426 static LPWSTR utf8ToUnicode(const char *zFilename){
31427   int nChar;
31428   LPWSTR zWideFilename;
31429
31430   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
31431   if( nChar==0 ){
31432     return 0;
31433   }
31434   zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
31435   if( zWideFilename==0 ){
31436     return 0;
31437   }
31438   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
31439                                 nChar);
31440   if( nChar==0 ){
31441     sqlite3_free(zWideFilename);
31442     zWideFilename = 0;
31443   }
31444   return zWideFilename;
31445 }
31446
31447 /*
31448 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
31449 ** obtained from sqlite3_malloc().
31450 */
31451 static char *unicodeToUtf8(LPCWSTR zWideFilename){
31452   int nByte;
31453   char *zFilename;
31454
31455   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
31456   if( nByte == 0 ){
31457     return 0;
31458   }
31459   zFilename = sqlite3MallocZero( nByte );
31460   if( zFilename==0 ){
31461     return 0;
31462   }
31463   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
31464                                 0, 0);
31465   if( nByte == 0 ){
31466     sqlite3_free(zFilename);
31467     zFilename = 0;
31468   }
31469   return zFilename;
31470 }
31471
31472 /*
31473 ** Convert an ANSI string to Microsoft Unicode, based on the
31474 ** current codepage settings for file apis.
31475 ** 
31476 ** Space to hold the returned string is obtained
31477 ** from sqlite3_malloc.
31478 */
31479 static LPWSTR mbcsToUnicode(const char *zFilename){
31480   int nByte;
31481   LPWSTR zMbcsFilename;
31482   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
31483
31484   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
31485                                 0)*sizeof(WCHAR);
31486   if( nByte==0 ){
31487     return 0;
31488   }
31489   zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
31490   if( zMbcsFilename==0 ){
31491     return 0;
31492   }
31493   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
31494                                 nByte);
31495   if( nByte==0 ){
31496     sqlite3_free(zMbcsFilename);
31497     zMbcsFilename = 0;
31498   }
31499   return zMbcsFilename;
31500 }
31501
31502 /*
31503 ** Convert Microsoft Unicode to multi-byte character string, based on the
31504 ** user's ANSI codepage.
31505 **
31506 ** Space to hold the returned string is obtained from
31507 ** sqlite3_malloc().
31508 */
31509 static char *unicodeToMbcs(LPCWSTR zWideFilename){
31510   int nByte;
31511   char *zFilename;
31512   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
31513
31514   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
31515   if( nByte == 0 ){
31516     return 0;
31517   }
31518   zFilename = sqlite3MallocZero( nByte );
31519   if( zFilename==0 ){
31520     return 0;
31521   }
31522   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
31523                                 nByte, 0, 0);
31524   if( nByte == 0 ){
31525     sqlite3_free(zFilename);
31526     zFilename = 0;
31527   }
31528   return zFilename;
31529 }
31530
31531 /*
31532 ** Convert multibyte character string to UTF-8.  Space to hold the
31533 ** returned string is obtained from sqlite3_malloc().
31534 */
31535 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
31536   char *zFilenameUtf8;
31537   LPWSTR zTmpWide;
31538
31539   zTmpWide = mbcsToUnicode(zFilename);
31540   if( zTmpWide==0 ){
31541     return 0;
31542   }
31543   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
31544   sqlite3_free(zTmpWide);
31545   return zFilenameUtf8;
31546 }
31547
31548 /*
31549 ** Convert UTF-8 to multibyte character string.  Space to hold the 
31550 ** returned string is obtained from sqlite3_malloc().
31551 */
31552 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
31553   char *zFilenameMbcs;
31554   LPWSTR zTmpWide;
31555
31556   zTmpWide = utf8ToUnicode(zFilename);
31557   if( zTmpWide==0 ){
31558     return 0;
31559   }
31560   zFilenameMbcs = unicodeToMbcs(zTmpWide);
31561   sqlite3_free(zTmpWide);
31562   return zFilenameMbcs;
31563 }
31564
31565 /*
31566 ** This function sets the data directory or the temporary directory based on
31567 ** the provided arguments.  The type argument must be 1 in order to set the
31568 ** data directory or 2 in order to set the temporary directory.  The zValue
31569 ** argument is the name of the directory to use.  The return value will be
31570 ** SQLITE_OK if successful.
31571 */
31572 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
31573   char **ppDirectory = 0;
31574 #ifndef SQLITE_OMIT_AUTOINIT
31575   int rc = sqlite3_initialize();
31576   if( rc ) return rc;
31577 #endif
31578   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
31579     ppDirectory = &sqlite3_data_directory;
31580   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
31581     ppDirectory = &sqlite3_temp_directory;
31582   }
31583   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
31584           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
31585   );
31586   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
31587   if( ppDirectory ){
31588     char *zValueUtf8 = 0;
31589     if( zValue && zValue[0] ){
31590       zValueUtf8 = unicodeToUtf8(zValue);
31591       if ( zValueUtf8==0 ){
31592         return SQLITE_NOMEM;
31593       }
31594     }
31595     sqlite3_free(*ppDirectory);
31596     *ppDirectory = zValueUtf8;
31597     return SQLITE_OK;
31598   }
31599   return SQLITE_ERROR;
31600 }
31601
31602 /*
31603 ** The return value of getLastErrorMsg
31604 ** is zero if the error message fits in the buffer, or non-zero
31605 ** otherwise (if the message was truncated).
31606 */
31607 static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
31608   /* FormatMessage returns 0 on failure.  Otherwise it
31609   ** returns the number of TCHARs written to the output
31610   ** buffer, excluding the terminating null char.
31611   */
31612   DWORD dwLen = 0;
31613   char *zOut = 0;
31614
31615   if( isNT() ){
31616 #if SQLITE_OS_WINRT
31617     WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */
31618     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
31619                              FORMAT_MESSAGE_IGNORE_INSERTS,
31620                              NULL,
31621                              lastErrno,
31622                              0,
31623                              zTempWide,
31624                              MAX_PATH,
31625                              0);
31626 #else
31627     LPWSTR zTempWide = NULL;
31628     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
31629                              FORMAT_MESSAGE_FROM_SYSTEM |
31630                              FORMAT_MESSAGE_IGNORE_INSERTS,
31631                              NULL,
31632                              lastErrno,
31633                              0,
31634                              (LPWSTR) &zTempWide,
31635                              0,
31636                              0);
31637 #endif
31638     if( dwLen > 0 ){
31639       /* allocate a buffer and convert to UTF8 */
31640       sqlite3BeginBenignMalloc();
31641       zOut = unicodeToUtf8(zTempWide);
31642       sqlite3EndBenignMalloc();
31643 #if !SQLITE_OS_WINRT
31644       /* free the system buffer allocated by FormatMessage */
31645       osLocalFree(zTempWide);
31646 #endif
31647     }
31648   }
31649 #ifdef SQLITE_WIN32_HAS_ANSI
31650   else{
31651     char *zTemp = NULL;
31652     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
31653                              FORMAT_MESSAGE_FROM_SYSTEM |
31654                              FORMAT_MESSAGE_IGNORE_INSERTS,
31655                              NULL,
31656                              lastErrno,
31657                              0,
31658                              (LPSTR) &zTemp,
31659                              0,
31660                              0);
31661     if( dwLen > 0 ){
31662       /* allocate a buffer and convert to UTF8 */
31663       sqlite3BeginBenignMalloc();
31664       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31665       sqlite3EndBenignMalloc();
31666       /* free the system buffer allocated by FormatMessage */
31667       osLocalFree(zTemp);
31668     }
31669   }
31670 #endif
31671   if( 0 == dwLen ){
31672     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
31673   }else{
31674     /* copy a maximum of nBuf chars to output buffer */
31675     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
31676     /* free the UTF8 buffer */
31677     sqlite3_free(zOut);
31678   }
31679   return 0;
31680 }
31681
31682 /*
31683 **
31684 ** This function - winLogErrorAtLine() - is only ever called via the macro
31685 ** winLogError().
31686 **
31687 ** This routine is invoked after an error occurs in an OS function.
31688 ** It logs a message using sqlite3_log() containing the current value of
31689 ** error code and, if possible, the human-readable equivalent from 
31690 ** FormatMessage.
31691 **
31692 ** The first argument passed to the macro should be the error code that
31693 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
31694 ** The two subsequent arguments should be the name of the OS function that
31695 ** failed and the associated file-system path, if any.
31696 */
31697 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
31698 static int winLogErrorAtLine(
31699   int errcode,                    /* SQLite error code */
31700   DWORD lastErrno,                /* Win32 last error */
31701   const char *zFunc,              /* Name of OS function that failed */
31702   const char *zPath,              /* File path associated with error */
31703   int iLine                       /* Source line number where error occurred */
31704 ){
31705   char zMsg[500];                 /* Human readable error text */
31706   int i;                          /* Loop counter */
31707
31708   zMsg[0] = 0;
31709   getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
31710   assert( errcode!=SQLITE_OK );
31711   if( zPath==0 ) zPath = "";
31712   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
31713   zMsg[i] = 0;
31714   sqlite3_log(errcode,
31715       "os_win.c:%d: (%d) %s(%s) - %s",
31716       iLine, lastErrno, zFunc, zPath, zMsg
31717   );
31718
31719   return errcode;
31720 }
31721
31722 /*
31723 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
31724 ** will be retried following a locking error - probably caused by 
31725 ** antivirus software.  Also the initial delay before the first retry.
31726 ** The delay increases linearly with each retry.
31727 */
31728 #ifndef SQLITE_WIN32_IOERR_RETRY
31729 # define SQLITE_WIN32_IOERR_RETRY 10
31730 #endif
31731 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
31732 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
31733 #endif
31734 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
31735 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
31736
31737 /*
31738 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
31739 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
31740 ** to give up with an error.
31741 */
31742 static int retryIoerr(int *pnRetry, DWORD *pError){
31743   DWORD e = osGetLastError();
31744   if( *pnRetry>=win32IoerrRetry ){
31745     if( pError ){
31746       *pError = e;
31747     }
31748     return 0;
31749   }
31750   if( e==ERROR_ACCESS_DENIED ||
31751       e==ERROR_LOCK_VIOLATION ||
31752       e==ERROR_SHARING_VIOLATION ){
31753     sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));
31754     ++*pnRetry;
31755     return 1;
31756   }
31757   if( pError ){
31758     *pError = e;
31759   }
31760   return 0;
31761 }
31762
31763 /*
31764 ** Log a I/O error retry episode.
31765 */
31766 static void logIoerr(int nRetry){
31767   if( nRetry ){
31768     sqlite3_log(SQLITE_IOERR, 
31769       "delayed %dms for lock/sharing conflict",
31770       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
31771     );
31772   }
31773 }
31774
31775 #if SQLITE_OS_WINCE
31776 /*************************************************************************
31777 ** This section contains code for WinCE only.
31778 */
31779 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
31780 /*
31781 ** The MSVC CRT on Windows CE may not have a localtime() function.  So
31782 ** create a substitute.
31783 */
31784 /* #include <time.h> */
31785 struct tm *__cdecl localtime(const time_t *t)
31786 {
31787   static struct tm y;
31788   FILETIME uTm, lTm;
31789   SYSTEMTIME pTm;
31790   sqlite3_int64 t64;
31791   t64 = *t;
31792   t64 = (t64 + 11644473600)*10000000;
31793   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
31794   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
31795   osFileTimeToLocalFileTime(&uTm,&lTm);
31796   osFileTimeToSystemTime(&lTm,&pTm);
31797   y.tm_year = pTm.wYear - 1900;
31798   y.tm_mon = pTm.wMonth - 1;
31799   y.tm_wday = pTm.wDayOfWeek;
31800   y.tm_mday = pTm.wDay;
31801   y.tm_hour = pTm.wHour;
31802   y.tm_min = pTm.wMinute;
31803   y.tm_sec = pTm.wSecond;
31804   return &y;
31805 }
31806 #endif
31807
31808 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
31809
31810 /*
31811 ** Acquire a lock on the handle h
31812 */
31813 static void winceMutexAcquire(HANDLE h){
31814    DWORD dwErr;
31815    do {
31816      dwErr = osWaitForSingleObject(h, INFINITE);
31817    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
31818 }
31819 /*
31820 ** Release a lock acquired by winceMutexAcquire()
31821 */
31822 #define winceMutexRelease(h) ReleaseMutex(h)
31823
31824 /*
31825 ** Create the mutex and shared memory used for locking in the file
31826 ** descriptor pFile
31827 */
31828 static int winceCreateLock(const char *zFilename, winFile *pFile){
31829   LPWSTR zTok;
31830   LPWSTR zName;
31831   DWORD lastErrno;
31832   BOOL bLogged = FALSE;
31833   BOOL bInit = TRUE;
31834
31835   zName = utf8ToUnicode(zFilename);
31836   if( zName==0 ){
31837     /* out of memory */
31838     return SQLITE_IOERR_NOMEM;
31839   }
31840
31841   /* Initialize the local lockdata */
31842   memset(&pFile->local, 0, sizeof(pFile->local));
31843
31844   /* Replace the backslashes from the filename and lowercase it
31845   ** to derive a mutex name. */
31846   zTok = osCharLowerW(zName);
31847   for (;*zTok;zTok++){
31848     if (*zTok == '\\') *zTok = '_';
31849   }
31850
31851   /* Create/open the named mutex */
31852   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
31853   if (!pFile->hMutex){
31854     pFile->lastErrno = osGetLastError();
31855     winLogError(SQLITE_IOERR, pFile->lastErrno,
31856                 "winceCreateLock1", zFilename);
31857     sqlite3_free(zName);
31858     return SQLITE_IOERR;
31859   }
31860
31861   /* Acquire the mutex before continuing */
31862   winceMutexAcquire(pFile->hMutex);
31863   
31864   /* Since the names of named mutexes, semaphores, file mappings etc are 
31865   ** case-sensitive, take advantage of that by uppercasing the mutex name
31866   ** and using that as the shared filemapping name.
31867   */
31868   osCharUpperW(zName);
31869   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
31870                                         PAGE_READWRITE, 0, sizeof(winceLock),
31871                                         zName);  
31872
31873   /* Set a flag that indicates we're the first to create the memory so it 
31874   ** must be zero-initialized */
31875   lastErrno = osGetLastError();
31876   if (lastErrno == ERROR_ALREADY_EXISTS){
31877     bInit = FALSE;
31878   }
31879
31880   sqlite3_free(zName);
31881
31882   /* If we succeeded in making the shared memory handle, map it. */
31883   if( pFile->hShared ){
31884     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, 
31885              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
31886     /* If mapping failed, close the shared memory handle and erase it */
31887     if( !pFile->shared ){
31888       pFile->lastErrno = osGetLastError();
31889       winLogError(SQLITE_IOERR, pFile->lastErrno,
31890                   "winceCreateLock2", zFilename);
31891       bLogged = TRUE;
31892       osCloseHandle(pFile->hShared);
31893       pFile->hShared = NULL;
31894     }
31895   }
31896
31897   /* If shared memory could not be created, then close the mutex and fail */
31898   if( pFile->hShared==NULL ){
31899     if( !bLogged ){
31900       pFile->lastErrno = lastErrno;
31901       winLogError(SQLITE_IOERR, pFile->lastErrno,
31902                   "winceCreateLock3", zFilename);
31903       bLogged = TRUE;
31904     }
31905     winceMutexRelease(pFile->hMutex);
31906     osCloseHandle(pFile->hMutex);
31907     pFile->hMutex = NULL;
31908     return SQLITE_IOERR;
31909   }
31910   
31911   /* Initialize the shared memory if we're supposed to */
31912   if( bInit ){
31913     memset(pFile->shared, 0, sizeof(winceLock));
31914   }
31915
31916   winceMutexRelease(pFile->hMutex);
31917   return SQLITE_OK;
31918 }
31919
31920 /*
31921 ** Destroy the part of winFile that deals with wince locks
31922 */
31923 static void winceDestroyLock(winFile *pFile){
31924   if (pFile->hMutex){
31925     /* Acquire the mutex */
31926     winceMutexAcquire(pFile->hMutex);
31927
31928     /* The following blocks should probably assert in debug mode, but they
31929        are to cleanup in case any locks remained open */
31930     if (pFile->local.nReaders){
31931       pFile->shared->nReaders --;
31932     }
31933     if (pFile->local.bReserved){
31934       pFile->shared->bReserved = FALSE;
31935     }
31936     if (pFile->local.bPending){
31937       pFile->shared->bPending = FALSE;
31938     }
31939     if (pFile->local.bExclusive){
31940       pFile->shared->bExclusive = FALSE;
31941     }
31942
31943     /* De-reference and close our copy of the shared memory handle */
31944     osUnmapViewOfFile(pFile->shared);
31945     osCloseHandle(pFile->hShared);
31946
31947     /* Done with the mutex */
31948     winceMutexRelease(pFile->hMutex);    
31949     osCloseHandle(pFile->hMutex);
31950     pFile->hMutex = NULL;
31951   }
31952 }
31953
31954 /* 
31955 ** An implementation of the LockFile() API of Windows for CE
31956 */
31957 static BOOL winceLockFile(
31958   LPHANDLE phFile,
31959   DWORD dwFileOffsetLow,
31960   DWORD dwFileOffsetHigh,
31961   DWORD nNumberOfBytesToLockLow,
31962   DWORD nNumberOfBytesToLockHigh
31963 ){
31964   winFile *pFile = HANDLE_TO_WINFILE(phFile);
31965   BOOL bReturn = FALSE;
31966
31967   UNUSED_PARAMETER(dwFileOffsetHigh);
31968   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31969
31970   if (!pFile->hMutex) return TRUE;
31971   winceMutexAcquire(pFile->hMutex);
31972
31973   /* Wanting an exclusive lock? */
31974   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
31975        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31976     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
31977        pFile->shared->bExclusive = TRUE;
31978        pFile->local.bExclusive = TRUE;
31979        bReturn = TRUE;
31980     }
31981   }
31982
31983   /* Want a read-only lock? */
31984   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
31985            nNumberOfBytesToLockLow == 1){
31986     if (pFile->shared->bExclusive == 0){
31987       pFile->local.nReaders ++;
31988       if (pFile->local.nReaders == 1){
31989         pFile->shared->nReaders ++;
31990       }
31991       bReturn = TRUE;
31992     }
31993   }
31994
31995   /* Want a pending lock? */
31996   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
31997            && nNumberOfBytesToLockLow == 1){
31998     /* If no pending lock has been acquired, then acquire it */
31999     if (pFile->shared->bPending == 0) {
32000       pFile->shared->bPending = TRUE;
32001       pFile->local.bPending = TRUE;
32002       bReturn = TRUE;
32003     }
32004   }
32005
32006   /* Want a reserved lock? */
32007   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
32008            && nNumberOfBytesToLockLow == 1){
32009     if (pFile->shared->bReserved == 0) {
32010       pFile->shared->bReserved = TRUE;
32011       pFile->local.bReserved = TRUE;
32012       bReturn = TRUE;
32013     }
32014   }
32015
32016   winceMutexRelease(pFile->hMutex);
32017   return bReturn;
32018 }
32019
32020 /*
32021 ** An implementation of the UnlockFile API of Windows for CE
32022 */
32023 static BOOL winceUnlockFile(
32024   LPHANDLE phFile,
32025   DWORD dwFileOffsetLow,
32026   DWORD dwFileOffsetHigh,
32027   DWORD nNumberOfBytesToUnlockLow,
32028   DWORD nNumberOfBytesToUnlockHigh
32029 ){
32030   winFile *pFile = HANDLE_TO_WINFILE(phFile);
32031   BOOL bReturn = FALSE;
32032
32033   UNUSED_PARAMETER(dwFileOffsetHigh);
32034   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
32035
32036   if (!pFile->hMutex) return TRUE;
32037   winceMutexAcquire(pFile->hMutex);
32038
32039   /* Releasing a reader lock or an exclusive lock */
32040   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
32041     /* Did we have an exclusive lock? */
32042     if (pFile->local.bExclusive){
32043       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
32044       pFile->local.bExclusive = FALSE;
32045       pFile->shared->bExclusive = FALSE;
32046       bReturn = TRUE;
32047     }
32048
32049     /* Did we just have a reader lock? */
32050     else if (pFile->local.nReaders){
32051       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
32052              || nNumberOfBytesToUnlockLow == 1);
32053       pFile->local.nReaders --;
32054       if (pFile->local.nReaders == 0)
32055       {
32056         pFile->shared->nReaders --;
32057       }
32058       bReturn = TRUE;
32059     }
32060   }
32061
32062   /* Releasing a pending lock */
32063   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
32064            && nNumberOfBytesToUnlockLow == 1){
32065     if (pFile->local.bPending){
32066       pFile->local.bPending = FALSE;
32067       pFile->shared->bPending = FALSE;
32068       bReturn = TRUE;
32069     }
32070   }
32071   /* Releasing a reserved lock */
32072   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
32073            && nNumberOfBytesToUnlockLow == 1){
32074     if (pFile->local.bReserved) {
32075       pFile->local.bReserved = FALSE;
32076       pFile->shared->bReserved = FALSE;
32077       bReturn = TRUE;
32078     }
32079   }
32080
32081   winceMutexRelease(pFile->hMutex);
32082   return bReturn;
32083 }
32084 /*
32085 ** End of the special code for wince
32086 *****************************************************************************/
32087 #endif /* SQLITE_OS_WINCE */
32088
32089 /*
32090 ** Lock a file region.
32091 */
32092 static BOOL winLockFile(
32093   LPHANDLE phFile,
32094   DWORD flags,
32095   DWORD offsetLow,
32096   DWORD offsetHigh,
32097   DWORD numBytesLow,
32098   DWORD numBytesHigh
32099 ){
32100 #if SQLITE_OS_WINCE
32101   /*
32102   ** NOTE: Windows CE is handled differently here due its lack of the Win32
32103   **       API LockFile.
32104   */
32105   return winceLockFile(phFile, offsetLow, offsetHigh,
32106                        numBytesLow, numBytesHigh);
32107 #else
32108   if( isNT() ){
32109     OVERLAPPED ovlp;
32110     memset(&ovlp, 0, sizeof(OVERLAPPED));
32111     ovlp.Offset = offsetLow;
32112     ovlp.OffsetHigh = offsetHigh;
32113     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
32114   }else{
32115     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
32116                       numBytesHigh);
32117   }
32118 #endif
32119 }
32120
32121 /*
32122 ** Unlock a file region.
32123  */
32124 static BOOL winUnlockFile(
32125   LPHANDLE phFile,
32126   DWORD offsetLow,
32127   DWORD offsetHigh,
32128   DWORD numBytesLow,
32129   DWORD numBytesHigh
32130 ){
32131 #if SQLITE_OS_WINCE
32132   /*
32133   ** NOTE: Windows CE is handled differently here due its lack of the Win32
32134   **       API UnlockFile.
32135   */
32136   return winceUnlockFile(phFile, offsetLow, offsetHigh,
32137                          numBytesLow, numBytesHigh);
32138 #else
32139   if( isNT() ){
32140     OVERLAPPED ovlp;
32141     memset(&ovlp, 0, sizeof(OVERLAPPED));
32142     ovlp.Offset = offsetLow;
32143     ovlp.OffsetHigh = offsetHigh;
32144     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
32145   }else{
32146     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
32147                         numBytesHigh);
32148   }
32149 #endif
32150 }
32151
32152 /*****************************************************************************
32153 ** The next group of routines implement the I/O methods specified
32154 ** by the sqlite3_io_methods object.
32155 ******************************************************************************/
32156
32157 /*
32158 ** Some Microsoft compilers lack this definition.
32159 */
32160 #ifndef INVALID_SET_FILE_POINTER
32161 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
32162 #endif
32163
32164 /*
32165 ** Move the current position of the file handle passed as the first 
32166 ** argument to offset iOffset within the file. If successful, return 0. 
32167 ** Otherwise, set pFile->lastErrno and return non-zero.
32168 */
32169 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
32170 #if !SQLITE_OS_WINRT
32171   LONG upperBits;                 /* Most sig. 32 bits of new offset */
32172   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
32173   DWORD dwRet;                    /* Value returned by SetFilePointer() */
32174   DWORD lastErrno;                /* Value returned by GetLastError() */
32175
32176   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
32177   lowerBits = (LONG)(iOffset & 0xffffffff);
32178
32179   /* API oddity: If successful, SetFilePointer() returns a dword 
32180   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
32181   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
32182   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
32183   ** whether an error has actually occurred, it is also necessary to call 
32184   ** GetLastError().
32185   */
32186   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
32187
32188   if( (dwRet==INVALID_SET_FILE_POINTER
32189       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
32190     pFile->lastErrno = lastErrno;
32191     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
32192              "seekWinFile", pFile->zPath);
32193     return 1;
32194   }
32195
32196   return 0;
32197 #else
32198   /*
32199   ** Same as above, except that this implementation works for WinRT.
32200   */
32201
32202   LARGE_INTEGER x;                /* The new offset */
32203   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
32204
32205   x.QuadPart = iOffset;
32206   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
32207
32208   if(!bRet){
32209     pFile->lastErrno = osGetLastError();
32210     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
32211              "seekWinFile", pFile->zPath);
32212     return 1;
32213   }
32214
32215   return 0;
32216 #endif
32217 }
32218
32219 /*
32220 ** Close a file.
32221 **
32222 ** It is reported that an attempt to close a handle might sometimes
32223 ** fail.  This is a very unreasonable result, but Windows is notorious
32224 ** for being unreasonable so I do not doubt that it might happen.  If
32225 ** the close fails, we pause for 100 milliseconds and try again.  As
32226 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
32227 ** giving up and returning an error.
32228 */
32229 #define MX_CLOSE_ATTEMPT 3
32230 static int winClose(sqlite3_file *id){
32231   int rc, cnt = 0;
32232   winFile *pFile = (winFile*)id;
32233
32234   assert( id!=0 );
32235 #ifndef SQLITE_OMIT_WAL
32236   assert( pFile->pShm==0 );
32237 #endif
32238   OSTRACE(("CLOSE %d\n", pFile->h));
32239   assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
32240   do{
32241     rc = osCloseHandle(pFile->h);
32242     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
32243   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
32244 #if SQLITE_OS_WINCE
32245 #define WINCE_DELETION_ATTEMPTS 3
32246   winceDestroyLock(pFile);
32247   if( pFile->zDeleteOnClose ){
32248     int cnt = 0;
32249     while(
32250            osDeleteFileW(pFile->zDeleteOnClose)==0
32251         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
32252         && cnt++ < WINCE_DELETION_ATTEMPTS
32253     ){
32254        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
32255     }
32256     sqlite3_free(pFile->zDeleteOnClose);
32257   }
32258 #endif
32259   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
32260   if( rc ){
32261     pFile->h = NULL;
32262   }
32263   OpenCounter(-1);
32264   return rc ? SQLITE_OK
32265             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
32266                           "winClose", pFile->zPath);
32267 }
32268
32269 /*
32270 ** Read data from a file into a buffer.  Return SQLITE_OK if all
32271 ** bytes were read successfully and SQLITE_IOERR if anything goes
32272 ** wrong.
32273 */
32274 static int winRead(
32275   sqlite3_file *id,          /* File to read from */
32276   void *pBuf,                /* Write content into this buffer */
32277   int amt,                   /* Number of bytes to read */
32278   sqlite3_int64 offset       /* Begin reading at this offset */
32279 ){
32280 #if !SQLITE_OS_WINCE
32281   OVERLAPPED overlapped;          /* The offset for ReadFile. */
32282 #endif
32283   winFile *pFile = (winFile*)id;  /* file handle */
32284   DWORD nRead;                    /* Number of bytes actually read from file */
32285   int nRetry = 0;                 /* Number of retrys */
32286
32287   assert( id!=0 );
32288   SimulateIOError(return SQLITE_IOERR_READ);
32289   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
32290
32291 #if SQLITE_OS_WINCE
32292   if( seekWinFile(pFile, offset) ){
32293     return SQLITE_FULL;
32294   }
32295   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
32296 #else
32297   memset(&overlapped, 0, sizeof(OVERLAPPED));
32298   overlapped.Offset = (LONG)(offset & 0xffffffff);
32299   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32300   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
32301          osGetLastError()!=ERROR_HANDLE_EOF ){
32302 #endif
32303     DWORD lastErrno;
32304     if( retryIoerr(&nRetry, &lastErrno) ) continue;
32305     pFile->lastErrno = lastErrno;
32306     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
32307              "winRead", pFile->zPath);
32308   }
32309   logIoerr(nRetry);
32310   if( nRead<(DWORD)amt ){
32311     /* Unread parts of the buffer must be zero-filled */
32312     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
32313     return SQLITE_IOERR_SHORT_READ;
32314   }
32315
32316   return SQLITE_OK;
32317 }
32318
32319 /*
32320 ** Write data from a buffer into a file.  Return SQLITE_OK on success
32321 ** or some other error code on failure.
32322 */
32323 static int winWrite(
32324   sqlite3_file *id,               /* File to write into */
32325   const void *pBuf,               /* The bytes to be written */
32326   int amt,                        /* Number of bytes to write */
32327   sqlite3_int64 offset            /* Offset into the file to begin writing at */
32328 ){
32329   int rc = 0;                     /* True if error has occurred, else false */
32330   winFile *pFile = (winFile*)id;  /* File handle */
32331   int nRetry = 0;                 /* Number of retries */
32332
32333   assert( amt>0 );
32334   assert( pFile );
32335   SimulateIOError(return SQLITE_IOERR_WRITE);
32336   SimulateDiskfullError(return SQLITE_FULL);
32337
32338   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
32339
32340 #if SQLITE_OS_WINCE
32341   rc = seekWinFile(pFile, offset);
32342   if( rc==0 ){
32343 #else
32344   {
32345 #endif
32346 #if !SQLITE_OS_WINCE
32347     OVERLAPPED overlapped;        /* The offset for WriteFile. */
32348 #endif
32349     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
32350     int nRem = amt;               /* Number of bytes yet to be written */
32351     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
32352     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
32353
32354 #if !SQLITE_OS_WINCE
32355     memset(&overlapped, 0, sizeof(OVERLAPPED));
32356     overlapped.Offset = (LONG)(offset & 0xffffffff);
32357     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32358 #endif
32359
32360     while( nRem>0 ){
32361 #if SQLITE_OS_WINCE
32362       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
32363 #else
32364       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
32365 #endif
32366         if( retryIoerr(&nRetry, &lastErrno) ) continue;
32367         break;
32368       }
32369       assert( nWrite==0 || nWrite<=(DWORD)nRem );
32370       if( nWrite==0 || nWrite>(DWORD)nRem ){
32371         lastErrno = osGetLastError();
32372         break;
32373       }
32374 #if !SQLITE_OS_WINCE
32375       offset += nWrite;
32376       overlapped.Offset = (LONG)(offset & 0xffffffff);
32377       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32378 #endif
32379       aRem += nWrite;
32380       nRem -= nWrite;
32381     }
32382     if( nRem>0 ){
32383       pFile->lastErrno = lastErrno;
32384       rc = 1;
32385     }
32386   }
32387
32388   if( rc ){
32389     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
32390        || ( pFile->lastErrno==ERROR_DISK_FULL )){
32391       return SQLITE_FULL;
32392     }
32393     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
32394              "winWrite", pFile->zPath);
32395   }else{
32396     logIoerr(nRetry);
32397   }
32398   return SQLITE_OK;
32399 }
32400
32401 /*
32402 ** Truncate an open file to a specified size
32403 */
32404 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
32405   winFile *pFile = (winFile*)id;  /* File handle object */
32406   int rc = SQLITE_OK;             /* Return code for this function */
32407
32408   assert( pFile );
32409
32410   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
32411   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
32412
32413   /* If the user has configured a chunk-size for this file, truncate the
32414   ** file so that it consists of an integer number of chunks (i.e. the
32415   ** actual file size after the operation may be larger than the requested
32416   ** size).
32417   */
32418   if( pFile->szChunk>0 ){
32419     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
32420   }
32421
32422   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
32423   if( seekWinFile(pFile, nByte) ){
32424     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
32425              "winTruncate1", pFile->zPath);
32426   }else if( 0==osSetEndOfFile(pFile->h) ){
32427     pFile->lastErrno = osGetLastError();
32428     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
32429              "winTruncate2", pFile->zPath);
32430   }
32431
32432   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
32433   return rc;
32434 }
32435
32436 #ifdef SQLITE_TEST
32437 /*
32438 ** Count the number of fullsyncs and normal syncs.  This is used to test
32439 ** that syncs and fullsyncs are occuring at the right times.
32440 */
32441 SQLITE_API int sqlite3_sync_count = 0;
32442 SQLITE_API int sqlite3_fullsync_count = 0;
32443 #endif
32444
32445 /*
32446 ** Make sure all writes to a particular file are committed to disk.
32447 */
32448 static int winSync(sqlite3_file *id, int flags){
32449 #ifndef SQLITE_NO_SYNC
32450   /*
32451   ** Used only when SQLITE_NO_SYNC is not defined.
32452    */
32453   BOOL rc;
32454 #endif
32455 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
32456     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
32457   /*
32458   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
32459   ** OSTRACE() macros.
32460    */
32461   winFile *pFile = (winFile*)id;
32462 #else
32463   UNUSED_PARAMETER(id);
32464 #endif
32465
32466   assert( pFile );
32467   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32468   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32469       || (flags&0x0F)==SQLITE_SYNC_FULL
32470   );
32471
32472   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
32473
32474   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
32475   ** line is to test that doing so does not cause any problems.
32476   */
32477   SimulateDiskfullError( return SQLITE_FULL );
32478
32479 #ifndef SQLITE_TEST
32480   UNUSED_PARAMETER(flags);
32481 #else
32482   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
32483     sqlite3_fullsync_count++;
32484   }
32485   sqlite3_sync_count++;
32486 #endif
32487
32488   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32489   ** no-op
32490   */
32491 #ifdef SQLITE_NO_SYNC
32492   return SQLITE_OK;
32493 #else
32494   rc = osFlushFileBuffers(pFile->h);
32495   SimulateIOError( rc=FALSE );
32496   if( rc ){
32497     return SQLITE_OK;
32498   }else{
32499     pFile->lastErrno = osGetLastError();
32500     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
32501              "winSync", pFile->zPath);
32502   }
32503 #endif
32504 }
32505
32506 /*
32507 ** Determine the current size of a file in bytes
32508 */
32509 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
32510   winFile *pFile = (winFile*)id;
32511   int rc = SQLITE_OK;
32512
32513   assert( id!=0 );
32514   SimulateIOError(return SQLITE_IOERR_FSTAT);
32515 #if SQLITE_OS_WINRT
32516   {
32517     FILE_STANDARD_INFO info;
32518     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
32519                                      &info, sizeof(info)) ){
32520       *pSize = info.EndOfFile.QuadPart;
32521     }else{
32522       pFile->lastErrno = osGetLastError();
32523       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
32524                        "winFileSize", pFile->zPath);
32525     }
32526   }
32527 #else
32528   {
32529     DWORD upperBits;
32530     DWORD lowerBits;
32531     DWORD lastErrno;
32532
32533     lowerBits = osGetFileSize(pFile->h, &upperBits);
32534     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
32535     if(   (lowerBits == INVALID_FILE_SIZE)
32536        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
32537       pFile->lastErrno = lastErrno;
32538       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
32539              "winFileSize", pFile->zPath);
32540     }
32541   }
32542 #endif
32543   return rc;
32544 }
32545
32546 /*
32547 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
32548 */
32549 #ifndef LOCKFILE_FAIL_IMMEDIATELY
32550 # define LOCKFILE_FAIL_IMMEDIATELY 1
32551 #endif
32552
32553 #ifndef LOCKFILE_EXCLUSIVE_LOCK
32554 # define LOCKFILE_EXCLUSIVE_LOCK 2
32555 #endif
32556
32557 /*
32558 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
32559 ** When the LockFile function was used, it was always expected to fail
32560 ** immediately if the lock could not be obtained.  Also, it always expected to
32561 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
32562 ** and reflect those expectations; therefore, they should not be changed.
32563 */
32564 #ifndef SQLITE_LOCKFILE_FLAGS
32565 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
32566                                   LOCKFILE_EXCLUSIVE_LOCK)
32567 #endif
32568
32569 /*
32570 ** Currently, SQLite never calls the LockFileEx function without wanting the
32571 ** call to fail immediately if the lock cannot be obtained.
32572 */
32573 #ifndef SQLITE_LOCKFILEEX_FLAGS
32574 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
32575 #endif
32576
32577 /*
32578 ** Acquire a reader lock.
32579 ** Different API routines are called depending on whether or not this
32580 ** is Win9x or WinNT.
32581 */
32582 static int getReadLock(winFile *pFile){
32583   int res;
32584   if( isNT() ){
32585 #if SQLITE_OS_WINCE
32586     /*
32587     ** NOTE: Windows CE is handled differently here due its lack of the Win32
32588     **       API LockFileEx.
32589     */
32590     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
32591 #else
32592     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
32593                       SHARED_SIZE, 0);
32594 #endif
32595   }
32596 #ifdef SQLITE_WIN32_HAS_ANSI
32597   else{
32598     int lk;
32599     sqlite3_randomness(sizeof(lk), &lk);
32600     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
32601     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
32602                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32603   }
32604 #endif
32605   if( res == 0 ){
32606     pFile->lastErrno = osGetLastError();
32607     /* No need to log a failure to lock */
32608   }
32609   return res;
32610 }
32611
32612 /*
32613 ** Undo a readlock
32614 */
32615 static int unlockReadLock(winFile *pFile){
32616   int res;
32617   DWORD lastErrno;
32618   if( isNT() ){
32619     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32620   }
32621 #ifdef SQLITE_WIN32_HAS_ANSI
32622   else{
32623     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32624   }
32625 #endif
32626   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
32627     pFile->lastErrno = lastErrno;
32628     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
32629              "unlockReadLock", pFile->zPath);
32630   }
32631   return res;
32632 }
32633
32634 /*
32635 ** Lock the file with the lock specified by parameter locktype - one
32636 ** of the following:
32637 **
32638 **     (1) SHARED_LOCK
32639 **     (2) RESERVED_LOCK
32640 **     (3) PENDING_LOCK
32641 **     (4) EXCLUSIVE_LOCK
32642 **
32643 ** Sometimes when requesting one lock state, additional lock states
32644 ** are inserted in between.  The locking might fail on one of the later
32645 ** transitions leaving the lock state different from what it started but
32646 ** still short of its goal.  The following chart shows the allowed
32647 ** transitions and the inserted intermediate states:
32648 **
32649 **    UNLOCKED -> SHARED
32650 **    SHARED -> RESERVED
32651 **    SHARED -> (PENDING) -> EXCLUSIVE
32652 **    RESERVED -> (PENDING) -> EXCLUSIVE
32653 **    PENDING -> EXCLUSIVE
32654 **
32655 ** This routine will only increase a lock.  The winUnlock() routine
32656 ** erases all locks at once and returns us immediately to locking level 0.
32657 ** It is not possible to lower the locking level one step at a time.  You
32658 ** must go straight to locking level 0.
32659 */
32660 static int winLock(sqlite3_file *id, int locktype){
32661   int rc = SQLITE_OK;    /* Return code from subroutines */
32662   int res = 1;           /* Result of a Windows lock call */
32663   int newLocktype;       /* Set pFile->locktype to this value before exiting */
32664   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
32665   winFile *pFile = (winFile*)id;
32666   DWORD lastErrno = NO_ERROR;
32667
32668   assert( id!=0 );
32669   OSTRACE(("LOCK %d %d was %d(%d)\n",
32670            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
32671
32672   /* If there is already a lock of this type or more restrictive on the
32673   ** OsFile, do nothing. Don't use the end_lock: exit path, as
32674   ** sqlite3OsEnterMutex() hasn't been called yet.
32675   */
32676   if( pFile->locktype>=locktype ){
32677     return SQLITE_OK;
32678   }
32679
32680   /* Make sure the locking sequence is correct
32681   */
32682   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
32683   assert( locktype!=PENDING_LOCK );
32684   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
32685
32686   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
32687   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
32688   ** the PENDING_LOCK byte is temporary.
32689   */
32690   newLocktype = pFile->locktype;
32691   if(   (pFile->locktype==NO_LOCK)
32692      || (   (locktype==EXCLUSIVE_LOCK)
32693          && (pFile->locktype==RESERVED_LOCK))
32694   ){
32695     int cnt = 3;
32696     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
32697                                          PENDING_BYTE, 0, 1, 0))==0 ){
32698       /* Try 3 times to get the pending lock.  This is needed to work
32699       ** around problems caused by indexing and/or anti-virus software on
32700       ** Windows systems.
32701       ** If you are using this code as a model for alternative VFSes, do not
32702       ** copy this retry logic.  It is a hack intended for Windows only.
32703       */
32704       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
32705       if( cnt ) sqlite3_win32_sleep(1);
32706     }
32707     gotPendingLock = res;
32708     if( !res ){
32709       lastErrno = osGetLastError();
32710     }
32711   }
32712
32713   /* Acquire a shared lock
32714   */
32715   if( locktype==SHARED_LOCK && res ){
32716     assert( pFile->locktype==NO_LOCK );
32717     res = getReadLock(pFile);
32718     if( res ){
32719       newLocktype = SHARED_LOCK;
32720     }else{
32721       lastErrno = osGetLastError();
32722     }
32723   }
32724
32725   /* Acquire a RESERVED lock
32726   */
32727   if( locktype==RESERVED_LOCK && res ){
32728     assert( pFile->locktype==SHARED_LOCK );
32729     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
32730     if( res ){
32731       newLocktype = RESERVED_LOCK;
32732     }else{
32733       lastErrno = osGetLastError();
32734     }
32735   }
32736
32737   /* Acquire a PENDING lock
32738   */
32739   if( locktype==EXCLUSIVE_LOCK && res ){
32740     newLocktype = PENDING_LOCK;
32741     gotPendingLock = 0;
32742   }
32743
32744   /* Acquire an EXCLUSIVE lock
32745   */
32746   if( locktype==EXCLUSIVE_LOCK && res ){
32747     assert( pFile->locktype>=SHARED_LOCK );
32748     res = unlockReadLock(pFile);
32749     OSTRACE(("unreadlock = %d\n", res));
32750     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
32751                       SHARED_SIZE, 0);
32752     if( res ){
32753       newLocktype = EXCLUSIVE_LOCK;
32754     }else{
32755       lastErrno = osGetLastError();
32756       OSTRACE(("error-code = %d\n", lastErrno));
32757       getReadLock(pFile);
32758     }
32759   }
32760
32761   /* If we are holding a PENDING lock that ought to be released, then
32762   ** release it now.
32763   */
32764   if( gotPendingLock && locktype==SHARED_LOCK ){
32765     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
32766   }
32767
32768   /* Update the state of the lock has held in the file descriptor then
32769   ** return the appropriate result code.
32770   */
32771   if( res ){
32772     rc = SQLITE_OK;
32773   }else{
32774     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
32775            locktype, newLocktype));
32776     pFile->lastErrno = lastErrno;
32777     rc = SQLITE_BUSY;
32778   }
32779   pFile->locktype = (u8)newLocktype;
32780   return rc;
32781 }
32782
32783 /*
32784 ** This routine checks if there is a RESERVED lock held on the specified
32785 ** file by this or any other process. If such a lock is held, return
32786 ** non-zero, otherwise zero.
32787 */
32788 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
32789   int rc;
32790   winFile *pFile = (winFile*)id;
32791
32792   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32793
32794   assert( id!=0 );
32795   if( pFile->locktype>=RESERVED_LOCK ){
32796     rc = 1;
32797     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
32798   }else{
32799     rc = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
32800     if( rc ){
32801       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
32802     }
32803     rc = !rc;
32804     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
32805   }
32806   *pResOut = rc;
32807   return SQLITE_OK;
32808 }
32809
32810 /*
32811 ** Lower the locking level on file descriptor id to locktype.  locktype
32812 ** must be either NO_LOCK or SHARED_LOCK.
32813 **
32814 ** If the locking level of the file descriptor is already at or below
32815 ** the requested locking level, this routine is a no-op.
32816 **
32817 ** It is not possible for this routine to fail if the second argument
32818 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
32819 ** might return SQLITE_IOERR;
32820 */
32821 static int winUnlock(sqlite3_file *id, int locktype){
32822   int type;
32823   winFile *pFile = (winFile*)id;
32824   int rc = SQLITE_OK;
32825   assert( pFile!=0 );
32826   assert( locktype<=SHARED_LOCK );
32827   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
32828           pFile->locktype, pFile->sharedLockByte));
32829   type = pFile->locktype;
32830   if( type>=EXCLUSIVE_LOCK ){
32831     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32832     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
32833       /* This should never happen.  We should always be able to
32834       ** reacquire the read lock */
32835       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
32836                "winUnlock", pFile->zPath);
32837     }
32838   }
32839   if( type>=RESERVED_LOCK ){
32840     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
32841   }
32842   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
32843     unlockReadLock(pFile);
32844   }
32845   if( type>=PENDING_LOCK ){
32846     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
32847   }
32848   pFile->locktype = (u8)locktype;
32849   return rc;
32850 }
32851
32852 /*
32853 ** If *pArg is inititially negative then this is a query.  Set *pArg to
32854 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
32855 **
32856 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
32857 */
32858 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
32859   if( *pArg<0 ){
32860     *pArg = (pFile->ctrlFlags & mask)!=0;
32861   }else if( (*pArg)==0 ){
32862     pFile->ctrlFlags &= ~mask;
32863   }else{
32864     pFile->ctrlFlags |= mask;
32865   }
32866 }
32867
32868 /* Forward declaration */
32869 static int getTempname(int nBuf, char *zBuf);
32870
32871 /*
32872 ** Control and query of the open file handle.
32873 */
32874 static int winFileControl(sqlite3_file *id, int op, void *pArg){
32875   winFile *pFile = (winFile*)id;
32876   switch( op ){
32877     case SQLITE_FCNTL_LOCKSTATE: {
32878       *(int*)pArg = pFile->locktype;
32879       return SQLITE_OK;
32880     }
32881     case SQLITE_LAST_ERRNO: {
32882       *(int*)pArg = (int)pFile->lastErrno;
32883       return SQLITE_OK;
32884     }
32885     case SQLITE_FCNTL_CHUNK_SIZE: {
32886       pFile->szChunk = *(int *)pArg;
32887       return SQLITE_OK;
32888     }
32889     case SQLITE_FCNTL_SIZE_HINT: {
32890       if( pFile->szChunk>0 ){
32891         sqlite3_int64 oldSz;
32892         int rc = winFileSize(id, &oldSz);
32893         if( rc==SQLITE_OK ){
32894           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
32895           if( newSz>oldSz ){
32896             SimulateIOErrorBenign(1);
32897             rc = winTruncate(id, newSz);
32898             SimulateIOErrorBenign(0);
32899           }
32900         }
32901         return rc;
32902       }
32903       return SQLITE_OK;
32904     }
32905     case SQLITE_FCNTL_PERSIST_WAL: {
32906       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
32907       return SQLITE_OK;
32908     }
32909     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
32910       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
32911       return SQLITE_OK;
32912     }
32913     case SQLITE_FCNTL_VFSNAME: {
32914       *(char**)pArg = sqlite3_mprintf("win32");
32915       return SQLITE_OK;
32916     }
32917     case SQLITE_FCNTL_WIN32_AV_RETRY: {
32918       int *a = (int*)pArg;
32919       if( a[0]>0 ){
32920         win32IoerrRetry = a[0];
32921       }else{
32922         a[0] = win32IoerrRetry;
32923       }
32924       if( a[1]>0 ){
32925         win32IoerrRetryDelay = a[1];
32926       }else{
32927         a[1] = win32IoerrRetryDelay;
32928       }
32929       return SQLITE_OK;
32930     }
32931     case SQLITE_FCNTL_TEMPFILENAME: {
32932       char *zTFile = sqlite3MallocZero( pFile->pVfs->mxPathname );
32933       if( zTFile ){
32934         getTempname(pFile->pVfs->mxPathname, zTFile);
32935         *(char**)pArg = zTFile;
32936       }
32937       return SQLITE_OK;
32938     }
32939   }
32940   return SQLITE_NOTFOUND;
32941 }
32942
32943 /*
32944 ** Return the sector size in bytes of the underlying block device for
32945 ** the specified file. This is almost always 512 bytes, but may be
32946 ** larger for some devices.
32947 **
32948 ** SQLite code assumes this function cannot fail. It also assumes that
32949 ** if two files are created in the same file-system directory (i.e.
32950 ** a database and its journal file) that the sector size will be the
32951 ** same for both.
32952 */
32953 static int winSectorSize(sqlite3_file *id){
32954   (void)id;
32955   return SQLITE_DEFAULT_SECTOR_SIZE;
32956 }
32957
32958 /*
32959 ** Return a vector of device characteristics.
32960 */
32961 static int winDeviceCharacteristics(sqlite3_file *id){
32962   winFile *p = (winFile*)id;
32963   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
32964          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
32965 }
32966
32967 #ifndef SQLITE_OMIT_WAL
32968
32969 /* 
32970 ** Windows will only let you create file view mappings
32971 ** on allocation size granularity boundaries.
32972 ** During sqlite3_os_init() we do a GetSystemInfo()
32973 ** to get the granularity size.
32974 */
32975 SYSTEM_INFO winSysInfo;
32976
32977 /*
32978 ** Helper functions to obtain and relinquish the global mutex. The
32979 ** global mutex is used to protect the winLockInfo objects used by 
32980 ** this file, all of which may be shared by multiple threads.
32981 **
32982 ** Function winShmMutexHeld() is used to assert() that the global mutex 
32983 ** is held when required. This function is only used as part of assert() 
32984 ** statements. e.g.
32985 **
32986 **   winShmEnterMutex()
32987 **     assert( winShmMutexHeld() );
32988 **   winShmLeaveMutex()
32989 */
32990 static void winShmEnterMutex(void){
32991   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32992 }
32993 static void winShmLeaveMutex(void){
32994   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32995 }
32996 #ifdef SQLITE_DEBUG
32997 static int winShmMutexHeld(void) {
32998   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32999 }
33000 #endif
33001
33002 /*
33003 ** Object used to represent a single file opened and mmapped to provide
33004 ** shared memory.  When multiple threads all reference the same
33005 ** log-summary, each thread has its own winFile object, but they all
33006 ** point to a single instance of this object.  In other words, each
33007 ** log-summary is opened only once per process.
33008 **
33009 ** winShmMutexHeld() must be true when creating or destroying
33010 ** this object or while reading or writing the following fields:
33011 **
33012 **      nRef
33013 **      pNext 
33014 **
33015 ** The following fields are read-only after the object is created:
33016 ** 
33017 **      fid
33018 **      zFilename
33019 **
33020 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
33021 ** winShmMutexHeld() is true when reading or writing any other field
33022 ** in this structure.
33023 **
33024 */
33025 struct winShmNode {
33026   sqlite3_mutex *mutex;      /* Mutex to access this object */
33027   char *zFilename;           /* Name of the file */
33028   winFile hFile;             /* File handle from winOpen */
33029
33030   int szRegion;              /* Size of shared-memory regions */
33031   int nRegion;               /* Size of array apRegion */
33032   struct ShmRegion {
33033     HANDLE hMap;             /* File handle from CreateFileMapping */
33034     void *pMap;
33035   } *aRegion;
33036   DWORD lastErrno;           /* The Windows errno from the last I/O error */
33037
33038   int nRef;                  /* Number of winShm objects pointing to this */
33039   winShm *pFirst;            /* All winShm objects pointing to this */
33040   winShmNode *pNext;         /* Next in list of all winShmNode objects */
33041 #ifdef SQLITE_DEBUG
33042   u8 nextShmId;              /* Next available winShm.id value */
33043 #endif
33044 };
33045
33046 /*
33047 ** A global array of all winShmNode objects.
33048 **
33049 ** The winShmMutexHeld() must be true while reading or writing this list.
33050 */
33051 static winShmNode *winShmNodeList = 0;
33052
33053 /*
33054 ** Structure used internally by this VFS to record the state of an
33055 ** open shared memory connection.
33056 **
33057 ** The following fields are initialized when this object is created and
33058 ** are read-only thereafter:
33059 **
33060 **    winShm.pShmNode
33061 **    winShm.id
33062 **
33063 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
33064 ** while accessing any read/write fields.
33065 */
33066 struct winShm {
33067   winShmNode *pShmNode;      /* The underlying winShmNode object */
33068   winShm *pNext;             /* Next winShm with the same winShmNode */
33069   u8 hasMutex;               /* True if holding the winShmNode mutex */
33070   u16 sharedMask;            /* Mask of shared locks held */
33071   u16 exclMask;              /* Mask of exclusive locks held */
33072 #ifdef SQLITE_DEBUG
33073   u8 id;                     /* Id of this connection with its winShmNode */
33074 #endif
33075 };
33076
33077 /*
33078 ** Constants used for locking
33079 */
33080 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
33081 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
33082
33083 /*
33084 ** Apply advisory locks for all n bytes beginning at ofst.
33085 */
33086 #define _SHM_UNLCK  1
33087 #define _SHM_RDLCK  2
33088 #define _SHM_WRLCK  3
33089 static int winShmSystemLock(
33090   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
33091   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
33092   int ofst,             /* Offset to first byte to be locked/unlocked */
33093   int nByte             /* Number of bytes to lock or unlock */
33094 ){
33095   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
33096
33097   /* Access to the winShmNode object is serialized by the caller */
33098   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
33099
33100   /* Release/Acquire the system-level lock */
33101   if( lockType==_SHM_UNLCK ){
33102     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
33103   }else{
33104     /* Initialize the locking parameters */
33105     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
33106     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
33107     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
33108   }
33109   
33110   if( rc!= 0 ){
33111     rc = SQLITE_OK;
33112   }else{
33113     pFile->lastErrno =  osGetLastError();
33114     rc = SQLITE_BUSY;
33115   }
33116
33117   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
33118            pFile->hFile.h,
33119            rc==SQLITE_OK ? "ok" : "failed",
33120            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
33121            pFile->lastErrno));
33122
33123   return rc;
33124 }
33125
33126 /* Forward references to VFS methods */
33127 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
33128 static int winDelete(sqlite3_vfs *,const char*,int);
33129
33130 /*
33131 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
33132 **
33133 ** This is not a VFS shared-memory method; it is a utility function called
33134 ** by VFS shared-memory methods.
33135 */
33136 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
33137   winShmNode **pp;
33138   winShmNode *p;
33139   BOOL bRc;
33140   assert( winShmMutexHeld() );
33141   pp = &winShmNodeList;
33142   while( (p = *pp)!=0 ){
33143     if( p->nRef==0 ){
33144       int i;
33145       if( p->mutex ) sqlite3_mutex_free(p->mutex);
33146       for(i=0; i<p->nRegion; i++){
33147         bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
33148         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
33149                  (int)osGetCurrentProcessId(), i,
33150                  bRc ? "ok" : "failed"));
33151         bRc = osCloseHandle(p->aRegion[i].hMap);
33152         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
33153                  (int)osGetCurrentProcessId(), i,
33154                  bRc ? "ok" : "failed"));
33155       }
33156       if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
33157         SimulateIOErrorBenign(1);
33158         winClose((sqlite3_file *)&p->hFile);
33159         SimulateIOErrorBenign(0);
33160       }
33161       if( deleteFlag ){
33162         SimulateIOErrorBenign(1);
33163         sqlite3BeginBenignMalloc();
33164         winDelete(pVfs, p->zFilename, 0);
33165         sqlite3EndBenignMalloc();
33166         SimulateIOErrorBenign(0);
33167       }
33168       *pp = p->pNext;
33169       sqlite3_free(p->aRegion);
33170       sqlite3_free(p);
33171     }else{
33172       pp = &p->pNext;
33173     }
33174   }
33175 }
33176
33177 /*
33178 ** Open the shared-memory area associated with database file pDbFd.
33179 **
33180 ** When opening a new shared-memory file, if no other instances of that
33181 ** file are currently open, in this process or in other processes, then
33182 ** the file must be truncated to zero length or have its header cleared.
33183 */
33184 static int winOpenSharedMemory(winFile *pDbFd){
33185   struct winShm *p;                  /* The connection to be opened */
33186   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
33187   int rc;                            /* Result code */
33188   struct winShmNode *pNew;           /* Newly allocated winShmNode */
33189   int nName;                         /* Size of zName in bytes */
33190
33191   assert( pDbFd->pShm==0 );    /* Not previously opened */
33192
33193   /* Allocate space for the new sqlite3_shm object.  Also speculatively
33194   ** allocate space for a new winShmNode and filename.
33195   */
33196   p = sqlite3MallocZero( sizeof(*p) );
33197   if( p==0 ) return SQLITE_IOERR_NOMEM;
33198   nName = sqlite3Strlen30(pDbFd->zPath);
33199   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
33200   if( pNew==0 ){
33201     sqlite3_free(p);
33202     return SQLITE_IOERR_NOMEM;
33203   }
33204   pNew->zFilename = (char*)&pNew[1];
33205   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
33206   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); 
33207
33208   /* Look to see if there is an existing winShmNode that can be used.
33209   ** If no matching winShmNode currently exists, create a new one.
33210   */
33211   winShmEnterMutex();
33212   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
33213     /* TBD need to come up with better match here.  Perhaps
33214     ** use FILE_ID_BOTH_DIR_INFO Structure.
33215     */
33216     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
33217   }
33218   if( pShmNode ){
33219     sqlite3_free(pNew);
33220   }else{
33221     pShmNode = pNew;
33222     pNew = 0;
33223     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
33224     pShmNode->pNext = winShmNodeList;
33225     winShmNodeList = pShmNode;
33226
33227     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33228     if( pShmNode->mutex==0 ){
33229       rc = SQLITE_IOERR_NOMEM;
33230       goto shm_open_err;
33231     }
33232
33233     rc = winOpen(pDbFd->pVfs,
33234                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
33235                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
33236                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
33237                  0);
33238     if( SQLITE_OK!=rc ){
33239       goto shm_open_err;
33240     }
33241
33242     /* Check to see if another process is holding the dead-man switch.
33243     ** If not, truncate the file to zero length. 
33244     */
33245     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
33246       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
33247       if( rc!=SQLITE_OK ){
33248         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
33249                  "winOpenShm", pDbFd->zPath);
33250       }
33251     }
33252     if( rc==SQLITE_OK ){
33253       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33254       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
33255     }
33256     if( rc ) goto shm_open_err;
33257   }
33258
33259   /* Make the new connection a child of the winShmNode */
33260   p->pShmNode = pShmNode;
33261 #ifdef SQLITE_DEBUG
33262   p->id = pShmNode->nextShmId++;
33263 #endif
33264   pShmNode->nRef++;
33265   pDbFd->pShm = p;
33266   winShmLeaveMutex();
33267
33268   /* The reference count on pShmNode has already been incremented under
33269   ** the cover of the winShmEnterMutex() mutex and the pointer from the
33270   ** new (struct winShm) object to the pShmNode has been set. All that is
33271   ** left to do is to link the new object into the linked list starting
33272   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
33273   ** mutex.
33274   */
33275   sqlite3_mutex_enter(pShmNode->mutex);
33276   p->pNext = pShmNode->pFirst;
33277   pShmNode->pFirst = p;
33278   sqlite3_mutex_leave(pShmNode->mutex);
33279   return SQLITE_OK;
33280
33281   /* Jump here on any error */
33282 shm_open_err:
33283   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33284   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
33285   sqlite3_free(p);
33286   sqlite3_free(pNew);
33287   winShmLeaveMutex();
33288   return rc;
33289 }
33290
33291 /*
33292 ** Close a connection to shared-memory.  Delete the underlying 
33293 ** storage if deleteFlag is true.
33294 */
33295 static int winShmUnmap(
33296   sqlite3_file *fd,          /* Database holding shared memory */
33297   int deleteFlag             /* Delete after closing if true */
33298 ){
33299   winFile *pDbFd;       /* Database holding shared-memory */
33300   winShm *p;            /* The connection to be closed */
33301   winShmNode *pShmNode; /* The underlying shared-memory file */
33302   winShm **pp;          /* For looping over sibling connections */
33303
33304   pDbFd = (winFile*)fd;
33305   p = pDbFd->pShm;
33306   if( p==0 ) return SQLITE_OK;
33307   pShmNode = p->pShmNode;
33308
33309   /* Remove connection p from the set of connections associated
33310   ** with pShmNode */
33311   sqlite3_mutex_enter(pShmNode->mutex);
33312   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
33313   *pp = p->pNext;
33314
33315   /* Free the connection p */
33316   sqlite3_free(p);
33317   pDbFd->pShm = 0;
33318   sqlite3_mutex_leave(pShmNode->mutex);
33319
33320   /* If pShmNode->nRef has reached 0, then close the underlying
33321   ** shared-memory file, too */
33322   winShmEnterMutex();
33323   assert( pShmNode->nRef>0 );
33324   pShmNode->nRef--;
33325   if( pShmNode->nRef==0 ){
33326     winShmPurge(pDbFd->pVfs, deleteFlag);
33327   }
33328   winShmLeaveMutex();
33329
33330   return SQLITE_OK;
33331 }
33332
33333 /*
33334 ** Change the lock state for a shared-memory segment.
33335 */
33336 static int winShmLock(
33337   sqlite3_file *fd,          /* Database file holding the shared memory */
33338   int ofst,                  /* First lock to acquire or release */
33339   int n,                     /* Number of locks to acquire or release */
33340   int flags                  /* What to do with the lock */
33341 ){
33342   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
33343   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
33344   winShm *pX;                           /* For looping over all siblings */
33345   winShmNode *pShmNode = p->pShmNode;
33346   int rc = SQLITE_OK;                   /* Result code */
33347   u16 mask;                             /* Mask of locks to take or release */
33348
33349   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
33350   assert( n>=1 );
33351   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
33352        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
33353        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
33354        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
33355   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
33356
33357   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
33358   assert( n>1 || mask==(1<<ofst) );
33359   sqlite3_mutex_enter(pShmNode->mutex);
33360   if( flags & SQLITE_SHM_UNLOCK ){
33361     u16 allMask = 0; /* Mask of locks held by siblings */
33362
33363     /* See if any siblings hold this same lock */
33364     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33365       if( pX==p ) continue;
33366       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
33367       allMask |= pX->sharedMask;
33368     }
33369
33370     /* Unlock the system-level locks */
33371     if( (mask & allMask)==0 ){
33372       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
33373     }else{
33374       rc = SQLITE_OK;
33375     }
33376
33377     /* Undo the local locks */
33378     if( rc==SQLITE_OK ){
33379       p->exclMask &= ~mask;
33380       p->sharedMask &= ~mask;
33381     } 
33382   }else if( flags & SQLITE_SHM_SHARED ){
33383     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
33384
33385     /* Find out which shared locks are already held by sibling connections.
33386     ** If any sibling already holds an exclusive lock, go ahead and return
33387     ** SQLITE_BUSY.
33388     */
33389     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33390       if( (pX->exclMask & mask)!=0 ){
33391         rc = SQLITE_BUSY;
33392         break;
33393       }
33394       allShared |= pX->sharedMask;
33395     }
33396
33397     /* Get shared locks at the system level, if necessary */
33398     if( rc==SQLITE_OK ){
33399       if( (allShared & mask)==0 ){
33400         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
33401       }else{
33402         rc = SQLITE_OK;
33403       }
33404     }
33405
33406     /* Get the local shared locks */
33407     if( rc==SQLITE_OK ){
33408       p->sharedMask |= mask;
33409     }
33410   }else{
33411     /* Make sure no sibling connections hold locks that will block this
33412     ** lock.  If any do, return SQLITE_BUSY right away.
33413     */
33414     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33415       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
33416         rc = SQLITE_BUSY;
33417         break;
33418       }
33419     }
33420   
33421     /* Get the exclusive locks at the system level.  Then if successful
33422     ** also mark the local connection as being locked.
33423     */
33424     if( rc==SQLITE_OK ){
33425       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
33426       if( rc==SQLITE_OK ){
33427         assert( (p->sharedMask & mask)==0 );
33428         p->exclMask |= mask;
33429       }
33430     }
33431   }
33432   sqlite3_mutex_leave(pShmNode->mutex);
33433   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
33434            p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
33435            rc ? "failed" : "ok"));
33436   return rc;
33437 }
33438
33439 /*
33440 ** Implement a memory barrier or memory fence on shared memory.  
33441 **
33442 ** All loads and stores begun before the barrier must complete before
33443 ** any load or store begun after the barrier.
33444 */
33445 static void winShmBarrier(
33446   sqlite3_file *fd          /* Database holding the shared memory */
33447 ){
33448   UNUSED_PARAMETER(fd);
33449   /* MemoryBarrier(); // does not work -- do not know why not */
33450   winShmEnterMutex();
33451   winShmLeaveMutex();
33452 }
33453
33454 /*
33455 ** This function is called to obtain a pointer to region iRegion of the 
33456 ** shared-memory associated with the database file fd. Shared-memory regions 
33457 ** are numbered starting from zero. Each shared-memory region is szRegion 
33458 ** bytes in size.
33459 **
33460 ** If an error occurs, an error code is returned and *pp is set to NULL.
33461 **
33462 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
33463 ** region has not been allocated (by any client, including one running in a
33464 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
33465 ** isWrite is non-zero and the requested shared-memory region has not yet 
33466 ** been allocated, it is allocated by this function.
33467 **
33468 ** If the shared-memory region has already been allocated or is allocated by
33469 ** this call as described above, then it is mapped into this processes 
33470 ** address space (if it is not already), *pp is set to point to the mapped 
33471 ** memory and SQLITE_OK returned.
33472 */
33473 static int winShmMap(
33474   sqlite3_file *fd,               /* Handle open on database file */
33475   int iRegion,                    /* Region to retrieve */
33476   int szRegion,                   /* Size of regions */
33477   int isWrite,                    /* True to extend file if necessary */
33478   void volatile **pp              /* OUT: Mapped memory */
33479 ){
33480   winFile *pDbFd = (winFile*)fd;
33481   winShm *p = pDbFd->pShm;
33482   winShmNode *pShmNode;
33483   int rc = SQLITE_OK;
33484
33485   if( !p ){
33486     rc = winOpenSharedMemory(pDbFd);
33487     if( rc!=SQLITE_OK ) return rc;
33488     p = pDbFd->pShm;
33489   }
33490   pShmNode = p->pShmNode;
33491
33492   sqlite3_mutex_enter(pShmNode->mutex);
33493   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
33494
33495   if( pShmNode->nRegion<=iRegion ){
33496     struct ShmRegion *apNew;           /* New aRegion[] array */
33497     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
33498     sqlite3_int64 sz;                  /* Current size of wal-index file */
33499
33500     pShmNode->szRegion = szRegion;
33501
33502     /* The requested region is not mapped into this processes address space.
33503     ** Check to see if it has been allocated (i.e. if the wal-index file is
33504     ** large enough to contain the requested region).
33505     */
33506     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
33507     if( rc!=SQLITE_OK ){
33508       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
33509                "winShmMap1", pDbFd->zPath);
33510       goto shmpage_out;
33511     }
33512
33513     if( sz<nByte ){
33514       /* The requested memory region does not exist. If isWrite is set to
33515       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
33516       **
33517       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
33518       ** the requested memory region.
33519       */
33520       if( !isWrite ) goto shmpage_out;
33521       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
33522       if( rc!=SQLITE_OK ){
33523         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
33524                  "winShmMap2", pDbFd->zPath);
33525         goto shmpage_out;
33526       }
33527     }
33528
33529     /* Map the requested memory region into this processes address space. */
33530     apNew = (struct ShmRegion *)sqlite3_realloc(
33531         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
33532     );
33533     if( !apNew ){
33534       rc = SQLITE_IOERR_NOMEM;
33535       goto shmpage_out;
33536     }
33537     pShmNode->aRegion = apNew;
33538
33539     while( pShmNode->nRegion<=iRegion ){
33540       HANDLE hMap = NULL;         /* file-mapping handle */
33541       void *pMap = 0;             /* Mapped memory region */
33542      
33543 #if SQLITE_OS_WINRT
33544       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
33545           NULL, PAGE_READWRITE, nByte, NULL
33546       );
33547 #elif defined(SQLITE_WIN32_HAS_WIDE)
33548       hMap = osCreateFileMappingW(pShmNode->hFile.h, 
33549           NULL, PAGE_READWRITE, 0, nByte, NULL
33550       );
33551 #elif defined(SQLITE_WIN32_HAS_ANSI)
33552       hMap = osCreateFileMappingA(pShmNode->hFile.h, 
33553           NULL, PAGE_READWRITE, 0, nByte, NULL
33554       );
33555 #endif
33556       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
33557                (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
33558                hMap ? "ok" : "failed"));
33559       if( hMap ){
33560         int iOffset = pShmNode->nRegion*szRegion;
33561         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33562 #if SQLITE_OS_WINRT
33563         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
33564             iOffset - iOffsetShift, szRegion + iOffsetShift
33565         );
33566 #else
33567         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
33568             0, iOffset - iOffsetShift, szRegion + iOffsetShift
33569         );
33570 #endif
33571         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
33572                  (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
33573                  szRegion, pMap ? "ok" : "failed"));
33574       }
33575       if( !pMap ){
33576         pShmNode->lastErrno = osGetLastError();
33577         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
33578                  "winShmMap3", pDbFd->zPath);
33579         if( hMap ) osCloseHandle(hMap);
33580         goto shmpage_out;
33581       }
33582
33583       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
33584       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
33585       pShmNode->nRegion++;
33586     }
33587   }
33588
33589 shmpage_out:
33590   if( pShmNode->nRegion>iRegion ){
33591     int iOffset = iRegion*szRegion;
33592     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33593     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
33594     *pp = (void *)&p[iOffsetShift];
33595   }else{
33596     *pp = 0;
33597   }
33598   sqlite3_mutex_leave(pShmNode->mutex);
33599   return rc;
33600 }
33601
33602 #else
33603 # define winShmMap     0
33604 # define winShmLock    0
33605 # define winShmBarrier 0
33606 # define winShmUnmap   0
33607 #endif /* #ifndef SQLITE_OMIT_WAL */
33608
33609 /*
33610 ** Here ends the implementation of all sqlite3_file methods.
33611 **
33612 ********************** End sqlite3_file Methods *******************************
33613 ******************************************************************************/
33614
33615 /*
33616 ** This vector defines all the methods that can operate on an
33617 ** sqlite3_file for win32.
33618 */
33619 static const sqlite3_io_methods winIoMethod = {
33620   2,                              /* iVersion */
33621   winClose,                       /* xClose */
33622   winRead,                        /* xRead */
33623   winWrite,                       /* xWrite */
33624   winTruncate,                    /* xTruncate */
33625   winSync,                        /* xSync */
33626   winFileSize,                    /* xFileSize */
33627   winLock,                        /* xLock */
33628   winUnlock,                      /* xUnlock */
33629   winCheckReservedLock,           /* xCheckReservedLock */
33630   winFileControl,                 /* xFileControl */
33631   winSectorSize,                  /* xSectorSize */
33632   winDeviceCharacteristics,       /* xDeviceCharacteristics */
33633   winShmMap,                      /* xShmMap */
33634   winShmLock,                     /* xShmLock */
33635   winShmBarrier,                  /* xShmBarrier */
33636   winShmUnmap                     /* xShmUnmap */
33637 };
33638
33639 /****************************************************************************
33640 **************************** sqlite3_vfs methods ****************************
33641 **
33642 ** This division contains the implementation of methods on the
33643 ** sqlite3_vfs object.
33644 */
33645
33646 /*
33647 ** Convert a UTF-8 filename into whatever form the underlying
33648 ** operating system wants filenames in.  Space to hold the result
33649 ** is obtained from malloc and must be freed by the calling
33650 ** function.
33651 */
33652 static void *convertUtf8Filename(const char *zFilename){
33653   void *zConverted = 0;
33654   if( isNT() ){
33655     zConverted = utf8ToUnicode(zFilename);
33656   }
33657 #ifdef SQLITE_WIN32_HAS_ANSI
33658   else{
33659     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
33660   }
33661 #endif
33662   /* caller will handle out of memory */
33663   return zConverted;
33664 }
33665
33666 /*
33667 ** Create a temporary file name in zBuf.  zBuf must be big enough to
33668 ** hold at pVfs->mxPathname characters.
33669 */
33670 static int getTempname(int nBuf, char *zBuf){
33671   static char zChars[] =
33672     "abcdefghijklmnopqrstuvwxyz"
33673     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
33674     "0123456789";
33675   size_t i, j;
33676   int nTempPath;
33677   char zTempPath[MAX_PATH+2];
33678
33679   /* It's odd to simulate an io-error here, but really this is just
33680   ** using the io-error infrastructure to test that SQLite handles this
33681   ** function failing. 
33682   */
33683   SimulateIOError( return SQLITE_IOERR );
33684
33685   memset(zTempPath, 0, MAX_PATH+2);
33686
33687   if( sqlite3_temp_directory ){
33688     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
33689   }
33690 #if !SQLITE_OS_WINRT
33691   else if( isNT() ){
33692     char *zMulti;
33693     WCHAR zWidePath[MAX_PATH];
33694     osGetTempPathW(MAX_PATH-30, zWidePath);
33695     zMulti = unicodeToUtf8(zWidePath);
33696     if( zMulti ){
33697       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
33698       sqlite3_free(zMulti);
33699     }else{
33700       return SQLITE_IOERR_NOMEM;
33701     }
33702   }
33703 #ifdef SQLITE_WIN32_HAS_ANSI
33704   else{
33705     char *zUtf8;
33706     char zMbcsPath[MAX_PATH];
33707     osGetTempPathA(MAX_PATH-30, zMbcsPath);
33708     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
33709     if( zUtf8 ){
33710       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
33711       sqlite3_free(zUtf8);
33712     }else{
33713       return SQLITE_IOERR_NOMEM;
33714     }
33715   }
33716 #endif
33717 #endif
33718
33719   /* Check that the output buffer is large enough for the temporary file 
33720   ** name. If it is not, return SQLITE_ERROR.
33721   */
33722   nTempPath = sqlite3Strlen30(zTempPath);
33723
33724   if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
33725     return SQLITE_ERROR;
33726   }
33727
33728   for(i=nTempPath; i>0 && zTempPath[i-1]=='\\'; i--){}
33729   zTempPath[i] = 0;
33730
33731   sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?
33732                        "%s\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,
33733                    zTempPath);
33734   j = sqlite3Strlen30(zBuf);
33735   sqlite3_randomness(15, &zBuf[j]);
33736   for(i=0; i<15; i++, j++){
33737     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
33738   }
33739   zBuf[j] = 0;
33740   zBuf[j+1] = 0;
33741
33742   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
33743   return SQLITE_OK; 
33744 }
33745
33746 /*
33747 ** Return TRUE if the named file is really a directory.  Return false if
33748 ** it is something other than a directory, or if there is any kind of memory
33749 ** allocation failure.
33750 */
33751 static int winIsDir(const void *zConverted){
33752   DWORD attr;
33753   int rc = 0;
33754   DWORD lastErrno;
33755
33756   if( isNT() ){
33757     int cnt = 0;
33758     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
33759     memset(&sAttrData, 0, sizeof(sAttrData));
33760     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
33761                              GetFileExInfoStandard,
33762                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
33763     if( !rc ){
33764       return 0; /* Invalid name? */
33765     }
33766     attr = sAttrData.dwFileAttributes;
33767 #if SQLITE_OS_WINCE==0
33768   }else{
33769     attr = osGetFileAttributesA((char*)zConverted);
33770 #endif
33771   }
33772   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
33773 }
33774
33775 /*
33776 ** Open a file.
33777 */
33778 static int winOpen(
33779   sqlite3_vfs *pVfs,        /* Not used */
33780   const char *zName,        /* Name of the file (UTF-8) */
33781   sqlite3_file *id,         /* Write the SQLite file handle here */
33782   int flags,                /* Open mode flags */
33783   int *pOutFlags            /* Status return flags */
33784 ){
33785   HANDLE h;
33786   DWORD lastErrno;
33787   DWORD dwDesiredAccess;
33788   DWORD dwShareMode;
33789   DWORD dwCreationDisposition;
33790   DWORD dwFlagsAndAttributes = 0;
33791 #if SQLITE_OS_WINCE
33792   int isTemp = 0;
33793 #endif
33794   winFile *pFile = (winFile*)id;
33795   void *zConverted;              /* Filename in OS encoding */
33796   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
33797   int cnt = 0;
33798
33799   /* If argument zPath is a NULL pointer, this function is required to open
33800   ** a temporary file. Use this buffer to store the file name in.
33801   */
33802   char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
33803
33804   int rc = SQLITE_OK;            /* Function Return Code */
33805 #if !defined(NDEBUG) || SQLITE_OS_WINCE
33806   int eType = flags&0xFFFFFF00;  /* Type of file to open */
33807 #endif
33808
33809   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
33810   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
33811   int isCreate     = (flags & SQLITE_OPEN_CREATE);
33812 #ifndef NDEBUG
33813   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
33814 #endif
33815   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
33816
33817 #ifndef NDEBUG
33818   int isOpenJournal = (isCreate && (
33819         eType==SQLITE_OPEN_MASTER_JOURNAL 
33820      || eType==SQLITE_OPEN_MAIN_JOURNAL 
33821      || eType==SQLITE_OPEN_WAL
33822   ));
33823 #endif
33824
33825   /* Check the following statements are true: 
33826   **
33827   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
33828   **   (b) if CREATE is set, then READWRITE must also be set, and
33829   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
33830   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
33831   */
33832   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
33833   assert(isCreate==0 || isReadWrite);
33834   assert(isExclusive==0 || isCreate);
33835   assert(isDelete==0 || isCreate);
33836
33837   /* The main DB, main journal, WAL file and master journal are never 
33838   ** automatically deleted. Nor are they ever temporary files.  */
33839   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
33840   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
33841   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
33842   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
33843
33844   /* Assert that the upper layer has set one of the "file-type" flags. */
33845   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
33846        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
33847        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
33848        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
33849   );
33850
33851   assert( pFile!=0 );
33852   memset(pFile, 0, sizeof(winFile));
33853   pFile->h = INVALID_HANDLE_VALUE;
33854
33855 #if SQLITE_OS_WINRT
33856   if( !sqlite3_temp_directory ){
33857     sqlite3_log(SQLITE_ERROR,
33858         "sqlite3_temp_directory variable should be set for WinRT");
33859   }
33860 #endif
33861
33862   /* If the second argument to this function is NULL, generate a 
33863   ** temporary file name to use 
33864   */
33865   if( !zUtf8Name ){
33866     assert(isDelete && !isOpenJournal);
33867     memset(zTmpname, 0, MAX_PATH+2);
33868     rc = getTempname(MAX_PATH+2, zTmpname);
33869     if( rc!=SQLITE_OK ){
33870       return rc;
33871     }
33872     zUtf8Name = zTmpname;
33873   }
33874
33875   /* Database filenames are double-zero terminated if they are not
33876   ** URIs with parameters.  Hence, they can always be passed into
33877   ** sqlite3_uri_parameter().
33878   */
33879   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
33880         zUtf8Name[strlen(zUtf8Name)+1]==0 );
33881
33882   /* Convert the filename to the system encoding. */
33883   zConverted = convertUtf8Filename(zUtf8Name);
33884   if( zConverted==0 ){
33885     return SQLITE_IOERR_NOMEM;
33886   }
33887
33888   if( winIsDir(zConverted) ){
33889     sqlite3_free(zConverted);
33890     return SQLITE_CANTOPEN_ISDIR;
33891   }
33892
33893   if( isReadWrite ){
33894     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
33895   }else{
33896     dwDesiredAccess = GENERIC_READ;
33897   }
33898
33899   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
33900   ** created. SQLite doesn't use it to indicate "exclusive access" 
33901   ** as it is usually understood.
33902   */
33903   if( isExclusive ){
33904     /* Creates a new file, only if it does not already exist. */
33905     /* If the file exists, it fails. */
33906     dwCreationDisposition = CREATE_NEW;
33907   }else if( isCreate ){
33908     /* Open existing file, or create if it doesn't exist */
33909     dwCreationDisposition = OPEN_ALWAYS;
33910   }else{
33911     /* Opens a file, only if it exists. */
33912     dwCreationDisposition = OPEN_EXISTING;
33913   }
33914
33915   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
33916
33917   if( isDelete ){
33918 #if SQLITE_OS_WINCE
33919     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
33920     isTemp = 1;
33921 #else
33922     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
33923                                | FILE_ATTRIBUTE_HIDDEN
33924                                | FILE_FLAG_DELETE_ON_CLOSE;
33925 #endif
33926   }else{
33927     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
33928   }
33929   /* Reports from the internet are that performance is always
33930   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
33931 #if SQLITE_OS_WINCE
33932   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
33933 #endif
33934
33935   if( isNT() ){
33936 #if SQLITE_OS_WINRT
33937     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
33938     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
33939     extendedParameters.dwFileAttributes =
33940             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
33941     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
33942     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
33943     extendedParameters.lpSecurityAttributes = NULL;
33944     extendedParameters.hTemplateFile = NULL;
33945     while( (h = osCreateFile2((LPCWSTR)zConverted,
33946                               dwDesiredAccess,
33947                               dwShareMode,
33948                               dwCreationDisposition,
33949                               &extendedParameters))==INVALID_HANDLE_VALUE &&
33950                               retryIoerr(&cnt, &lastErrno) ){
33951                /* Noop */
33952     }
33953 #else
33954     while( (h = osCreateFileW((LPCWSTR)zConverted,
33955                               dwDesiredAccess,
33956                               dwShareMode, NULL,
33957                               dwCreationDisposition,
33958                               dwFlagsAndAttributes,
33959                               NULL))==INVALID_HANDLE_VALUE &&
33960                               retryIoerr(&cnt, &lastErrno) ){
33961                /* Noop */
33962     }
33963 #endif
33964   }
33965 #ifdef SQLITE_WIN32_HAS_ANSI
33966   else{
33967     while( (h = osCreateFileA((LPCSTR)zConverted,
33968                               dwDesiredAccess,
33969                               dwShareMode, NULL,
33970                               dwCreationDisposition,
33971                               dwFlagsAndAttributes,
33972                               NULL))==INVALID_HANDLE_VALUE &&
33973                               retryIoerr(&cnt, &lastErrno) ){
33974                /* Noop */
33975     }
33976   }
33977 #endif
33978   logIoerr(cnt);
33979
33980   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
33981            h, zName, dwDesiredAccess, 
33982            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
33983
33984   if( h==INVALID_HANDLE_VALUE ){
33985     pFile->lastErrno = lastErrno;
33986     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
33987     sqlite3_free(zConverted);
33988     if( isReadWrite && !isExclusive ){
33989       return winOpen(pVfs, zName, id, 
33990          ((flags|SQLITE_OPEN_READONLY) &
33991                      ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
33992          pOutFlags);
33993     }else{
33994       return SQLITE_CANTOPEN_BKPT;
33995     }
33996   }
33997
33998   if( pOutFlags ){
33999     if( isReadWrite ){
34000       *pOutFlags = SQLITE_OPEN_READWRITE;
34001     }else{
34002       *pOutFlags = SQLITE_OPEN_READONLY;
34003     }
34004   }
34005
34006 #if SQLITE_OS_WINCE
34007   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
34008        && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
34009   ){
34010     osCloseHandle(h);
34011     sqlite3_free(zConverted);
34012     return rc;
34013   }
34014   if( isTemp ){
34015     pFile->zDeleteOnClose = zConverted;
34016   }else
34017 #endif
34018   {
34019     sqlite3_free(zConverted);
34020   }
34021
34022   pFile->pMethod = &winIoMethod;
34023   pFile->pVfs = pVfs;
34024   pFile->h = h;
34025   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
34026     pFile->ctrlFlags |= WINFILE_PSOW;
34027   }
34028   pFile->lastErrno = NO_ERROR;
34029   pFile->zPath = zName;
34030
34031   OpenCounter(+1);
34032   return rc;
34033 }
34034
34035 /*
34036 ** Delete the named file.
34037 **
34038 ** Note that Windows does not allow a file to be deleted if some other
34039 ** process has it open.  Sometimes a virus scanner or indexing program
34040 ** will open a journal file shortly after it is created in order to do
34041 ** whatever it does.  While this other process is holding the
34042 ** file open, we will be unable to delete it.  To work around this
34043 ** problem, we delay 100 milliseconds and try to delete again.  Up
34044 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
34045 ** up and returning an error.
34046 */
34047 static int winDelete(
34048   sqlite3_vfs *pVfs,          /* Not used on win32 */
34049   const char *zFilename,      /* Name of file to delete */
34050   int syncDir                 /* Not used on win32 */
34051 ){
34052   int cnt = 0;
34053   int rc;
34054   DWORD attr;
34055   DWORD lastErrno;
34056   void *zConverted;
34057   UNUSED_PARAMETER(pVfs);
34058   UNUSED_PARAMETER(syncDir);
34059
34060   SimulateIOError(return SQLITE_IOERR_DELETE);
34061   zConverted = convertUtf8Filename(zFilename);
34062   if( zConverted==0 ){
34063     return SQLITE_IOERR_NOMEM;
34064   }
34065   if( isNT() ){
34066     do {
34067 #if SQLITE_OS_WINRT
34068       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
34069       memset(&sAttrData, 0, sizeof(sAttrData));
34070       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
34071                                   &sAttrData) ){
34072         attr = sAttrData.dwFileAttributes;
34073       }else{
34074         lastErrno = osGetLastError();
34075         if( lastErrno==ERROR_FILE_NOT_FOUND
34076          || lastErrno==ERROR_PATH_NOT_FOUND ){
34077           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
34078         }else{
34079           rc = SQLITE_ERROR;
34080         }
34081         break;
34082       }
34083 #else
34084       attr = osGetFileAttributesW(zConverted);
34085 #endif
34086       if ( attr==INVALID_FILE_ATTRIBUTES ){
34087         lastErrno = osGetLastError();
34088         if( lastErrno==ERROR_FILE_NOT_FOUND
34089          || lastErrno==ERROR_PATH_NOT_FOUND ){
34090           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
34091         }else{
34092           rc = SQLITE_ERROR;
34093         }
34094         break;
34095       }
34096       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
34097         rc = SQLITE_ERROR; /* Files only. */
34098         break;
34099       }
34100       if ( osDeleteFileW(zConverted) ){
34101         rc = SQLITE_OK; /* Deleted OK. */
34102         break;
34103       }
34104       if ( !retryIoerr(&cnt, &lastErrno) ){
34105         rc = SQLITE_ERROR; /* No more retries. */
34106         break;
34107       }
34108     } while(1);
34109   }
34110 #ifdef SQLITE_WIN32_HAS_ANSI
34111   else{
34112     do {
34113       attr = osGetFileAttributesA(zConverted);
34114       if ( attr==INVALID_FILE_ATTRIBUTES ){
34115         lastErrno = osGetLastError();
34116         if( lastErrno==ERROR_FILE_NOT_FOUND
34117          || lastErrno==ERROR_PATH_NOT_FOUND ){
34118           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
34119         }else{
34120           rc = SQLITE_ERROR;
34121         }
34122         break;
34123       }
34124       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
34125         rc = SQLITE_ERROR; /* Files only. */
34126         break;
34127       }
34128       if ( osDeleteFileA(zConverted) ){
34129         rc = SQLITE_OK; /* Deleted OK. */
34130         break;
34131       }
34132       if ( !retryIoerr(&cnt, &lastErrno) ){
34133         rc = SQLITE_ERROR; /* No more retries. */
34134         break;
34135       }
34136     } while(1);
34137   }
34138 #endif
34139   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
34140     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
34141              "winDelete", zFilename);
34142   }else{
34143     logIoerr(cnt);
34144   }
34145   sqlite3_free(zConverted);
34146   OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
34147   return rc;
34148 }
34149
34150 /*
34151 ** Check the existence and status of a file.
34152 */
34153 static int winAccess(
34154   sqlite3_vfs *pVfs,         /* Not used on win32 */
34155   const char *zFilename,     /* Name of file to check */
34156   int flags,                 /* Type of test to make on this file */
34157   int *pResOut               /* OUT: Result */
34158 ){
34159   DWORD attr;
34160   int rc = 0;
34161   DWORD lastErrno;
34162   void *zConverted;
34163   UNUSED_PARAMETER(pVfs);
34164
34165   SimulateIOError( return SQLITE_IOERR_ACCESS; );
34166   zConverted = convertUtf8Filename(zFilename);
34167   if( zConverted==0 ){
34168     return SQLITE_IOERR_NOMEM;
34169   }
34170   if( isNT() ){
34171     int cnt = 0;
34172     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
34173     memset(&sAttrData, 0, sizeof(sAttrData));
34174     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
34175                              GetFileExInfoStandard, 
34176                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
34177     if( rc ){
34178       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
34179       ** as if it does not exist.
34180       */
34181       if(    flags==SQLITE_ACCESS_EXISTS
34182           && sAttrData.nFileSizeHigh==0 
34183           && sAttrData.nFileSizeLow==0 ){
34184         attr = INVALID_FILE_ATTRIBUTES;
34185       }else{
34186         attr = sAttrData.dwFileAttributes;
34187       }
34188     }else{
34189       logIoerr(cnt);
34190       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
34191         winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
34192         sqlite3_free(zConverted);
34193         return SQLITE_IOERR_ACCESS;
34194       }else{
34195         attr = INVALID_FILE_ATTRIBUTES;
34196       }
34197     }
34198   }
34199 #ifdef SQLITE_WIN32_HAS_ANSI
34200   else{
34201     attr = osGetFileAttributesA((char*)zConverted);
34202   }
34203 #endif
34204   sqlite3_free(zConverted);
34205   switch( flags ){
34206     case SQLITE_ACCESS_READ:
34207     case SQLITE_ACCESS_EXISTS:
34208       rc = attr!=INVALID_FILE_ATTRIBUTES;
34209       break;
34210     case SQLITE_ACCESS_READWRITE:
34211       rc = attr!=INVALID_FILE_ATTRIBUTES &&
34212              (attr & FILE_ATTRIBUTE_READONLY)==0;
34213       break;
34214     default:
34215       assert(!"Invalid flags argument");
34216   }
34217   *pResOut = rc;
34218   return SQLITE_OK;
34219 }
34220
34221
34222 /*
34223 ** Returns non-zero if the specified path name should be used verbatim.  If
34224 ** non-zero is returned from this function, the calling function must simply
34225 ** use the provided path name verbatim -OR- resolve it into a full path name
34226 ** using the GetFullPathName Win32 API function (if available).
34227 */
34228 static BOOL winIsVerbatimPathname(
34229   const char *zPathname
34230 ){
34231   /*
34232   ** If the path name starts with a forward slash or a backslash, it is either
34233   ** a legal UNC name, a volume relative path, or an absolute path name in the
34234   ** "Unix" format on Windows.  There is no easy way to differentiate between
34235   ** the final two cases; therefore, we return the safer return value of TRUE
34236   ** so that callers of this function will simply use it verbatim.
34237   */
34238   if ( zPathname[0]=='/' || zPathname[0]=='\\' ){
34239     return TRUE;
34240   }
34241
34242   /*
34243   ** If the path name starts with a letter and a colon it is either a volume
34244   ** relative path or an absolute path.  Callers of this function must not
34245   ** attempt to treat it as a relative path name (i.e. they should simply use
34246   ** it verbatim).
34247   */
34248   if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){
34249     return TRUE;
34250   }
34251
34252   /*
34253   ** If we get to this point, the path name should almost certainly be a purely
34254   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
34255   */
34256   return FALSE;
34257 }
34258
34259 /*
34260 ** Turn a relative pathname into a full pathname.  Write the full
34261 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
34262 ** bytes in size.
34263 */
34264 static int winFullPathname(
34265   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
34266   const char *zRelative,        /* Possibly relative input path */
34267   int nFull,                    /* Size of output buffer in bytes */
34268   char *zFull                   /* Output buffer */
34269 ){
34270   
34271 #if defined(__CYGWIN__)
34272   SimulateIOError( return SQLITE_ERROR );
34273   UNUSED_PARAMETER(nFull);
34274   assert( pVfs->mxPathname>=MAX_PATH );
34275   assert( nFull>=pVfs->mxPathname );
34276   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
34277     /*
34278     ** NOTE: We are dealing with a relative path name and the data
34279     **       directory has been set.  Therefore, use it as the basis
34280     **       for converting the relative path name to an absolute
34281     **       one by prepending the data directory and a slash.
34282     */
34283     char zOut[MAX_PATH+1];
34284     memset(zOut, 0, MAX_PATH+1);
34285     cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
34286                      MAX_PATH+1);
34287     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
34288                      sqlite3_data_directory, zOut);
34289   }else{
34290     cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull);
34291   }
34292   return SQLITE_OK;
34293 #endif
34294
34295 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
34296   SimulateIOError( return SQLITE_ERROR );
34297   /* WinCE has no concept of a relative pathname, or so I am told. */
34298   /* WinRT has no way to convert a relative path to an absolute one. */
34299   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
34300     /*
34301     ** NOTE: We are dealing with a relative path name and the data
34302     **       directory has been set.  Therefore, use it as the basis
34303     **       for converting the relative path name to an absolute
34304     **       one by prepending the data directory and a backslash.
34305     */
34306     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
34307                      sqlite3_data_directory, zRelative);
34308   }else{
34309     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
34310   }
34311   return SQLITE_OK;
34312 #endif
34313
34314 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
34315   DWORD nByte;
34316   void *zConverted;
34317   char *zOut;
34318
34319   /* If this path name begins with "/X:", where "X" is any alphabetic
34320   ** character, discard the initial "/" from the pathname.
34321   */
34322   if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
34323     zRelative++;
34324   }
34325
34326   /* It's odd to simulate an io-error here, but really this is just
34327   ** using the io-error infrastructure to test that SQLite handles this
34328   ** function failing. This function could fail if, for example, the
34329   ** current working directory has been unlinked.
34330   */
34331   SimulateIOError( return SQLITE_ERROR );
34332   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
34333     /*
34334     ** NOTE: We are dealing with a relative path name and the data
34335     **       directory has been set.  Therefore, use it as the basis
34336     **       for converting the relative path name to an absolute
34337     **       one by prepending the data directory and a backslash.
34338     */
34339     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
34340                      sqlite3_data_directory, zRelative);
34341     return SQLITE_OK;
34342   }
34343   zConverted = convertUtf8Filename(zRelative);
34344   if( zConverted==0 ){
34345     return SQLITE_IOERR_NOMEM;
34346   }
34347   if( isNT() ){
34348     LPWSTR zTemp;
34349     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
34350     if( nByte==0 ){
34351       winLogError(SQLITE_ERROR, osGetLastError(),
34352                   "GetFullPathNameW1", zConverted);
34353       sqlite3_free(zConverted);
34354       return SQLITE_CANTOPEN_FULLPATH;
34355     }
34356     nByte += 3;
34357     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
34358     if( zTemp==0 ){
34359       sqlite3_free(zConverted);
34360       return SQLITE_IOERR_NOMEM;
34361     }
34362     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
34363     if( nByte==0 ){
34364       winLogError(SQLITE_ERROR, osGetLastError(),
34365                   "GetFullPathNameW2", zConverted);
34366       sqlite3_free(zConverted);
34367       sqlite3_free(zTemp);
34368       return SQLITE_CANTOPEN_FULLPATH;
34369     }
34370     sqlite3_free(zConverted);
34371     zOut = unicodeToUtf8(zTemp);
34372     sqlite3_free(zTemp);
34373   }
34374 #ifdef SQLITE_WIN32_HAS_ANSI
34375   else{
34376     char *zTemp;
34377     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
34378     if( nByte==0 ){
34379       winLogError(SQLITE_ERROR, osGetLastError(),
34380                   "GetFullPathNameA1", zConverted);
34381       sqlite3_free(zConverted);
34382       return SQLITE_CANTOPEN_FULLPATH;
34383     }
34384     nByte += 3;
34385     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
34386     if( zTemp==0 ){
34387       sqlite3_free(zConverted);
34388       return SQLITE_IOERR_NOMEM;
34389     }
34390     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
34391     if( nByte==0 ){
34392       winLogError(SQLITE_ERROR, osGetLastError(),
34393                   "GetFullPathNameA2", zConverted);
34394       sqlite3_free(zConverted);
34395       sqlite3_free(zTemp);
34396       return SQLITE_CANTOPEN_FULLPATH;
34397     }
34398     sqlite3_free(zConverted);
34399     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
34400     sqlite3_free(zTemp);
34401   }
34402 #endif
34403   if( zOut ){
34404     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
34405     sqlite3_free(zOut);
34406     return SQLITE_OK;
34407   }else{
34408     return SQLITE_IOERR_NOMEM;
34409   }
34410 #endif
34411 }
34412
34413 #ifndef SQLITE_OMIT_LOAD_EXTENSION
34414 /*
34415 ** Interfaces for opening a shared library, finding entry points
34416 ** within the shared library, and closing the shared library.
34417 */
34418 /*
34419 ** Interfaces for opening a shared library, finding entry points
34420 ** within the shared library, and closing the shared library.
34421 */
34422 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
34423   HANDLE h;
34424   void *zConverted = convertUtf8Filename(zFilename);
34425   UNUSED_PARAMETER(pVfs);
34426   if( zConverted==0 ){
34427     return 0;
34428   }
34429   if( isNT() ){
34430 #if SQLITE_OS_WINRT
34431     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
34432 #else
34433     h = osLoadLibraryW((LPCWSTR)zConverted);
34434 #endif
34435   }
34436 #ifdef SQLITE_WIN32_HAS_ANSI
34437   else{
34438     h = osLoadLibraryA((char*)zConverted);
34439   }
34440 #endif
34441   sqlite3_free(zConverted);
34442   return (void*)h;
34443 }
34444 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
34445   UNUSED_PARAMETER(pVfs);
34446   getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
34447 }
34448 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
34449   UNUSED_PARAMETER(pVfs);
34450   return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
34451 }
34452 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
34453   UNUSED_PARAMETER(pVfs);
34454   osFreeLibrary((HANDLE)pHandle);
34455 }
34456 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
34457   #define winDlOpen  0
34458   #define winDlError 0
34459   #define winDlSym   0
34460   #define winDlClose 0
34461 #endif
34462
34463
34464 /*
34465 ** Write up to nBuf bytes of randomness into zBuf.
34466 */
34467 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34468   int n = 0;
34469   UNUSED_PARAMETER(pVfs);
34470 #if defined(SQLITE_TEST)
34471   n = nBuf;
34472   memset(zBuf, 0, nBuf);
34473 #else
34474   if( sizeof(SYSTEMTIME)<=nBuf-n ){
34475     SYSTEMTIME x;
34476     osGetSystemTime(&x);
34477     memcpy(&zBuf[n], &x, sizeof(x));
34478     n += sizeof(x);
34479   }
34480   if( sizeof(DWORD)<=nBuf-n ){
34481     DWORD pid = osGetCurrentProcessId();
34482     memcpy(&zBuf[n], &pid, sizeof(pid));
34483     n += sizeof(pid);
34484   }
34485 #if SQLITE_OS_WINRT
34486   if( sizeof(ULONGLONG)<=nBuf-n ){
34487     ULONGLONG cnt = osGetTickCount64();
34488     memcpy(&zBuf[n], &cnt, sizeof(cnt));
34489     n += sizeof(cnt);
34490   }
34491 #else
34492   if( sizeof(DWORD)<=nBuf-n ){
34493     DWORD cnt = osGetTickCount();
34494     memcpy(&zBuf[n], &cnt, sizeof(cnt));
34495     n += sizeof(cnt);
34496   }
34497 #endif
34498   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
34499     LARGE_INTEGER i;
34500     osQueryPerformanceCounter(&i);
34501     memcpy(&zBuf[n], &i, sizeof(i));
34502     n += sizeof(i);
34503   }
34504 #endif
34505   return n;
34506 }
34507
34508
34509 /*
34510 ** Sleep for a little while.  Return the amount of time slept.
34511 */
34512 static int winSleep(sqlite3_vfs *pVfs, int microsec){
34513   sqlite3_win32_sleep((microsec+999)/1000);
34514   UNUSED_PARAMETER(pVfs);
34515   return ((microsec+999)/1000)*1000;
34516 }
34517
34518 /*
34519 ** The following variable, if set to a non-zero value, is interpreted as
34520 ** the number of seconds since 1970 and is used to set the result of
34521 ** sqlite3OsCurrentTime() during testing.
34522 */
34523 #ifdef SQLITE_TEST
34524 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
34525 #endif
34526
34527 /*
34528 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
34529 ** the current time and date as a Julian Day number times 86_400_000.  In
34530 ** other words, write into *piNow the number of milliseconds since the Julian
34531 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
34532 ** proleptic Gregorian calendar.
34533 **
34534 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
34535 ** cannot be found.
34536 */
34537 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
34538   /* FILETIME structure is a 64-bit value representing the number of 
34539      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
34540   */
34541   FILETIME ft;
34542   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
34543 #ifdef SQLITE_TEST
34544   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
34545 #endif
34546   /* 2^32 - to avoid use of LL and warnings in gcc */
34547   static const sqlite3_int64 max32BitValue = 
34548       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
34549       (sqlite3_int64)294967296;
34550
34551 #if SQLITE_OS_WINCE
34552   SYSTEMTIME time;
34553   osGetSystemTime(&time);
34554   /* if SystemTimeToFileTime() fails, it returns zero. */
34555   if (!osSystemTimeToFileTime(&time,&ft)){
34556     return SQLITE_ERROR;
34557   }
34558 #else
34559   osGetSystemTimeAsFileTime( &ft );
34560 #endif
34561
34562   *piNow = winFiletimeEpoch +
34563             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
34564                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
34565
34566 #ifdef SQLITE_TEST
34567   if( sqlite3_current_time ){
34568     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
34569   }
34570 #endif
34571   UNUSED_PARAMETER(pVfs);
34572   return SQLITE_OK;
34573 }
34574
34575 /*
34576 ** Find the current time (in Universal Coordinated Time).  Write the
34577 ** current time and date as a Julian Day number into *prNow and
34578 ** return 0.  Return 1 if the time and date cannot be found.
34579 */
34580 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
34581   int rc;
34582   sqlite3_int64 i;
34583   rc = winCurrentTimeInt64(pVfs, &i);
34584   if( !rc ){
34585     *prNow = i/86400000.0;
34586   }
34587   return rc;
34588 }
34589
34590 /*
34591 ** The idea is that this function works like a combination of
34592 ** GetLastError() and FormatMessage() on Windows (or errno and
34593 ** strerror_r() on Unix). After an error is returned by an OS
34594 ** function, SQLite calls this function with zBuf pointing to
34595 ** a buffer of nBuf bytes. The OS layer should populate the
34596 ** buffer with a nul-terminated UTF-8 encoded error message
34597 ** describing the last IO error to have occurred within the calling
34598 ** thread.
34599 **
34600 ** If the error message is too large for the supplied buffer,
34601 ** it should be truncated. The return value of xGetLastError
34602 ** is zero if the error message fits in the buffer, or non-zero
34603 ** otherwise (if the message was truncated). If non-zero is returned,
34604 ** then it is not necessary to include the nul-terminator character
34605 ** in the output buffer.
34606 **
34607 ** Not supplying an error message will have no adverse effect
34608 ** on SQLite. It is fine to have an implementation that never
34609 ** returns an error message:
34610 **
34611 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34612 **     assert(zBuf[0]=='\0');
34613 **     return 0;
34614 **   }
34615 **
34616 ** However if an error message is supplied, it will be incorporated
34617 ** by sqlite into the error message available to the user using
34618 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
34619 */
34620 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34621   UNUSED_PARAMETER(pVfs);
34622   return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
34623 }
34624
34625 /*
34626 ** Initialize and deinitialize the operating system interface.
34627 */
34628 SQLITE_API int sqlite3_os_init(void){
34629   static sqlite3_vfs winVfs = {
34630     3,                   /* iVersion */
34631     sizeof(winFile),     /* szOsFile */
34632     MAX_PATH,            /* mxPathname */
34633     0,                   /* pNext */
34634     "win32",             /* zName */
34635     0,                   /* pAppData */
34636     winOpen,             /* xOpen */
34637     winDelete,           /* xDelete */
34638     winAccess,           /* xAccess */
34639     winFullPathname,     /* xFullPathname */
34640     winDlOpen,           /* xDlOpen */
34641     winDlError,          /* xDlError */
34642     winDlSym,            /* xDlSym */
34643     winDlClose,          /* xDlClose */
34644     winRandomness,       /* xRandomness */
34645     winSleep,            /* xSleep */
34646     winCurrentTime,      /* xCurrentTime */
34647     winGetLastError,     /* xGetLastError */
34648     winCurrentTimeInt64, /* xCurrentTimeInt64 */
34649     winSetSystemCall,    /* xSetSystemCall */
34650     winGetSystemCall,    /* xGetSystemCall */
34651     winNextSystemCall,   /* xNextSystemCall */
34652   };
34653
34654   /* Double-check that the aSyscall[] array has been constructed
34655   ** correctly.  See ticket [bb3a86e890c8e96ab] */
34656   assert( ArraySize(aSyscall)==74 );
34657
34658 #ifndef SQLITE_OMIT_WAL
34659   /* get memory map allocation granularity */
34660   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
34661 #if SQLITE_OS_WINRT
34662   osGetNativeSystemInfo(&winSysInfo);
34663 #else
34664   osGetSystemInfo(&winSysInfo);
34665 #endif
34666   assert(winSysInfo.dwAllocationGranularity > 0);
34667 #endif
34668
34669   sqlite3_vfs_register(&winVfs, 1);
34670   return SQLITE_OK; 
34671 }
34672
34673 SQLITE_API int sqlite3_os_end(void){ 
34674 #if SQLITE_OS_WINRT
34675   if( sleepObj!=NULL ){
34676     osCloseHandle(sleepObj);
34677     sleepObj = NULL;
34678   }
34679 #endif
34680   return SQLITE_OK;
34681 }
34682
34683 #endif /* SQLITE_OS_WIN */
34684
34685 /************** End of os_win.c **********************************************/
34686 /************** Begin file bitvec.c ******************************************/
34687 /*
34688 ** 2008 February 16
34689 **
34690 ** The author disclaims copyright to this source code.  In place of
34691 ** a legal notice, here is a blessing:
34692 **
34693 **    May you do good and not evil.
34694 **    May you find forgiveness for yourself and forgive others.
34695 **    May you share freely, never taking more than you give.
34696 **
34697 *************************************************************************
34698 ** This file implements an object that represents a fixed-length
34699 ** bitmap.  Bits are numbered starting with 1.
34700 **
34701 ** A bitmap is used to record which pages of a database file have been
34702 ** journalled during a transaction, or which pages have the "dont-write"
34703 ** property.  Usually only a few pages are meet either condition.
34704 ** So the bitmap is usually sparse and has low cardinality.
34705 ** But sometimes (for example when during a DROP of a large table) most
34706 ** or all of the pages in a database can get journalled.  In those cases, 
34707 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
34708 ** to handle both cases well.
34709 **
34710 ** The size of the bitmap is fixed when the object is created.
34711 **
34712 ** All bits are clear when the bitmap is created.  Individual bits
34713 ** may be set or cleared one at a time.
34714 **
34715 ** Test operations are about 100 times more common that set operations.
34716 ** Clear operations are exceedingly rare.  There are usually between
34717 ** 5 and 500 set operations per Bitvec object, though the number of sets can
34718 ** sometimes grow into tens of thousands or larger.  The size of the
34719 ** Bitvec object is the number of pages in the database file at the
34720 ** start of a transaction, and is thus usually less than a few thousand,
34721 ** but can be as large as 2 billion for a really big database.
34722 */
34723
34724 /* Size of the Bitvec structure in bytes. */
34725 #define BITVEC_SZ        512
34726
34727 /* Round the union size down to the nearest pointer boundary, since that's how 
34728 ** it will be aligned within the Bitvec struct. */
34729 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
34730
34731 /* Type of the array "element" for the bitmap representation. 
34732 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
34733 ** Setting this to the "natural word" size of your CPU may improve
34734 ** performance. */
34735 #define BITVEC_TELEM     u8
34736 /* Size, in bits, of the bitmap element. */
34737 #define BITVEC_SZELEM    8
34738 /* Number of elements in a bitmap array. */
34739 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
34740 /* Number of bits in the bitmap array. */
34741 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
34742
34743 /* Number of u32 values in hash table. */
34744 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
34745 /* Maximum number of entries in hash table before 
34746 ** sub-dividing and re-hashing. */
34747 #define BITVEC_MXHASH    (BITVEC_NINT/2)
34748 /* Hashing function for the aHash representation.
34749 ** Empirical testing showed that the *37 multiplier 
34750 ** (an arbitrary prime)in the hash function provided 
34751 ** no fewer collisions than the no-op *1. */
34752 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
34753
34754 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
34755
34756
34757 /*
34758 ** A bitmap is an instance of the following structure.
34759 **
34760 ** This bitmap records the existence of zero or more bits
34761 ** with values between 1 and iSize, inclusive.
34762 **
34763 ** There are three possible representations of the bitmap.
34764 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
34765 ** bitmap.  The least significant bit is bit 1.
34766 **
34767 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
34768 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
34769 **
34770 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
34771 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
34772 ** handles up to iDivisor separate values of i.  apSub[0] holds
34773 ** values between 1 and iDivisor.  apSub[1] holds values between
34774 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
34775 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
34776 ** to hold deal with values between 1 and iDivisor.
34777 */
34778 struct Bitvec {
34779   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
34780   u32 nSet;       /* Number of bits that are set - only valid for aHash
34781                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
34782                   ** this would be 125. */
34783   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
34784                   /* Should >=0 for apSub element. */
34785                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
34786                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
34787   union {
34788     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
34789     u32 aHash[BITVEC_NINT];      /* Hash table representation */
34790     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
34791   } u;
34792 };
34793
34794 /*
34795 ** Create a new bitmap object able to handle bits between 0 and iSize,
34796 ** inclusive.  Return a pointer to the new object.  Return NULL if 
34797 ** malloc fails.
34798 */
34799 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
34800   Bitvec *p;
34801   assert( sizeof(*p)==BITVEC_SZ );
34802   p = sqlite3MallocZero( sizeof(*p) );
34803   if( p ){
34804     p->iSize = iSize;
34805   }
34806   return p;
34807 }
34808
34809 /*
34810 ** Check to see if the i-th bit is set.  Return true or false.
34811 ** If p is NULL (if the bitmap has not been created) or if
34812 ** i is out of range, then return false.
34813 */
34814 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
34815   if( p==0 ) return 0;
34816   if( i>p->iSize || i==0 ) return 0;
34817   i--;
34818   while( p->iDivisor ){
34819     u32 bin = i/p->iDivisor;
34820     i = i%p->iDivisor;
34821     p = p->u.apSub[bin];
34822     if (!p) {
34823       return 0;
34824     }
34825   }
34826   if( p->iSize<=BITVEC_NBIT ){
34827     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
34828   } else{
34829     u32 h = BITVEC_HASH(i++);
34830     while( p->u.aHash[h] ){
34831       if( p->u.aHash[h]==i ) return 1;
34832       h = (h+1) % BITVEC_NINT;
34833     }
34834     return 0;
34835   }
34836 }
34837
34838 /*
34839 ** Set the i-th bit.  Return 0 on success and an error code if
34840 ** anything goes wrong.
34841 **
34842 ** This routine might cause sub-bitmaps to be allocated.  Failing
34843 ** to get the memory needed to hold the sub-bitmap is the only
34844 ** that can go wrong with an insert, assuming p and i are valid.
34845 **
34846 ** The calling function must ensure that p is a valid Bitvec object
34847 ** and that the value for "i" is within range of the Bitvec object.
34848 ** Otherwise the behavior is undefined.
34849 */
34850 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
34851   u32 h;
34852   if( p==0 ) return SQLITE_OK;
34853   assert( i>0 );
34854   assert( i<=p->iSize );
34855   i--;
34856   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
34857     u32 bin = i/p->iDivisor;
34858     i = i%p->iDivisor;
34859     if( p->u.apSub[bin]==0 ){
34860       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
34861       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
34862     }
34863     p = p->u.apSub[bin];
34864   }
34865   if( p->iSize<=BITVEC_NBIT ){
34866     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
34867     return SQLITE_OK;
34868   }
34869   h = BITVEC_HASH(i++);
34870   /* if there wasn't a hash collision, and this doesn't */
34871   /* completely fill the hash, then just add it without */
34872   /* worring about sub-dividing and re-hashing. */
34873   if( !p->u.aHash[h] ){
34874     if (p->nSet<(BITVEC_NINT-1)) {
34875       goto bitvec_set_end;
34876     } else {
34877       goto bitvec_set_rehash;
34878     }
34879   }
34880   /* there was a collision, check to see if it's already */
34881   /* in hash, if not, try to find a spot for it */
34882   do {
34883     if( p->u.aHash[h]==i ) return SQLITE_OK;
34884     h++;
34885     if( h>=BITVEC_NINT ) h = 0;
34886   } while( p->u.aHash[h] );
34887   /* we didn't find it in the hash.  h points to the first */
34888   /* available free spot. check to see if this is going to */
34889   /* make our hash too "full".  */
34890 bitvec_set_rehash:
34891   if( p->nSet>=BITVEC_MXHASH ){
34892     unsigned int j;
34893     int rc;
34894     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
34895     if( aiValues==0 ){
34896       return SQLITE_NOMEM;
34897     }else{
34898       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34899       memset(p->u.apSub, 0, sizeof(p->u.apSub));
34900       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
34901       rc = sqlite3BitvecSet(p, i);
34902       for(j=0; j<BITVEC_NINT; j++){
34903         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
34904       }
34905       sqlite3StackFree(0, aiValues);
34906       return rc;
34907     }
34908   }
34909 bitvec_set_end:
34910   p->nSet++;
34911   p->u.aHash[h] = i;
34912   return SQLITE_OK;
34913 }
34914
34915 /*
34916 ** Clear the i-th bit.
34917 **
34918 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
34919 ** that BitvecClear can use to rebuilt its hash table.
34920 */
34921 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
34922   if( p==0 ) return;
34923   assert( i>0 );
34924   i--;
34925   while( p->iDivisor ){
34926     u32 bin = i/p->iDivisor;
34927     i = i%p->iDivisor;
34928     p = p->u.apSub[bin];
34929     if (!p) {
34930       return;
34931     }
34932   }
34933   if( p->iSize<=BITVEC_NBIT ){
34934     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
34935   }else{
34936     unsigned int j;
34937     u32 *aiValues = pBuf;
34938     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34939     memset(p->u.aHash, 0, sizeof(p->u.aHash));
34940     p->nSet = 0;
34941     for(j=0; j<BITVEC_NINT; j++){
34942       if( aiValues[j] && aiValues[j]!=(i+1) ){
34943         u32 h = BITVEC_HASH(aiValues[j]-1);
34944         p->nSet++;
34945         while( p->u.aHash[h] ){
34946           h++;
34947           if( h>=BITVEC_NINT ) h = 0;
34948         }
34949         p->u.aHash[h] = aiValues[j];
34950       }
34951     }
34952   }
34953 }
34954
34955 /*
34956 ** Destroy a bitmap object.  Reclaim all memory used.
34957 */
34958 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
34959   if( p==0 ) return;
34960   if( p->iDivisor ){
34961     unsigned int i;
34962     for(i=0; i<BITVEC_NPTR; i++){
34963       sqlite3BitvecDestroy(p->u.apSub[i]);
34964     }
34965   }
34966   sqlite3_free(p);
34967 }
34968
34969 /*
34970 ** Return the value of the iSize parameter specified when Bitvec *p
34971 ** was created.
34972 */
34973 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
34974   return p->iSize;
34975 }
34976
34977 #ifndef SQLITE_OMIT_BUILTIN_TEST
34978 /*
34979 ** Let V[] be an array of unsigned characters sufficient to hold
34980 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
34981 ** Then the following macros can be used to set, clear, or test
34982 ** individual bits within V.
34983 */
34984 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
34985 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
34986 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
34987
34988 /*
34989 ** This routine runs an extensive test of the Bitvec code.
34990 **
34991 ** The input is an array of integers that acts as a program
34992 ** to test the Bitvec.  The integers are opcodes followed
34993 ** by 0, 1, or 3 operands, depending on the opcode.  Another
34994 ** opcode follows immediately after the last operand.
34995 **
34996 ** There are 6 opcodes numbered from 0 through 5.  0 is the
34997 ** "halt" opcode and causes the test to end.
34998 **
34999 **    0          Halt and return the number of errors
35000 **    1 N S X    Set N bits beginning with S and incrementing by X
35001 **    2 N S X    Clear N bits beginning with S and incrementing by X
35002 **    3 N        Set N randomly chosen bits
35003 **    4 N        Clear N randomly chosen bits
35004 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
35005 **
35006 ** The opcodes 1 through 4 perform set and clear operations are performed
35007 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
35008 ** Opcode 5 works on the linear array only, not on the Bitvec.
35009 ** Opcode 5 is used to deliberately induce a fault in order to
35010 ** confirm that error detection works.
35011 **
35012 ** At the conclusion of the test the linear array is compared
35013 ** against the Bitvec object.  If there are any differences,
35014 ** an error is returned.  If they are the same, zero is returned.
35015 **
35016 ** If a memory allocation error occurs, return -1.
35017 */
35018 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
35019   Bitvec *pBitvec = 0;
35020   unsigned char *pV = 0;
35021   int rc = -1;
35022   int i, nx, pc, op;
35023   void *pTmpSpace;
35024
35025   /* Allocate the Bitvec to be tested and a linear array of
35026   ** bits to act as the reference */
35027   pBitvec = sqlite3BitvecCreate( sz );
35028   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
35029   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
35030   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
35031
35032   /* NULL pBitvec tests */
35033   sqlite3BitvecSet(0, 1);
35034   sqlite3BitvecClear(0, 1, pTmpSpace);
35035
35036   /* Run the program */
35037   pc = 0;
35038   while( (op = aOp[pc])!=0 ){
35039     switch( op ){
35040       case 1:
35041       case 2:
35042       case 5: {
35043         nx = 4;
35044         i = aOp[pc+2] - 1;
35045         aOp[pc+2] += aOp[pc+3];
35046         break;
35047       }
35048       case 3:
35049       case 4: 
35050       default: {
35051         nx = 2;
35052         sqlite3_randomness(sizeof(i), &i);
35053         break;
35054       }
35055     }
35056     if( (--aOp[pc+1]) > 0 ) nx = 0;
35057     pc += nx;
35058     i = (i & 0x7fffffff)%sz;
35059     if( (op & 1)!=0 ){
35060       SETBIT(pV, (i+1));
35061       if( op!=5 ){
35062         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
35063       }
35064     }else{
35065       CLEARBIT(pV, (i+1));
35066       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
35067     }
35068   }
35069
35070   /* Test to make sure the linear array exactly matches the
35071   ** Bitvec object.  Start with the assumption that they do
35072   ** match (rc==0).  Change rc to non-zero if a discrepancy
35073   ** is found.
35074   */
35075   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
35076           + sqlite3BitvecTest(pBitvec, 0)
35077           + (sqlite3BitvecSize(pBitvec) - sz);
35078   for(i=1; i<=sz; i++){
35079     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
35080       rc = i;
35081       break;
35082     }
35083   }
35084
35085   /* Free allocated structure */
35086 bitvec_end:
35087   sqlite3_free(pTmpSpace);
35088   sqlite3_free(pV);
35089   sqlite3BitvecDestroy(pBitvec);
35090   return rc;
35091 }
35092 #endif /* SQLITE_OMIT_BUILTIN_TEST */
35093
35094 /************** End of bitvec.c **********************************************/
35095 /************** Begin file pcache.c ******************************************/
35096 /*
35097 ** 2008 August 05
35098 **
35099 ** The author disclaims copyright to this source code.  In place of
35100 ** a legal notice, here is a blessing:
35101 **
35102 **    May you do good and not evil.
35103 **    May you find forgiveness for yourself and forgive others.
35104 **    May you share freely, never taking more than you give.
35105 **
35106 *************************************************************************
35107 ** This file implements that page cache.
35108 */
35109
35110 /*
35111 ** A complete page cache is an instance of this structure.
35112 */
35113 struct PCache {
35114   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
35115   PgHdr *pSynced;                     /* Last synced page in dirty page list */
35116   int nRef;                           /* Number of referenced pages */
35117   int szCache;                        /* Configured cache size */
35118   int szPage;                         /* Size of every page in this cache */
35119   int szExtra;                        /* Size of extra space for each page */
35120   int bPurgeable;                     /* True if pages are on backing store */
35121   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
35122   void *pStress;                      /* Argument to xStress */
35123   sqlite3_pcache *pCache;             /* Pluggable cache module */
35124   PgHdr *pPage1;                      /* Reference to page 1 */
35125 };
35126
35127 /*
35128 ** Some of the assert() macros in this code are too expensive to run
35129 ** even during normal debugging.  Use them only rarely on long-running
35130 ** tests.  Enable the expensive asserts using the
35131 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
35132 */
35133 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
35134 # define expensive_assert(X)  assert(X)
35135 #else
35136 # define expensive_assert(X)
35137 #endif
35138
35139 /********************************** Linked List Management ********************/
35140
35141 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
35142 /*
35143 ** Check that the pCache->pSynced variable is set correctly. If it
35144 ** is not, either fail an assert or return zero. Otherwise, return
35145 ** non-zero. This is only used in debugging builds, as follows:
35146 **
35147 **   expensive_assert( pcacheCheckSynced(pCache) );
35148 */
35149 static int pcacheCheckSynced(PCache *pCache){
35150   PgHdr *p;
35151   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
35152     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
35153   }
35154   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
35155 }
35156 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
35157
35158 /*
35159 ** Remove page pPage from the list of dirty pages.
35160 */
35161 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
35162   PCache *p = pPage->pCache;
35163
35164   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
35165   assert( pPage->pDirtyPrev || pPage==p->pDirty );
35166
35167   /* Update the PCache1.pSynced variable if necessary. */
35168   if( p->pSynced==pPage ){
35169     PgHdr *pSynced = pPage->pDirtyPrev;
35170     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
35171       pSynced = pSynced->pDirtyPrev;
35172     }
35173     p->pSynced = pSynced;
35174   }
35175
35176   if( pPage->pDirtyNext ){
35177     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
35178   }else{
35179     assert( pPage==p->pDirtyTail );
35180     p->pDirtyTail = pPage->pDirtyPrev;
35181   }
35182   if( pPage->pDirtyPrev ){
35183     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
35184   }else{
35185     assert( pPage==p->pDirty );
35186     p->pDirty = pPage->pDirtyNext;
35187   }
35188   pPage->pDirtyNext = 0;
35189   pPage->pDirtyPrev = 0;
35190
35191   expensive_assert( pcacheCheckSynced(p) );
35192 }
35193
35194 /*
35195 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
35196 ** pPage).
35197 */
35198 static void pcacheAddToDirtyList(PgHdr *pPage){
35199   PCache *p = pPage->pCache;
35200
35201   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
35202
35203   pPage->pDirtyNext = p->pDirty;
35204   if( pPage->pDirtyNext ){
35205     assert( pPage->pDirtyNext->pDirtyPrev==0 );
35206     pPage->pDirtyNext->pDirtyPrev = pPage;
35207   }
35208   p->pDirty = pPage;
35209   if( !p->pDirtyTail ){
35210     p->pDirtyTail = pPage;
35211   }
35212   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
35213     p->pSynced = pPage;
35214   }
35215   expensive_assert( pcacheCheckSynced(p) );
35216 }
35217
35218 /*
35219 ** Wrapper around the pluggable caches xUnpin method. If the cache is
35220 ** being used for an in-memory database, this function is a no-op.
35221 */
35222 static void pcacheUnpin(PgHdr *p){
35223   PCache *pCache = p->pCache;
35224   if( pCache->bPurgeable ){
35225     if( p->pgno==1 ){
35226       pCache->pPage1 = 0;
35227     }
35228     sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
35229   }
35230 }
35231
35232 /*************************************************** General Interfaces ******
35233 **
35234 ** Initialize and shutdown the page cache subsystem. Neither of these 
35235 ** functions are threadsafe.
35236 */
35237 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
35238   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
35239     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
35240     ** built-in default page cache is used instead of the application defined
35241     ** page cache. */
35242     sqlite3PCacheSetDefault();
35243   }
35244   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
35245 }
35246 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
35247   if( sqlite3GlobalConfig.pcache2.xShutdown ){
35248     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
35249     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
35250   }
35251 }
35252
35253 /*
35254 ** Return the size in bytes of a PCache object.
35255 */
35256 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
35257
35258 /*
35259 ** Create a new PCache object. Storage space to hold the object
35260 ** has already been allocated and is passed in as the p pointer. 
35261 ** The caller discovers how much space needs to be allocated by 
35262 ** calling sqlite3PcacheSize().
35263 */
35264 SQLITE_PRIVATE void sqlite3PcacheOpen(
35265   int szPage,                  /* Size of every page */
35266   int szExtra,                 /* Extra space associated with each page */
35267   int bPurgeable,              /* True if pages are on backing store */
35268   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
35269   void *pStress,               /* Argument to xStress */
35270   PCache *p                    /* Preallocated space for the PCache */
35271 ){
35272   memset(p, 0, sizeof(PCache));
35273   p->szPage = szPage;
35274   p->szExtra = szExtra;
35275   p->bPurgeable = bPurgeable;
35276   p->xStress = xStress;
35277   p->pStress = pStress;
35278   p->szCache = 100;
35279 }
35280
35281 /*
35282 ** Change the page size for PCache object. The caller must ensure that there
35283 ** are no outstanding page references when this function is called.
35284 */
35285 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
35286   assert( pCache->nRef==0 && pCache->pDirty==0 );
35287   if( pCache->pCache ){
35288     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
35289     pCache->pCache = 0;
35290     pCache->pPage1 = 0;
35291   }
35292   pCache->szPage = szPage;
35293 }
35294
35295 /*
35296 ** Compute the number of pages of cache requested.
35297 */
35298 static int numberOfCachePages(PCache *p){
35299   if( p->szCache>=0 ){
35300     return p->szCache;
35301   }else{
35302     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
35303   }
35304 }
35305
35306 /*
35307 ** Try to obtain a page from the cache.
35308 */
35309 SQLITE_PRIVATE int sqlite3PcacheFetch(
35310   PCache *pCache,       /* Obtain the page from this cache */
35311   Pgno pgno,            /* Page number to obtain */
35312   int createFlag,       /* If true, create page if it does not exist already */
35313   PgHdr **ppPage        /* Write the page here */
35314 ){
35315   sqlite3_pcache_page *pPage = 0;
35316   PgHdr *pPgHdr = 0;
35317   int eCreate;
35318
35319   assert( pCache!=0 );
35320   assert( createFlag==1 || createFlag==0 );
35321   assert( pgno>0 );
35322
35323   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
35324   ** allocate it now.
35325   */
35326   if( !pCache->pCache && createFlag ){
35327     sqlite3_pcache *p;
35328     p = sqlite3GlobalConfig.pcache2.xCreate(
35329         pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
35330     );
35331     if( !p ){
35332       return SQLITE_NOMEM;
35333     }
35334     sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
35335     pCache->pCache = p;
35336   }
35337
35338   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
35339   if( pCache->pCache ){
35340     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
35341   }
35342
35343   if( !pPage && eCreate==1 ){
35344     PgHdr *pPg;
35345
35346     /* Find a dirty page to write-out and recycle. First try to find a 
35347     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
35348     ** cleared), but if that is not possible settle for any other 
35349     ** unreferenced dirty page.
35350     */
35351     expensive_assert( pcacheCheckSynced(pCache) );
35352     for(pPg=pCache->pSynced; 
35353         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
35354         pPg=pPg->pDirtyPrev
35355     );
35356     pCache->pSynced = pPg;
35357     if( !pPg ){
35358       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
35359     }
35360     if( pPg ){
35361       int rc;
35362 #ifdef SQLITE_LOG_CACHE_SPILL
35363       sqlite3_log(SQLITE_FULL, 
35364                   "spill page %d making room for %d - cache used: %d/%d",
35365                   pPg->pgno, pgno,
35366                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
35367                   numberOfCachePages(pCache));
35368 #endif
35369       rc = pCache->xStress(pCache->pStress, pPg);
35370       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
35371         return rc;
35372       }
35373     }
35374
35375     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
35376   }
35377
35378   if( pPage ){
35379     pPgHdr = (PgHdr *)pPage->pExtra;
35380
35381     if( !pPgHdr->pPage ){
35382       memset(pPgHdr, 0, sizeof(PgHdr));
35383       pPgHdr->pPage = pPage;
35384       pPgHdr->pData = pPage->pBuf;
35385       pPgHdr->pExtra = (void *)&pPgHdr[1];
35386       memset(pPgHdr->pExtra, 0, pCache->szExtra);
35387       pPgHdr->pCache = pCache;
35388       pPgHdr->pgno = pgno;
35389     }
35390     assert( pPgHdr->pCache==pCache );
35391     assert( pPgHdr->pgno==pgno );
35392     assert( pPgHdr->pData==pPage->pBuf );
35393     assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
35394
35395     if( 0==pPgHdr->nRef ){
35396       pCache->nRef++;
35397     }
35398     pPgHdr->nRef++;
35399     if( pgno==1 ){
35400       pCache->pPage1 = pPgHdr;
35401     }
35402   }
35403   *ppPage = pPgHdr;
35404   return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
35405 }
35406
35407 /*
35408 ** Decrement the reference count on a page. If the page is clean and the
35409 ** reference count drops to 0, then it is made elible for recycling.
35410 */
35411 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
35412   assert( p->nRef>0 );
35413   p->nRef--;
35414   if( p->nRef==0 ){
35415     PCache *pCache = p->pCache;
35416     pCache->nRef--;
35417     if( (p->flags&PGHDR_DIRTY)==0 ){
35418       pcacheUnpin(p);
35419     }else{
35420       /* Move the page to the head of the dirty list. */
35421       pcacheRemoveFromDirtyList(p);
35422       pcacheAddToDirtyList(p);
35423     }
35424   }
35425 }
35426
35427 /*
35428 ** Increase the reference count of a supplied page by 1.
35429 */
35430 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
35431   assert(p->nRef>0);
35432   p->nRef++;
35433 }
35434
35435 /*
35436 ** Drop a page from the cache. There must be exactly one reference to the
35437 ** page. This function deletes that reference, so after it returns the
35438 ** page pointed to by p is invalid.
35439 */
35440 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
35441   PCache *pCache;
35442   assert( p->nRef==1 );
35443   if( p->flags&PGHDR_DIRTY ){
35444     pcacheRemoveFromDirtyList(p);
35445   }
35446   pCache = p->pCache;
35447   pCache->nRef--;
35448   if( p->pgno==1 ){
35449     pCache->pPage1 = 0;
35450   }
35451   sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
35452 }
35453
35454 /*
35455 ** Make sure the page is marked as dirty. If it isn't dirty already,
35456 ** make it so.
35457 */
35458 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
35459   p->flags &= ~PGHDR_DONT_WRITE;
35460   assert( p->nRef>0 );
35461   if( 0==(p->flags & PGHDR_DIRTY) ){
35462     p->flags |= PGHDR_DIRTY;
35463     pcacheAddToDirtyList( p);
35464   }
35465 }
35466
35467 /*
35468 ** Make sure the page is marked as clean. If it isn't clean already,
35469 ** make it so.
35470 */
35471 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
35472   if( (p->flags & PGHDR_DIRTY) ){
35473     pcacheRemoveFromDirtyList(p);
35474     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
35475     if( p->nRef==0 ){
35476       pcacheUnpin(p);
35477     }
35478   }
35479 }
35480
35481 /*
35482 ** Make every page in the cache clean.
35483 */
35484 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
35485   PgHdr *p;
35486   while( (p = pCache->pDirty)!=0 ){
35487     sqlite3PcacheMakeClean(p);
35488   }
35489 }
35490
35491 /*
35492 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
35493 */
35494 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
35495   PgHdr *p;
35496   for(p=pCache->pDirty; p; p=p->pDirtyNext){
35497     p->flags &= ~PGHDR_NEED_SYNC;
35498   }
35499   pCache->pSynced = pCache->pDirtyTail;
35500 }
35501
35502 /*
35503 ** Change the page number of page p to newPgno. 
35504 */
35505 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
35506   PCache *pCache = p->pCache;
35507   assert( p->nRef>0 );
35508   assert( newPgno>0 );
35509   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
35510   p->pgno = newPgno;
35511   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
35512     pcacheRemoveFromDirtyList(p);
35513     pcacheAddToDirtyList(p);
35514   }
35515 }
35516
35517 /*
35518 ** Drop every cache entry whose page number is greater than "pgno". The
35519 ** caller must ensure that there are no outstanding references to any pages
35520 ** other than page 1 with a page number greater than pgno.
35521 **
35522 ** If there is a reference to page 1 and the pgno parameter passed to this
35523 ** function is 0, then the data area associated with page 1 is zeroed, but
35524 ** the page object is not dropped.
35525 */
35526 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
35527   if( pCache->pCache ){
35528     PgHdr *p;
35529     PgHdr *pNext;
35530     for(p=pCache->pDirty; p; p=pNext){
35531       pNext = p->pDirtyNext;
35532       /* This routine never gets call with a positive pgno except right
35533       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
35534       ** it must be that pgno==0.
35535       */
35536       assert( p->pgno>0 );
35537       if( ALWAYS(p->pgno>pgno) ){
35538         assert( p->flags&PGHDR_DIRTY );
35539         sqlite3PcacheMakeClean(p);
35540       }
35541     }
35542     if( pgno==0 && pCache->pPage1 ){
35543       memset(pCache->pPage1->pData, 0, pCache->szPage);
35544       pgno = 1;
35545     }
35546     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
35547   }
35548 }
35549
35550 /*
35551 ** Close a cache.
35552 */
35553 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
35554   if( pCache->pCache ){
35555     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
35556   }
35557 }
35558
35559 /* 
35560 ** Discard the contents of the cache.
35561 */
35562 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
35563   sqlite3PcacheTruncate(pCache, 0);
35564 }
35565
35566 /*
35567 ** Merge two lists of pages connected by pDirty and in pgno order.
35568 ** Do not both fixing the pDirtyPrev pointers.
35569 */
35570 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
35571   PgHdr result, *pTail;
35572   pTail = &result;
35573   while( pA && pB ){
35574     if( pA->pgno<pB->pgno ){
35575       pTail->pDirty = pA;
35576       pTail = pA;
35577       pA = pA->pDirty;
35578     }else{
35579       pTail->pDirty = pB;
35580       pTail = pB;
35581       pB = pB->pDirty;
35582     }
35583   }
35584   if( pA ){
35585     pTail->pDirty = pA;
35586   }else if( pB ){
35587     pTail->pDirty = pB;
35588   }else{
35589     pTail->pDirty = 0;
35590   }
35591   return result.pDirty;
35592 }
35593
35594 /*
35595 ** Sort the list of pages in accending order by pgno.  Pages are
35596 ** connected by pDirty pointers.  The pDirtyPrev pointers are
35597 ** corrupted by this sort.
35598 **
35599 ** Since there cannot be more than 2^31 distinct pages in a database,
35600 ** there cannot be more than 31 buckets required by the merge sorter.
35601 ** One extra bucket is added to catch overflow in case something
35602 ** ever changes to make the previous sentence incorrect.
35603 */
35604 #define N_SORT_BUCKET  32
35605 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
35606   PgHdr *a[N_SORT_BUCKET], *p;
35607   int i;
35608   memset(a, 0, sizeof(a));
35609   while( pIn ){
35610     p = pIn;
35611     pIn = p->pDirty;
35612     p->pDirty = 0;
35613     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
35614       if( a[i]==0 ){
35615         a[i] = p;
35616         break;
35617       }else{
35618         p = pcacheMergeDirtyList(a[i], p);
35619         a[i] = 0;
35620       }
35621     }
35622     if( NEVER(i==N_SORT_BUCKET-1) ){
35623       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
35624       ** the input list.  But that is impossible.
35625       */
35626       a[i] = pcacheMergeDirtyList(a[i], p);
35627     }
35628   }
35629   p = a[0];
35630   for(i=1; i<N_SORT_BUCKET; i++){
35631     p = pcacheMergeDirtyList(p, a[i]);
35632   }
35633   return p;
35634 }
35635
35636 /*
35637 ** Return a list of all dirty pages in the cache, sorted by page number.
35638 */
35639 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
35640   PgHdr *p;
35641   for(p=pCache->pDirty; p; p=p->pDirtyNext){
35642     p->pDirty = p->pDirtyNext;
35643   }
35644   return pcacheSortDirtyList(pCache->pDirty);
35645 }
35646
35647 /* 
35648 ** Return the total number of referenced pages held by the cache.
35649 */
35650 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
35651   return pCache->nRef;
35652 }
35653
35654 /*
35655 ** Return the number of references to the page supplied as an argument.
35656 */
35657 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
35658   return p->nRef;
35659 }
35660
35661 /* 
35662 ** Return the total number of pages in the cache.
35663 */
35664 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
35665   int nPage = 0;
35666   if( pCache->pCache ){
35667     nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
35668   }
35669   return nPage;
35670 }
35671
35672 #ifdef SQLITE_TEST
35673 /*
35674 ** Get the suggested cache-size value.
35675 */
35676 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
35677   return numberOfCachePages(pCache);
35678 }
35679 #endif
35680
35681 /*
35682 ** Set the suggested cache-size value.
35683 */
35684 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
35685   pCache->szCache = mxPage;
35686   if( pCache->pCache ){
35687     sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
35688                                            numberOfCachePages(pCache));
35689   }
35690 }
35691
35692 /*
35693 ** Free up as much memory as possible from the page cache.
35694 */
35695 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
35696   if( pCache->pCache ){
35697     sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
35698   }
35699 }
35700
35701 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
35702 /*
35703 ** For all dirty pages currently in the cache, invoke the specified
35704 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
35705 ** defined.
35706 */
35707 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
35708   PgHdr *pDirty;
35709   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
35710     xIter(pDirty);
35711   }
35712 }
35713 #endif
35714
35715 /************** End of pcache.c **********************************************/
35716 /************** Begin file pcache1.c *****************************************/
35717 /*
35718 ** 2008 November 05
35719 **
35720 ** The author disclaims copyright to this source code.  In place of
35721 ** a legal notice, here is a blessing:
35722 **
35723 **    May you do good and not evil.
35724 **    May you find forgiveness for yourself and forgive others.
35725 **    May you share freely, never taking more than you give.
35726 **
35727 *************************************************************************
35728 **
35729 ** This file implements the default page cache implementation (the
35730 ** sqlite3_pcache interface). It also contains part of the implementation
35731 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
35732 ** If the default page cache implementation is overriden, then neither of
35733 ** these two features are available.
35734 */
35735
35736
35737 typedef struct PCache1 PCache1;
35738 typedef struct PgHdr1 PgHdr1;
35739 typedef struct PgFreeslot PgFreeslot;
35740 typedef struct PGroup PGroup;
35741
35742 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
35743 ** of one or more PCaches that are able to recycle each others unpinned
35744 ** pages when they are under memory pressure.  A PGroup is an instance of
35745 ** the following object.
35746 **
35747 ** This page cache implementation works in one of two modes:
35748 **
35749 **   (1)  Every PCache is the sole member of its own PGroup.  There is
35750 **        one PGroup per PCache.
35751 **
35752 **   (2)  There is a single global PGroup that all PCaches are a member
35753 **        of.
35754 **
35755 ** Mode 1 uses more memory (since PCache instances are not able to rob
35756 ** unused pages from other PCaches) but it also operates without a mutex,
35757 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
35758 ** threadsafe, but recycles pages more efficiently.
35759 **
35760 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
35761 ** PGroup which is the pcache1.grp global variable and its mutex is
35762 ** SQLITE_MUTEX_STATIC_LRU.
35763 */
35764 struct PGroup {
35765   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
35766   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
35767   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
35768   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
35769   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
35770   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
35771 };
35772
35773 /* Each page cache is an instance of the following object.  Every
35774 ** open database file (including each in-memory database and each
35775 ** temporary or transient database) has a single page cache which
35776 ** is an instance of this object.
35777 **
35778 ** Pointers to structures of this type are cast and returned as 
35779 ** opaque sqlite3_pcache* handles.
35780 */
35781 struct PCache1 {
35782   /* Cache configuration parameters. Page size (szPage) and the purgeable
35783   ** flag (bPurgeable) are set when the cache is created. nMax may be 
35784   ** modified at any time by a call to the pcache1Cachesize() method.
35785   ** The PGroup mutex must be held when accessing nMax.
35786   */
35787   PGroup *pGroup;                     /* PGroup this cache belongs to */
35788   int szPage;                         /* Size of allocated pages in bytes */
35789   int szExtra;                        /* Size of extra space in bytes */
35790   int bPurgeable;                     /* True if cache is purgeable */
35791   unsigned int nMin;                  /* Minimum number of pages reserved */
35792   unsigned int nMax;                  /* Configured "cache_size" value */
35793   unsigned int n90pct;                /* nMax*9/10 */
35794   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
35795
35796   /* Hash table of all pages. The following variables may only be accessed
35797   ** when the accessor is holding the PGroup mutex.
35798   */
35799   unsigned int nRecyclable;           /* Number of pages in the LRU list */
35800   unsigned int nPage;                 /* Total number of pages in apHash */
35801   unsigned int nHash;                 /* Number of slots in apHash[] */
35802   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
35803 };
35804
35805 /*
35806 ** Each cache entry is represented by an instance of the following 
35807 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
35808 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
35809 ** in memory.
35810 */
35811 struct PgHdr1 {
35812   sqlite3_pcache_page page;
35813   unsigned int iKey;             /* Key value (page number) */
35814   PgHdr1 *pNext;                 /* Next in hash table chain */
35815   PCache1 *pCache;               /* Cache that currently owns this page */
35816   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
35817   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
35818 };
35819
35820 /*
35821 ** Free slots in the allocator used to divide up the buffer provided using
35822 ** the SQLITE_CONFIG_PAGECACHE mechanism.
35823 */
35824 struct PgFreeslot {
35825   PgFreeslot *pNext;  /* Next free slot */
35826 };
35827
35828 /*
35829 ** Global data used by this cache.
35830 */
35831 static SQLITE_WSD struct PCacheGlobal {
35832   PGroup grp;                    /* The global PGroup for mode (2) */
35833
35834   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
35835   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
35836   ** fixed at sqlite3_initialize() time and do not require mutex protection.
35837   ** The nFreeSlot and pFree values do require mutex protection.
35838   */
35839   int isInit;                    /* True if initialized */
35840   int szSlot;                    /* Size of each free slot */
35841   int nSlot;                     /* The number of pcache slots */
35842   int nReserve;                  /* Try to keep nFreeSlot above this */
35843   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
35844   /* Above requires no mutex.  Use mutex below for variable that follow. */
35845   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
35846   PgFreeslot *pFree;             /* Free page blocks */
35847   int nFreeSlot;                 /* Number of unused pcache slots */
35848   /* The following value requires a mutex to change.  We skip the mutex on
35849   ** reading because (1) most platforms read a 32-bit integer atomically and
35850   ** (2) even if an incorrect value is read, no great harm is done since this
35851   ** is really just an optimization. */
35852   int bUnderPressure;            /* True if low on PAGECACHE memory */
35853 } pcache1_g;
35854
35855 /*
35856 ** All code in this file should access the global structure above via the
35857 ** alias "pcache1". This ensures that the WSD emulation is used when
35858 ** compiling for systems that do not support real WSD.
35859 */
35860 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
35861
35862 /*
35863 ** Macros to enter and leave the PCache LRU mutex.
35864 */
35865 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
35866 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
35867
35868 /******************************************************************************/
35869 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
35870
35871 /*
35872 ** This function is called during initialization if a static buffer is 
35873 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
35874 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
35875 ** enough to contain 'n' buffers of 'sz' bytes each.
35876 **
35877 ** This routine is called from sqlite3_initialize() and so it is guaranteed
35878 ** to be serialized already.  There is no need for further mutexing.
35879 */
35880 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
35881   if( pcache1.isInit ){
35882     PgFreeslot *p;
35883     sz = ROUNDDOWN8(sz);
35884     pcache1.szSlot = sz;
35885     pcache1.nSlot = pcache1.nFreeSlot = n;
35886     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
35887     pcache1.pStart = pBuf;
35888     pcache1.pFree = 0;
35889     pcache1.bUnderPressure = 0;
35890     while( n-- ){
35891       p = (PgFreeslot*)pBuf;
35892       p->pNext = pcache1.pFree;
35893       pcache1.pFree = p;
35894       pBuf = (void*)&((char*)pBuf)[sz];
35895     }
35896     pcache1.pEnd = pBuf;
35897   }
35898 }
35899
35900 /*
35901 ** Malloc function used within this file to allocate space from the buffer
35902 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
35903 ** such buffer exists or there is no space left in it, this function falls 
35904 ** back to sqlite3Malloc().
35905 **
35906 ** Multiple threads can run this routine at the same time.  Global variables
35907 ** in pcache1 need to be protected via mutex.
35908 */
35909 static void *pcache1Alloc(int nByte){
35910   void *p = 0;
35911   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35912   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
35913   if( nByte<=pcache1.szSlot ){
35914     sqlite3_mutex_enter(pcache1.mutex);
35915     p = (PgHdr1 *)pcache1.pFree;
35916     if( p ){
35917       pcache1.pFree = pcache1.pFree->pNext;
35918       pcache1.nFreeSlot--;
35919       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35920       assert( pcache1.nFreeSlot>=0 );
35921       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
35922     }
35923     sqlite3_mutex_leave(pcache1.mutex);
35924   }
35925   if( p==0 ){
35926     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
35927     ** it from sqlite3Malloc instead.
35928     */
35929     p = sqlite3Malloc(nByte);
35930 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
35931     if( p ){
35932       int sz = sqlite3MallocSize(p);
35933       sqlite3_mutex_enter(pcache1.mutex);
35934       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
35935       sqlite3_mutex_leave(pcache1.mutex);
35936     }
35937 #endif
35938     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35939   }
35940   return p;
35941 }
35942
35943 /*
35944 ** Free an allocated buffer obtained from pcache1Alloc().
35945 */
35946 static int pcache1Free(void *p){
35947   int nFreed = 0;
35948   if( p==0 ) return 0;
35949   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35950     PgFreeslot *pSlot;
35951     sqlite3_mutex_enter(pcache1.mutex);
35952     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
35953     pSlot = (PgFreeslot*)p;
35954     pSlot->pNext = pcache1.pFree;
35955     pcache1.pFree = pSlot;
35956     pcache1.nFreeSlot++;
35957     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35958     assert( pcache1.nFreeSlot<=pcache1.nSlot );
35959     sqlite3_mutex_leave(pcache1.mutex);
35960   }else{
35961     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35962     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35963     nFreed = sqlite3MallocSize(p);
35964 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
35965     sqlite3_mutex_enter(pcache1.mutex);
35966     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
35967     sqlite3_mutex_leave(pcache1.mutex);
35968 #endif
35969     sqlite3_free(p);
35970   }
35971   return nFreed;
35972 }
35973
35974 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35975 /*
35976 ** Return the size of a pcache allocation
35977 */
35978 static int pcache1MemSize(void *p){
35979   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35980     return pcache1.szSlot;
35981   }else{
35982     int iSize;
35983     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35984     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35985     iSize = sqlite3MallocSize(p);
35986     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35987     return iSize;
35988   }
35989 }
35990 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35991
35992 /*
35993 ** Allocate a new page object initially associated with cache pCache.
35994 */
35995 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
35996   PgHdr1 *p = 0;
35997   void *pPg;
35998
35999   /* The group mutex must be released before pcache1Alloc() is called. This
36000   ** is because it may call sqlite3_release_memory(), which assumes that 
36001   ** this mutex is not held. */
36002   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36003   pcache1LeaveMutex(pCache->pGroup);
36004 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
36005   pPg = pcache1Alloc(pCache->szPage);
36006   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
36007   if( !pPg || !p ){
36008     pcache1Free(pPg);
36009     sqlite3_free(p);
36010     pPg = 0;
36011   }
36012 #else
36013   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
36014   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
36015 #endif
36016   pcache1EnterMutex(pCache->pGroup);
36017
36018   if( pPg ){
36019     p->page.pBuf = pPg;
36020     p->page.pExtra = &p[1];
36021     if( pCache->bPurgeable ){
36022       pCache->pGroup->nCurrentPage++;
36023     }
36024     return p;
36025   }
36026   return 0;
36027 }
36028
36029 /*
36030 ** Free a page object allocated by pcache1AllocPage().
36031 **
36032 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
36033 ** that the current implementation happens to never call this routine
36034 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
36035 */
36036 static void pcache1FreePage(PgHdr1 *p){
36037   if( ALWAYS(p) ){
36038     PCache1 *pCache = p->pCache;
36039     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
36040     pcache1Free(p->page.pBuf);
36041 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
36042     sqlite3_free(p);
36043 #endif
36044     if( pCache->bPurgeable ){
36045       pCache->pGroup->nCurrentPage--;
36046     }
36047   }
36048 }
36049
36050 /*
36051 ** Malloc function used by SQLite to obtain space from the buffer configured
36052 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
36053 ** exists, this function falls back to sqlite3Malloc().
36054 */
36055 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
36056   return pcache1Alloc(sz);
36057 }
36058
36059 /*
36060 ** Free an allocated buffer obtained from sqlite3PageMalloc().
36061 */
36062 SQLITE_PRIVATE void sqlite3PageFree(void *p){
36063   pcache1Free(p);
36064 }
36065
36066
36067 /*
36068 ** Return true if it desirable to avoid allocating a new page cache
36069 ** entry.
36070 **
36071 ** If memory was allocated specifically to the page cache using
36072 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
36073 ** it is desirable to avoid allocating a new page cache entry because
36074 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
36075 ** for all page cache needs and we should not need to spill the
36076 ** allocation onto the heap.
36077 **
36078 ** Or, the heap is used for all page cache memory but the heap is
36079 ** under memory pressure, then again it is desirable to avoid
36080 ** allocating a new page cache entry in order to avoid stressing
36081 ** the heap even further.
36082 */
36083 static int pcache1UnderMemoryPressure(PCache1 *pCache){
36084   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
36085     return pcache1.bUnderPressure;
36086   }else{
36087     return sqlite3HeapNearlyFull();
36088   }
36089 }
36090
36091 /******************************************************************************/
36092 /******** General Implementation Functions ************************************/
36093
36094 /*
36095 ** This function is used to resize the hash table used by the cache passed
36096 ** as the first argument.
36097 **
36098 ** The PCache mutex must be held when this function is called.
36099 */
36100 static int pcache1ResizeHash(PCache1 *p){
36101   PgHdr1 **apNew;
36102   unsigned int nNew;
36103   unsigned int i;
36104
36105   assert( sqlite3_mutex_held(p->pGroup->mutex) );
36106
36107   nNew = p->nHash*2;
36108   if( nNew<256 ){
36109     nNew = 256;
36110   }
36111
36112   pcache1LeaveMutex(p->pGroup);
36113   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
36114   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
36115   if( p->nHash ){ sqlite3EndBenignMalloc(); }
36116   pcache1EnterMutex(p->pGroup);
36117   if( apNew ){
36118     for(i=0; i<p->nHash; i++){
36119       PgHdr1 *pPage;
36120       PgHdr1 *pNext = p->apHash[i];
36121       while( (pPage = pNext)!=0 ){
36122         unsigned int h = pPage->iKey % nNew;
36123         pNext = pPage->pNext;
36124         pPage->pNext = apNew[h];
36125         apNew[h] = pPage;
36126       }
36127     }
36128     sqlite3_free(p->apHash);
36129     p->apHash = apNew;
36130     p->nHash = nNew;
36131   }
36132
36133   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
36134 }
36135
36136 /*
36137 ** This function is used internally to remove the page pPage from the 
36138 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
36139 ** LRU list, then this function is a no-op.
36140 **
36141 ** The PGroup mutex must be held when this function is called.
36142 **
36143 ** If pPage is NULL then this routine is a no-op.
36144 */
36145 static void pcache1PinPage(PgHdr1 *pPage){
36146   PCache1 *pCache;
36147   PGroup *pGroup;
36148
36149   if( pPage==0 ) return;
36150   pCache = pPage->pCache;
36151   pGroup = pCache->pGroup;
36152   assert( sqlite3_mutex_held(pGroup->mutex) );
36153   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
36154     if( pPage->pLruPrev ){
36155       pPage->pLruPrev->pLruNext = pPage->pLruNext;
36156     }
36157     if( pPage->pLruNext ){
36158       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
36159     }
36160     if( pGroup->pLruHead==pPage ){
36161       pGroup->pLruHead = pPage->pLruNext;
36162     }
36163     if( pGroup->pLruTail==pPage ){
36164       pGroup->pLruTail = pPage->pLruPrev;
36165     }
36166     pPage->pLruNext = 0;
36167     pPage->pLruPrev = 0;
36168     pPage->pCache->nRecyclable--;
36169   }
36170 }
36171
36172
36173 /*
36174 ** Remove the page supplied as an argument from the hash table 
36175 ** (PCache1.apHash structure) that it is currently stored in.
36176 **
36177 ** The PGroup mutex must be held when this function is called.
36178 */
36179 static void pcache1RemoveFromHash(PgHdr1 *pPage){
36180   unsigned int h;
36181   PCache1 *pCache = pPage->pCache;
36182   PgHdr1 **pp;
36183
36184   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36185   h = pPage->iKey % pCache->nHash;
36186   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
36187   *pp = (*pp)->pNext;
36188
36189   pCache->nPage--;
36190 }
36191
36192 /*
36193 ** If there are currently more than nMaxPage pages allocated, try
36194 ** to recycle pages to reduce the number allocated to nMaxPage.
36195 */
36196 static void pcache1EnforceMaxPage(PGroup *pGroup){
36197   assert( sqlite3_mutex_held(pGroup->mutex) );
36198   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
36199     PgHdr1 *p = pGroup->pLruTail;
36200     assert( p->pCache->pGroup==pGroup );
36201     pcache1PinPage(p);
36202     pcache1RemoveFromHash(p);
36203     pcache1FreePage(p);
36204   }
36205 }
36206
36207 /*
36208 ** Discard all pages from cache pCache with a page number (key value) 
36209 ** greater than or equal to iLimit. Any pinned pages that meet this 
36210 ** criteria are unpinned before they are discarded.
36211 **
36212 ** The PCache mutex must be held when this function is called.
36213 */
36214 static void pcache1TruncateUnsafe(
36215   PCache1 *pCache,             /* The cache to truncate */
36216   unsigned int iLimit          /* Drop pages with this pgno or larger */
36217 ){
36218   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
36219   unsigned int h;
36220   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36221   for(h=0; h<pCache->nHash; h++){
36222     PgHdr1 **pp = &pCache->apHash[h]; 
36223     PgHdr1 *pPage;
36224     while( (pPage = *pp)!=0 ){
36225       if( pPage->iKey>=iLimit ){
36226         pCache->nPage--;
36227         *pp = pPage->pNext;
36228         pcache1PinPage(pPage);
36229         pcache1FreePage(pPage);
36230       }else{
36231         pp = &pPage->pNext;
36232         TESTONLY( nPage++; )
36233       }
36234     }
36235   }
36236   assert( pCache->nPage==nPage );
36237 }
36238
36239 /******************************************************************************/
36240 /******** sqlite3_pcache Methods **********************************************/
36241
36242 /*
36243 ** Implementation of the sqlite3_pcache.xInit method.
36244 */
36245 static int pcache1Init(void *NotUsed){
36246   UNUSED_PARAMETER(NotUsed);
36247   assert( pcache1.isInit==0 );
36248   memset(&pcache1, 0, sizeof(pcache1));
36249   if( sqlite3GlobalConfig.bCoreMutex ){
36250     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
36251     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
36252   }
36253   pcache1.grp.mxPinned = 10;
36254   pcache1.isInit = 1;
36255   return SQLITE_OK;
36256 }
36257
36258 /*
36259 ** Implementation of the sqlite3_pcache.xShutdown method.
36260 ** Note that the static mutex allocated in xInit does 
36261 ** not need to be freed.
36262 */
36263 static void pcache1Shutdown(void *NotUsed){
36264   UNUSED_PARAMETER(NotUsed);
36265   assert( pcache1.isInit!=0 );
36266   memset(&pcache1, 0, sizeof(pcache1));
36267 }
36268
36269 /*
36270 ** Implementation of the sqlite3_pcache.xCreate method.
36271 **
36272 ** Allocate a new cache.
36273 */
36274 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
36275   PCache1 *pCache;      /* The newly created page cache */
36276   PGroup *pGroup;       /* The group the new page cache will belong to */
36277   int sz;               /* Bytes of memory required to allocate the new cache */
36278
36279   /*
36280   ** The seperateCache variable is true if each PCache has its own private
36281   ** PGroup.  In other words, separateCache is true for mode (1) where no
36282   ** mutexing is required.
36283   **
36284   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
36285   **
36286   **   *  Always use a unified cache in single-threaded applications
36287   **
36288   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
36289   **      use separate caches (mode-1)
36290   */
36291 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
36292   const int separateCache = 0;
36293 #else
36294   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
36295 #endif
36296
36297   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
36298   assert( szExtra < 300 );
36299
36300   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
36301   pCache = (PCache1 *)sqlite3MallocZero(sz);
36302   if( pCache ){
36303     if( separateCache ){
36304       pGroup = (PGroup*)&pCache[1];
36305       pGroup->mxPinned = 10;
36306     }else{
36307       pGroup = &pcache1.grp;
36308     }
36309     pCache->pGroup = pGroup;
36310     pCache->szPage = szPage;
36311     pCache->szExtra = szExtra;
36312     pCache->bPurgeable = (bPurgeable ? 1 : 0);
36313     if( bPurgeable ){
36314       pCache->nMin = 10;
36315       pcache1EnterMutex(pGroup);
36316       pGroup->nMinPage += pCache->nMin;
36317       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36318       pcache1LeaveMutex(pGroup);
36319     }
36320   }
36321   return (sqlite3_pcache *)pCache;
36322 }
36323
36324 /*
36325 ** Implementation of the sqlite3_pcache.xCachesize method. 
36326 **
36327 ** Configure the cache_size limit for a cache.
36328 */
36329 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
36330   PCache1 *pCache = (PCache1 *)p;
36331   if( pCache->bPurgeable ){
36332     PGroup *pGroup = pCache->pGroup;
36333     pcache1EnterMutex(pGroup);
36334     pGroup->nMaxPage += (nMax - pCache->nMax);
36335     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36336     pCache->nMax = nMax;
36337     pCache->n90pct = pCache->nMax*9/10;
36338     pcache1EnforceMaxPage(pGroup);
36339     pcache1LeaveMutex(pGroup);
36340   }
36341 }
36342
36343 /*
36344 ** Implementation of the sqlite3_pcache.xShrink method. 
36345 **
36346 ** Free up as much memory as possible.
36347 */
36348 static void pcache1Shrink(sqlite3_pcache *p){
36349   PCache1 *pCache = (PCache1*)p;
36350   if( pCache->bPurgeable ){
36351     PGroup *pGroup = pCache->pGroup;
36352     int savedMaxPage;
36353     pcache1EnterMutex(pGroup);
36354     savedMaxPage = pGroup->nMaxPage;
36355     pGroup->nMaxPage = 0;
36356     pcache1EnforceMaxPage(pGroup);
36357     pGroup->nMaxPage = savedMaxPage;
36358     pcache1LeaveMutex(pGroup);
36359   }
36360 }
36361
36362 /*
36363 ** Implementation of the sqlite3_pcache.xPagecount method. 
36364 */
36365 static int pcache1Pagecount(sqlite3_pcache *p){
36366   int n;
36367   PCache1 *pCache = (PCache1*)p;
36368   pcache1EnterMutex(pCache->pGroup);
36369   n = pCache->nPage;
36370   pcache1LeaveMutex(pCache->pGroup);
36371   return n;
36372 }
36373
36374 /*
36375 ** Implementation of the sqlite3_pcache.xFetch method. 
36376 **
36377 ** Fetch a page by key value.
36378 **
36379 ** Whether or not a new page may be allocated by this function depends on
36380 ** the value of the createFlag argument.  0 means do not allocate a new
36381 ** page.  1 means allocate a new page if space is easily available.  2 
36382 ** means to try really hard to allocate a new page.
36383 **
36384 ** For a non-purgeable cache (a cache used as the storage for an in-memory
36385 ** database) there is really no difference between createFlag 1 and 2.  So
36386 ** the calling function (pcache.c) will never have a createFlag of 1 on
36387 ** a non-purgeable cache.
36388 **
36389 ** There are three different approaches to obtaining space for a page,
36390 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
36391 **
36392 **   1. Regardless of the value of createFlag, the cache is searched for a 
36393 **      copy of the requested page. If one is found, it is returned.
36394 **
36395 **   2. If createFlag==0 and the page is not already in the cache, NULL is
36396 **      returned.
36397 **
36398 **   3. If createFlag is 1, and the page is not already in the cache, then
36399 **      return NULL (do not allocate a new page) if any of the following
36400 **      conditions are true:
36401 **
36402 **       (a) the number of pages pinned by the cache is greater than
36403 **           PCache1.nMax, or
36404 **
36405 **       (b) the number of pages pinned by the cache is greater than
36406 **           the sum of nMax for all purgeable caches, less the sum of 
36407 **           nMin for all other purgeable caches, or
36408 **
36409 **   4. If none of the first three conditions apply and the cache is marked
36410 **      as purgeable, and if one of the following is true:
36411 **
36412 **       (a) The number of pages allocated for the cache is already 
36413 **           PCache1.nMax, or
36414 **
36415 **       (b) The number of pages allocated for all purgeable caches is
36416 **           already equal to or greater than the sum of nMax for all
36417 **           purgeable caches,
36418 **
36419 **       (c) The system is under memory pressure and wants to avoid
36420 **           unnecessary pages cache entry allocations
36421 **
36422 **      then attempt to recycle a page from the LRU list. If it is the right
36423 **      size, return the recycled buffer. Otherwise, free the buffer and
36424 **      proceed to step 5. 
36425 **
36426 **   5. Otherwise, allocate and return a new page buffer.
36427 */
36428 static sqlite3_pcache_page *pcache1Fetch(
36429   sqlite3_pcache *p, 
36430   unsigned int iKey, 
36431   int createFlag
36432 ){
36433   unsigned int nPinned;
36434   PCache1 *pCache = (PCache1 *)p;
36435   PGroup *pGroup;
36436   PgHdr1 *pPage = 0;
36437
36438   assert( pCache->bPurgeable || createFlag!=1 );
36439   assert( pCache->bPurgeable || pCache->nMin==0 );
36440   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
36441   assert( pCache->nMin==0 || pCache->bPurgeable );
36442   pcache1EnterMutex(pGroup = pCache->pGroup);
36443
36444   /* Step 1: Search the hash table for an existing entry. */
36445   if( pCache->nHash>0 ){
36446     unsigned int h = iKey % pCache->nHash;
36447     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
36448   }
36449
36450   /* Step 2: Abort if no existing page is found and createFlag is 0 */
36451   if( pPage || createFlag==0 ){
36452     pcache1PinPage(pPage);
36453     goto fetch_out;
36454   }
36455
36456   /* The pGroup local variable will normally be initialized by the
36457   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
36458   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
36459   ** local variable here.  Delaying the initialization of pGroup is an
36460   ** optimization:  The common case is to exit the module before reaching
36461   ** this point.
36462   */
36463 #ifdef SQLITE_MUTEX_OMIT
36464   pGroup = pCache->pGroup;
36465 #endif
36466
36467   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
36468   assert( pCache->nPage >= pCache->nRecyclable );
36469   nPinned = pCache->nPage - pCache->nRecyclable;
36470   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
36471   assert( pCache->n90pct == pCache->nMax*9/10 );
36472   if( createFlag==1 && (
36473         nPinned>=pGroup->mxPinned
36474      || nPinned>=pCache->n90pct
36475      || pcache1UnderMemoryPressure(pCache)
36476   )){
36477     goto fetch_out;
36478   }
36479
36480   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
36481     goto fetch_out;
36482   }
36483
36484   /* Step 4. Try to recycle a page. */
36485   if( pCache->bPurgeable && pGroup->pLruTail && (
36486          (pCache->nPage+1>=pCache->nMax)
36487       || pGroup->nCurrentPage>=pGroup->nMaxPage
36488       || pcache1UnderMemoryPressure(pCache)
36489   )){
36490     PCache1 *pOther;
36491     pPage = pGroup->pLruTail;
36492     pcache1RemoveFromHash(pPage);
36493     pcache1PinPage(pPage);
36494     pOther = pPage->pCache;
36495
36496     /* We want to verify that szPage and szExtra are the same for pOther
36497     ** and pCache.  Assert that we can verify this by comparing sums. */
36498     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
36499     assert( pCache->szExtra<512 );
36500     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
36501     assert( pOther->szExtra<512 );
36502
36503     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
36504       pcache1FreePage(pPage);
36505       pPage = 0;
36506     }else{
36507       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
36508     }
36509   }
36510
36511   /* Step 5. If a usable page buffer has still not been found, 
36512   ** attempt to allocate a new one. 
36513   */
36514   if( !pPage ){
36515     if( createFlag==1 ) sqlite3BeginBenignMalloc();
36516     pPage = pcache1AllocPage(pCache);
36517     if( createFlag==1 ) sqlite3EndBenignMalloc();
36518   }
36519
36520   if( pPage ){
36521     unsigned int h = iKey % pCache->nHash;
36522     pCache->nPage++;
36523     pPage->iKey = iKey;
36524     pPage->pNext = pCache->apHash[h];
36525     pPage->pCache = pCache;
36526     pPage->pLruPrev = 0;
36527     pPage->pLruNext = 0;
36528     *(void **)pPage->page.pExtra = 0;
36529     pCache->apHash[h] = pPage;
36530   }
36531
36532 fetch_out:
36533   if( pPage && iKey>pCache->iMaxKey ){
36534     pCache->iMaxKey = iKey;
36535   }
36536   pcache1LeaveMutex(pGroup);
36537   return &pPage->page;
36538 }
36539
36540
36541 /*
36542 ** Implementation of the sqlite3_pcache.xUnpin method.
36543 **
36544 ** Mark a page as unpinned (eligible for asynchronous recycling).
36545 */
36546 static void pcache1Unpin(
36547   sqlite3_pcache *p, 
36548   sqlite3_pcache_page *pPg, 
36549   int reuseUnlikely
36550 ){
36551   PCache1 *pCache = (PCache1 *)p;
36552   PgHdr1 *pPage = (PgHdr1 *)pPg;
36553   PGroup *pGroup = pCache->pGroup;
36554  
36555   assert( pPage->pCache==pCache );
36556   pcache1EnterMutex(pGroup);
36557
36558   /* It is an error to call this function if the page is already 
36559   ** part of the PGroup LRU list.
36560   */
36561   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
36562   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
36563
36564   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
36565     pcache1RemoveFromHash(pPage);
36566     pcache1FreePage(pPage);
36567   }else{
36568     /* Add the page to the PGroup LRU list. */
36569     if( pGroup->pLruHead ){
36570       pGroup->pLruHead->pLruPrev = pPage;
36571       pPage->pLruNext = pGroup->pLruHead;
36572       pGroup->pLruHead = pPage;
36573     }else{
36574       pGroup->pLruTail = pPage;
36575       pGroup->pLruHead = pPage;
36576     }
36577     pCache->nRecyclable++;
36578   }
36579
36580   pcache1LeaveMutex(pCache->pGroup);
36581 }
36582
36583 /*
36584 ** Implementation of the sqlite3_pcache.xRekey method. 
36585 */
36586 static void pcache1Rekey(
36587   sqlite3_pcache *p,
36588   sqlite3_pcache_page *pPg,
36589   unsigned int iOld,
36590   unsigned int iNew
36591 ){
36592   PCache1 *pCache = (PCache1 *)p;
36593   PgHdr1 *pPage = (PgHdr1 *)pPg;
36594   PgHdr1 **pp;
36595   unsigned int h; 
36596   assert( pPage->iKey==iOld );
36597   assert( pPage->pCache==pCache );
36598
36599   pcache1EnterMutex(pCache->pGroup);
36600
36601   h = iOld%pCache->nHash;
36602   pp = &pCache->apHash[h];
36603   while( (*pp)!=pPage ){
36604     pp = &(*pp)->pNext;
36605   }
36606   *pp = pPage->pNext;
36607
36608   h = iNew%pCache->nHash;
36609   pPage->iKey = iNew;
36610   pPage->pNext = pCache->apHash[h];
36611   pCache->apHash[h] = pPage;
36612   if( iNew>pCache->iMaxKey ){
36613     pCache->iMaxKey = iNew;
36614   }
36615
36616   pcache1LeaveMutex(pCache->pGroup);
36617 }
36618
36619 /*
36620 ** Implementation of the sqlite3_pcache.xTruncate method. 
36621 **
36622 ** Discard all unpinned pages in the cache with a page number equal to
36623 ** or greater than parameter iLimit. Any pinned pages with a page number
36624 ** equal to or greater than iLimit are implicitly unpinned.
36625 */
36626 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
36627   PCache1 *pCache = (PCache1 *)p;
36628   pcache1EnterMutex(pCache->pGroup);
36629   if( iLimit<=pCache->iMaxKey ){
36630     pcache1TruncateUnsafe(pCache, iLimit);
36631     pCache->iMaxKey = iLimit-1;
36632   }
36633   pcache1LeaveMutex(pCache->pGroup);
36634 }
36635
36636 /*
36637 ** Implementation of the sqlite3_pcache.xDestroy method. 
36638 **
36639 ** Destroy a cache allocated using pcache1Create().
36640 */
36641 static void pcache1Destroy(sqlite3_pcache *p){
36642   PCache1 *pCache = (PCache1 *)p;
36643   PGroup *pGroup = pCache->pGroup;
36644   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
36645   pcache1EnterMutex(pGroup);
36646   pcache1TruncateUnsafe(pCache, 0);
36647   assert( pGroup->nMaxPage >= pCache->nMax );
36648   pGroup->nMaxPage -= pCache->nMax;
36649   assert( pGroup->nMinPage >= pCache->nMin );
36650   pGroup->nMinPage -= pCache->nMin;
36651   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36652   pcache1EnforceMaxPage(pGroup);
36653   pcache1LeaveMutex(pGroup);
36654   sqlite3_free(pCache->apHash);
36655   sqlite3_free(pCache);
36656 }
36657
36658 /*
36659 ** This function is called during initialization (sqlite3_initialize()) to
36660 ** install the default pluggable cache module, assuming the user has not
36661 ** already provided an alternative.
36662 */
36663 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
36664   static const sqlite3_pcache_methods2 defaultMethods = {
36665     1,                       /* iVersion */
36666     0,                       /* pArg */
36667     pcache1Init,             /* xInit */
36668     pcache1Shutdown,         /* xShutdown */
36669     pcache1Create,           /* xCreate */
36670     pcache1Cachesize,        /* xCachesize */
36671     pcache1Pagecount,        /* xPagecount */
36672     pcache1Fetch,            /* xFetch */
36673     pcache1Unpin,            /* xUnpin */
36674     pcache1Rekey,            /* xRekey */
36675     pcache1Truncate,         /* xTruncate */
36676     pcache1Destroy,          /* xDestroy */
36677     pcache1Shrink            /* xShrink */
36678   };
36679   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
36680 }
36681
36682 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
36683 /*
36684 ** This function is called to free superfluous dynamically allocated memory
36685 ** held by the pager system. Memory in use by any SQLite pager allocated
36686 ** by the current thread may be sqlite3_free()ed.
36687 **
36688 ** nReq is the number of bytes of memory required. Once this much has
36689 ** been released, the function returns. The return value is the total number 
36690 ** of bytes of memory released.
36691 */
36692 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
36693   int nFree = 0;
36694   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
36695   assert( sqlite3_mutex_notheld(pcache1.mutex) );
36696   if( pcache1.pStart==0 ){
36697     PgHdr1 *p;
36698     pcache1EnterMutex(&pcache1.grp);
36699     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
36700       nFree += pcache1MemSize(p->page.pBuf);
36701 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
36702       nFree += sqlite3MemSize(p);
36703 #endif
36704       pcache1PinPage(p);
36705       pcache1RemoveFromHash(p);
36706       pcache1FreePage(p);
36707     }
36708     pcache1LeaveMutex(&pcache1.grp);
36709   }
36710   return nFree;
36711 }
36712 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
36713
36714 #ifdef SQLITE_TEST
36715 /*
36716 ** This function is used by test procedures to inspect the internal state
36717 ** of the global cache.
36718 */
36719 SQLITE_PRIVATE void sqlite3PcacheStats(
36720   int *pnCurrent,      /* OUT: Total number of pages cached */
36721   int *pnMax,          /* OUT: Global maximum cache size */
36722   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
36723   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
36724 ){
36725   PgHdr1 *p;
36726   int nRecyclable = 0;
36727   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
36728     nRecyclable++;
36729   }
36730   *pnCurrent = pcache1.grp.nCurrentPage;
36731   *pnMax = (int)pcache1.grp.nMaxPage;
36732   *pnMin = (int)pcache1.grp.nMinPage;
36733   *pnRecyclable = nRecyclable;
36734 }
36735 #endif
36736
36737 /************** End of pcache1.c *********************************************/
36738 /************** Begin file rowset.c ******************************************/
36739 /*
36740 ** 2008 December 3
36741 **
36742 ** The author disclaims copyright to this source code.  In place of
36743 ** a legal notice, here is a blessing:
36744 **
36745 **    May you do good and not evil.
36746 **    May you find forgiveness for yourself and forgive others.
36747 **    May you share freely, never taking more than you give.
36748 **
36749 *************************************************************************
36750 **
36751 ** This module implements an object we call a "RowSet".
36752 **
36753 ** The RowSet object is a collection of rowids.  Rowids
36754 ** are inserted into the RowSet in an arbitrary order.  Inserts
36755 ** can be intermixed with tests to see if a given rowid has been
36756 ** previously inserted into the RowSet.
36757 **
36758 ** After all inserts are finished, it is possible to extract the
36759 ** elements of the RowSet in sorted order.  Once this extraction
36760 ** process has started, no new elements may be inserted.
36761 **
36762 ** Hence, the primitive operations for a RowSet are:
36763 **
36764 **    CREATE
36765 **    INSERT
36766 **    TEST
36767 **    SMALLEST
36768 **    DESTROY
36769 **
36770 ** The CREATE and DESTROY primitives are the constructor and destructor,
36771 ** obviously.  The INSERT primitive adds a new element to the RowSet.
36772 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
36773 ** extracts the least value from the RowSet.
36774 **
36775 ** The INSERT primitive might allocate additional memory.  Memory is
36776 ** allocated in chunks so most INSERTs do no allocation.  There is an 
36777 ** upper bound on the size of allocated memory.  No memory is freed
36778 ** until DESTROY.
36779 **
36780 ** The TEST primitive includes a "batch" number.  The TEST primitive
36781 ** will only see elements that were inserted before the last change
36782 ** in the batch number.  In other words, if an INSERT occurs between
36783 ** two TESTs where the TESTs have the same batch nubmer, then the
36784 ** value added by the INSERT will not be visible to the second TEST.
36785 ** The initial batch number is zero, so if the very first TEST contains
36786 ** a non-zero batch number, it will see all prior INSERTs.
36787 **
36788 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
36789 ** that is attempted.
36790 **
36791 ** The cost of an INSERT is roughly constant.  (Sometime new memory
36792 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
36793 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
36794 ** The cost of a TEST using the same batch number is O(logN).  The cost
36795 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
36796 ** primitives are constant time.  The cost of DESTROY is O(N).
36797 **
36798 ** There is an added cost of O(N) when switching between TEST and
36799 ** SMALLEST primitives.
36800 */
36801
36802
36803 /*
36804 ** Target size for allocation chunks.
36805 */
36806 #define ROWSET_ALLOCATION_SIZE 1024
36807
36808 /*
36809 ** The number of rowset entries per allocation chunk.
36810 */
36811 #define ROWSET_ENTRY_PER_CHUNK  \
36812                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
36813
36814 /*
36815 ** Each entry in a RowSet is an instance of the following object.
36816 **
36817 ** This same object is reused to store a linked list of trees of RowSetEntry
36818 ** objects.  In that alternative use, pRight points to the next entry
36819 ** in the list, pLeft points to the tree, and v is unused.  The
36820 ** RowSet.pForest value points to the head of this forest list.
36821 */
36822 struct RowSetEntry {            
36823   i64 v;                        /* ROWID value for this entry */
36824   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
36825   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
36826 };
36827
36828 /*
36829 ** RowSetEntry objects are allocated in large chunks (instances of the
36830 ** following structure) to reduce memory allocation overhead.  The
36831 ** chunks are kept on a linked list so that they can be deallocated
36832 ** when the RowSet is destroyed.
36833 */
36834 struct RowSetChunk {
36835   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
36836   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
36837 };
36838
36839 /*
36840 ** A RowSet in an instance of the following structure.
36841 **
36842 ** A typedef of this structure if found in sqliteInt.h.
36843 */
36844 struct RowSet {
36845   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
36846   sqlite3 *db;                   /* The database connection */
36847   struct RowSetEntry *pEntry;    /* List of entries using pRight */
36848   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
36849   struct RowSetEntry *pFresh;    /* Source of new entry objects */
36850   struct RowSetEntry *pForest;   /* List of binary trees of entries */
36851   u16 nFresh;                    /* Number of objects on pFresh */
36852   u8 rsFlags;                    /* Various flags */
36853   u8 iBatch;                     /* Current insert batch */
36854 };
36855
36856 /*
36857 ** Allowed values for RowSet.rsFlags
36858 */
36859 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
36860 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
36861
36862 /*
36863 ** Turn bulk memory into a RowSet object.  N bytes of memory
36864 ** are available at pSpace.  The db pointer is used as a memory context
36865 ** for any subsequent allocations that need to occur.
36866 ** Return a pointer to the new RowSet object.
36867 **
36868 ** It must be the case that N is sufficient to make a Rowset.  If not
36869 ** an assertion fault occurs.
36870 ** 
36871 ** If N is larger than the minimum, use the surplus as an initial
36872 ** allocation of entries available to be filled.
36873 */
36874 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
36875   RowSet *p;
36876   assert( N >= ROUND8(sizeof(*p)) );
36877   p = pSpace;
36878   p->pChunk = 0;
36879   p->db = db;
36880   p->pEntry = 0;
36881   p->pLast = 0;
36882   p->pForest = 0;
36883   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
36884   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
36885   p->rsFlags = ROWSET_SORTED;
36886   p->iBatch = 0;
36887   return p;
36888 }
36889
36890 /*
36891 ** Deallocate all chunks from a RowSet.  This frees all memory that
36892 ** the RowSet has allocated over its lifetime.  This routine is
36893 ** the destructor for the RowSet.
36894 */
36895 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
36896   struct RowSetChunk *pChunk, *pNextChunk;
36897   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
36898     pNextChunk = pChunk->pNextChunk;
36899     sqlite3DbFree(p->db, pChunk);
36900   }
36901   p->pChunk = 0;
36902   p->nFresh = 0;
36903   p->pEntry = 0;
36904   p->pLast = 0;
36905   p->pForest = 0;
36906   p->rsFlags = ROWSET_SORTED;
36907 }
36908
36909 /*
36910 ** Allocate a new RowSetEntry object that is associated with the
36911 ** given RowSet.  Return a pointer to the new and completely uninitialized
36912 ** objected.
36913 **
36914 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
36915 ** routine returns NULL.
36916 */
36917 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
36918   assert( p!=0 );
36919   if( p->nFresh==0 ){
36920     struct RowSetChunk *pNew;
36921     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
36922     if( pNew==0 ){
36923       return 0;
36924     }
36925     pNew->pNextChunk = p->pChunk;
36926     p->pChunk = pNew;
36927     p->pFresh = pNew->aEntry;
36928     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
36929   }
36930   p->nFresh--;
36931   return p->pFresh++;
36932 }
36933
36934 /*
36935 ** Insert a new value into a RowSet.
36936 **
36937 ** The mallocFailed flag of the database connection is set if a
36938 ** memory allocation fails.
36939 */
36940 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
36941   struct RowSetEntry *pEntry;  /* The new entry */
36942   struct RowSetEntry *pLast;   /* The last prior entry */
36943
36944   /* This routine is never called after sqlite3RowSetNext() */
36945   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
36946
36947   pEntry = rowSetEntryAlloc(p);
36948   if( pEntry==0 ) return;
36949   pEntry->v = rowid;
36950   pEntry->pRight = 0;
36951   pLast = p->pLast;
36952   if( pLast ){
36953     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
36954       p->rsFlags &= ~ROWSET_SORTED;
36955     }
36956     pLast->pRight = pEntry;
36957   }else{
36958     p->pEntry = pEntry;
36959   }
36960   p->pLast = pEntry;
36961 }
36962
36963 /*
36964 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
36965 **
36966 ** The input lists are connected via pRight pointers and are 
36967 ** assumed to each already be in sorted order.
36968 */
36969 static struct RowSetEntry *rowSetEntryMerge(
36970   struct RowSetEntry *pA,    /* First sorted list to be merged */
36971   struct RowSetEntry *pB     /* Second sorted list to be merged */
36972 ){
36973   struct RowSetEntry head;
36974   struct RowSetEntry *pTail;
36975
36976   pTail = &head;
36977   while( pA && pB ){
36978     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36979     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
36980     if( pA->v<pB->v ){
36981       pTail->pRight = pA;
36982       pA = pA->pRight;
36983       pTail = pTail->pRight;
36984     }else if( pB->v<pA->v ){
36985       pTail->pRight = pB;
36986       pB = pB->pRight;
36987       pTail = pTail->pRight;
36988     }else{
36989       pA = pA->pRight;
36990     }
36991   }
36992   if( pA ){
36993     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36994     pTail->pRight = pA;
36995   }else{
36996     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
36997     pTail->pRight = pB;
36998   }
36999   return head.pRight;
37000 }
37001
37002 /*
37003 ** Sort all elements on the list of RowSetEntry objects into order of
37004 ** increasing v.
37005 */ 
37006 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
37007   unsigned int i;
37008   struct RowSetEntry *pNext, *aBucket[40];
37009
37010   memset(aBucket, 0, sizeof(aBucket));
37011   while( pIn ){
37012     pNext = pIn->pRight;
37013     pIn->pRight = 0;
37014     for(i=0; aBucket[i]; i++){
37015       pIn = rowSetEntryMerge(aBucket[i], pIn);
37016       aBucket[i] = 0;
37017     }
37018     aBucket[i] = pIn;
37019     pIn = pNext;
37020   }
37021   pIn = 0;
37022   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
37023     pIn = rowSetEntryMerge(pIn, aBucket[i]);
37024   }
37025   return pIn;
37026 }
37027
37028
37029 /*
37030 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
37031 ** Convert this tree into a linked list connected by the pRight pointers
37032 ** and return pointers to the first and last elements of the new list.
37033 */
37034 static void rowSetTreeToList(
37035   struct RowSetEntry *pIn,         /* Root of the input tree */
37036   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
37037   struct RowSetEntry **ppLast      /* Write tail of the output list here */
37038 ){
37039   assert( pIn!=0 );
37040   if( pIn->pLeft ){
37041     struct RowSetEntry *p;
37042     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
37043     p->pRight = pIn;
37044   }else{
37045     *ppFirst = pIn;
37046   }
37047   if( pIn->pRight ){
37048     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
37049   }else{
37050     *ppLast = pIn;
37051   }
37052   assert( (*ppLast)->pRight==0 );
37053 }
37054
37055
37056 /*
37057 ** Convert a sorted list of elements (connected by pRight) into a binary
37058 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
37059 ** node taken from the head of *ppList.  A depth of 2 means a tree with
37060 ** three nodes.  And so forth.
37061 **
37062 ** Use as many entries from the input list as required and update the
37063 ** *ppList to point to the unused elements of the list.  If the input
37064 ** list contains too few elements, then construct an incomplete tree
37065 ** and leave *ppList set to NULL.
37066 **
37067 ** Return a pointer to the root of the constructed binary tree.
37068 */
37069 static struct RowSetEntry *rowSetNDeepTree(
37070   struct RowSetEntry **ppList,
37071   int iDepth
37072 ){
37073   struct RowSetEntry *p;         /* Root of the new tree */
37074   struct RowSetEntry *pLeft;     /* Left subtree */
37075   if( *ppList==0 ){
37076     return 0;
37077   }
37078   if( iDepth==1 ){
37079     p = *ppList;
37080     *ppList = p->pRight;
37081     p->pLeft = p->pRight = 0;
37082     return p;
37083   }
37084   pLeft = rowSetNDeepTree(ppList, iDepth-1);
37085   p = *ppList;
37086   if( p==0 ){
37087     return pLeft;
37088   }
37089   p->pLeft = pLeft;
37090   *ppList = p->pRight;
37091   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
37092   return p;
37093 }
37094
37095 /*
37096 ** Convert a sorted list of elements into a binary tree. Make the tree
37097 ** as deep as it needs to be in order to contain the entire list.
37098 */
37099 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
37100   int iDepth;           /* Depth of the tree so far */
37101   struct RowSetEntry *p;       /* Current tree root */
37102   struct RowSetEntry *pLeft;   /* Left subtree */
37103
37104   assert( pList!=0 );
37105   p = pList;
37106   pList = p->pRight;
37107   p->pLeft = p->pRight = 0;
37108   for(iDepth=1; pList; iDepth++){
37109     pLeft = p;
37110     p = pList;
37111     pList = p->pRight;
37112     p->pLeft = pLeft;
37113     p->pRight = rowSetNDeepTree(&pList, iDepth);
37114   }
37115   return p;
37116 }
37117
37118 /*
37119 ** Take all the entries on p->pEntry and on the trees in p->pForest and
37120 ** sort them all together into one big ordered list on p->pEntry.
37121 **
37122 ** This routine should only be called once in the life of a RowSet.
37123 */
37124 static void rowSetToList(RowSet *p){
37125
37126   /* This routine is called only once */
37127   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
37128
37129   if( (p->rsFlags & ROWSET_SORTED)==0 ){
37130     p->pEntry = rowSetEntrySort(p->pEntry);
37131   }
37132
37133   /* While this module could theoretically support it, sqlite3RowSetNext()
37134   ** is never called after sqlite3RowSetText() for the same RowSet.  So
37135   ** there is never a forest to deal with.  Should this change, simply
37136   ** remove the assert() and the #if 0. */
37137   assert( p->pForest==0 );
37138 #if 0
37139   while( p->pForest ){
37140     struct RowSetEntry *pTree = p->pForest->pLeft;
37141     if( pTree ){
37142       struct RowSetEntry *pHead, *pTail;
37143       rowSetTreeToList(pTree, &pHead, &pTail);
37144       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
37145     }
37146     p->pForest = p->pForest->pRight;
37147   }
37148 #endif
37149   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
37150 }
37151
37152 /*
37153 ** Extract the smallest element from the RowSet.
37154 ** Write the element into *pRowid.  Return 1 on success.  Return
37155 ** 0 if the RowSet is already empty.
37156 **
37157 ** After this routine has been called, the sqlite3RowSetInsert()
37158 ** routine may not be called again.  
37159 */
37160 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
37161   assert( p!=0 );
37162
37163   /* Merge the forest into a single sorted list on first call */
37164   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
37165
37166   /* Return the next entry on the list */
37167   if( p->pEntry ){
37168     *pRowid = p->pEntry->v;
37169     p->pEntry = p->pEntry->pRight;
37170     if( p->pEntry==0 ){
37171       sqlite3RowSetClear(p);
37172     }
37173     return 1;
37174   }else{
37175     return 0;
37176   }
37177 }
37178
37179 /*
37180 ** Check to see if element iRowid was inserted into the rowset as
37181 ** part of any insert batch prior to iBatch.  Return 1 or 0.
37182 **
37183 ** If this is the first test of a new batch and if there exist entires
37184 ** on pRowSet->pEntry, then sort those entires into the forest at
37185 ** pRowSet->pForest so that they can be tested.
37186 */
37187 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
37188   struct RowSetEntry *p, *pTree;
37189
37190   /* This routine is never called after sqlite3RowSetNext() */
37191   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
37192
37193   /* Sort entries into the forest on the first test of a new batch 
37194   */
37195   if( iBatch!=pRowSet->iBatch ){
37196     p = pRowSet->pEntry;
37197     if( p ){
37198       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
37199       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
37200         p = rowSetEntrySort(p);
37201       }
37202       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
37203         ppPrevTree = &pTree->pRight;
37204         if( pTree->pLeft==0 ){
37205           pTree->pLeft = rowSetListToTree(p);
37206           break;
37207         }else{
37208           struct RowSetEntry *pAux, *pTail;
37209           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
37210           pTree->pLeft = 0;
37211           p = rowSetEntryMerge(pAux, p);
37212         }
37213       }
37214       if( pTree==0 ){
37215         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
37216         if( pTree ){
37217           pTree->v = 0;
37218           pTree->pRight = 0;
37219           pTree->pLeft = rowSetListToTree(p);
37220         }
37221       }
37222       pRowSet->pEntry = 0;
37223       pRowSet->pLast = 0;
37224       pRowSet->rsFlags |= ROWSET_SORTED;
37225     }
37226     pRowSet->iBatch = iBatch;
37227   }
37228
37229   /* Test to see if the iRowid value appears anywhere in the forest.
37230   ** Return 1 if it does and 0 if not.
37231   */
37232   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
37233     p = pTree->pLeft;
37234     while( p ){
37235       if( p->v<iRowid ){
37236         p = p->pRight;
37237       }else if( p->v>iRowid ){
37238         p = p->pLeft;
37239       }else{
37240         return 1;
37241       }
37242     }
37243   }
37244   return 0;
37245 }
37246
37247 /************** End of rowset.c **********************************************/
37248 /************** Begin file pager.c *******************************************/
37249 /*
37250 ** 2001 September 15
37251 **
37252 ** The author disclaims copyright to this source code.  In place of
37253 ** a legal notice, here is a blessing:
37254 **
37255 **    May you do good and not evil.
37256 **    May you find forgiveness for yourself and forgive others.
37257 **    May you share freely, never taking more than you give.
37258 **
37259 *************************************************************************
37260 ** This is the implementation of the page cache subsystem or "pager".
37261 ** 
37262 ** The pager is used to access a database disk file.  It implements
37263 ** atomic commit and rollback through the use of a journal file that
37264 ** is separate from the database file.  The pager also implements file
37265 ** locking to prevent two processes from writing the same database
37266 ** file simultaneously, or one process from reading the database while
37267 ** another is writing.
37268 */
37269 #ifndef SQLITE_OMIT_DISKIO
37270 /************** Include wal.h in the middle of pager.c ***********************/
37271 /************** Begin file wal.h *********************************************/
37272 /*
37273 ** 2010 February 1
37274 **
37275 ** The author disclaims copyright to this source code.  In place of
37276 ** a legal notice, here is a blessing:
37277 **
37278 **    May you do good and not evil.
37279 **    May you find forgiveness for yourself and forgive others.
37280 **    May you share freely, never taking more than you give.
37281 **
37282 *************************************************************************
37283 ** This header file defines the interface to the write-ahead logging 
37284 ** system. Refer to the comments below and the header comment attached to 
37285 ** the implementation of each function in log.c for further details.
37286 */
37287
37288 #ifndef _WAL_H_
37289 #define _WAL_H_
37290
37291
37292 /* Additional values that can be added to the sync_flags argument of
37293 ** sqlite3WalFrames():
37294 */
37295 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
37296 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
37297
37298 #ifdef SQLITE_OMIT_WAL
37299 # define sqlite3WalOpen(x,y,z)                   0
37300 # define sqlite3WalLimit(x,y)
37301 # define sqlite3WalClose(w,x,y,z)                0
37302 # define sqlite3WalBeginReadTransaction(y,z)     0
37303 # define sqlite3WalEndReadTransaction(z)
37304 # define sqlite3WalRead(v,w,x,y,z)               0
37305 # define sqlite3WalDbsize(y)                     0
37306 # define sqlite3WalBeginWriteTransaction(y)      0
37307 # define sqlite3WalEndWriteTransaction(x)        0
37308 # define sqlite3WalUndo(x,y,z)                   0
37309 # define sqlite3WalSavepoint(y,z)
37310 # define sqlite3WalSavepointUndo(y,z)            0
37311 # define sqlite3WalFrames(u,v,w,x,y,z)           0
37312 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
37313 # define sqlite3WalCallback(z)                   0
37314 # define sqlite3WalExclusiveMode(y,z)            0
37315 # define sqlite3WalHeapMemory(z)                 0
37316 # define sqlite3WalFramesize(z)                  0
37317 #else
37318
37319 #define WAL_SAVEPOINT_NDATA 4
37320
37321 /* Connection to a write-ahead log (WAL) file. 
37322 ** There is one object of this type for each pager. 
37323 */
37324 typedef struct Wal Wal;
37325
37326 /* Open and close a connection to a write-ahead log. */
37327 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
37328 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
37329
37330 /* Set the limiting size of a WAL file. */
37331 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
37332
37333 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
37334 ** snapshot is like a read-transaction.  It is the state of the database
37335 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
37336 ** preserves the current state even if the other threads or processes
37337 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
37338 ** transaction and releases the lock.
37339 */
37340 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
37341 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
37342
37343 /* Read a page from the write-ahead log, if it is present. */
37344 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
37345
37346 /* If the WAL is not empty, return the size of the database. */
37347 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
37348
37349 /* Obtain or release the WRITER lock. */
37350 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
37351 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
37352
37353 /* Undo any frames written (but not committed) to the log */
37354 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
37355
37356 /* Return an integer that records the current (uncommitted) write
37357 ** position in the WAL */
37358 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
37359
37360 /* Move the write position of the WAL back to iFrame.  Called in
37361 ** response to a ROLLBACK TO command. */
37362 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
37363
37364 /* Write a frame or frames to the log. */
37365 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
37366
37367 /* Copy pages from the log to the database file */ 
37368 SQLITE_PRIVATE int sqlite3WalCheckpoint(
37369   Wal *pWal,                      /* Write-ahead log connection */
37370   int eMode,                      /* One of PASSIVE, FULL and RESTART */
37371   int (*xBusy)(void*),            /* Function to call when busy */
37372   void *pBusyArg,                 /* Context argument for xBusyHandler */
37373   int sync_flags,                 /* Flags to sync db file with (or 0) */
37374   int nBuf,                       /* Size of buffer nBuf */
37375   u8 *zBuf,                       /* Temporary buffer to use */
37376   int *pnLog,                     /* OUT: Number of frames in WAL */
37377   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
37378 );
37379
37380 /* Return the value to pass to a sqlite3_wal_hook callback, the
37381 ** number of frames in the WAL at the point of the last commit since
37382 ** sqlite3WalCallback() was called.  If no commits have occurred since
37383 ** the last call, then return 0.
37384 */
37385 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
37386
37387 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
37388 ** by the pager layer on the database file.
37389 */
37390 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
37391
37392 /* Return true if the argument is non-NULL and the WAL module is using
37393 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
37394 ** WAL module is using shared-memory, return false. 
37395 */
37396 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
37397
37398 #ifdef SQLITE_ENABLE_ZIPVFS
37399 /* If the WAL file is not empty, return the number of bytes of content
37400 ** stored in each frame (i.e. the db page-size when the WAL was created).
37401 */
37402 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
37403 #endif
37404
37405 #endif /* ifndef SQLITE_OMIT_WAL */
37406 #endif /* _WAL_H_ */
37407
37408 /************** End of wal.h *************************************************/
37409 /************** Continuing where we left off in pager.c **********************/
37410
37411
37412 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
37413 **
37414 ** This comment block describes invariants that hold when using a rollback
37415 ** journal.  These invariants do not apply for journal_mode=WAL,
37416 ** journal_mode=MEMORY, or journal_mode=OFF.
37417 **
37418 ** Within this comment block, a page is deemed to have been synced
37419 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
37420 ** Otherwise, the page is not synced until the xSync method of the VFS
37421 ** is called successfully on the file containing the page.
37422 **
37423 ** Definition:  A page of the database file is said to be "overwriteable" if
37424 ** one or more of the following are true about the page:
37425 ** 
37426 **     (a)  The original content of the page as it was at the beginning of
37427 **          the transaction has been written into the rollback journal and
37428 **          synced.
37429 ** 
37430 **     (b)  The page was a freelist leaf page at the start of the transaction.
37431 ** 
37432 **     (c)  The page number is greater than the largest page that existed in
37433 **          the database file at the start of the transaction.
37434 ** 
37435 ** (1) A page of the database file is never overwritten unless one of the
37436 **     following are true:
37437 ** 
37438 **     (a) The page and all other pages on the same sector are overwriteable.
37439 ** 
37440 **     (b) The atomic page write optimization is enabled, and the entire
37441 **         transaction other than the update of the transaction sequence
37442 **         number consists of a single page change.
37443 ** 
37444 ** (2) The content of a page written into the rollback journal exactly matches
37445 **     both the content in the database when the rollback journal was written
37446 **     and the content in the database at the beginning of the current
37447 **     transaction.
37448 ** 
37449 ** (3) Writes to the database file are an integer multiple of the page size
37450 **     in length and are aligned on a page boundary.
37451 ** 
37452 ** (4) Reads from the database file are either aligned on a page boundary and
37453 **     an integer multiple of the page size in length or are taken from the
37454 **     first 100 bytes of the database file.
37455 ** 
37456 ** (5) All writes to the database file are synced prior to the rollback journal
37457 **     being deleted, truncated, or zeroed.
37458 ** 
37459 ** (6) If a master journal file is used, then all writes to the database file
37460 **     are synced prior to the master journal being deleted.
37461 ** 
37462 ** Definition: Two databases (or the same database at two points it time)
37463 ** are said to be "logically equivalent" if they give the same answer to
37464 ** all queries.  Note in particular the content of freelist leaf
37465 ** pages can be changed arbitarily without effecting the logical equivalence
37466 ** of the database.
37467 ** 
37468 ** (7) At any time, if any subset, including the empty set and the total set,
37469 **     of the unsynced changes to a rollback journal are removed and the 
37470 **     journal is rolled back, the resulting database file will be logical
37471 **     equivalent to the database file at the beginning of the transaction.
37472 ** 
37473 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
37474 **     is called to restore the database file to the same size it was at
37475 **     the beginning of the transaction.  (In some VFSes, the xTruncate
37476 **     method is a no-op, but that does not change the fact the SQLite will
37477 **     invoke it.)
37478 ** 
37479 ** (9) Whenever the database file is modified, at least one bit in the range
37480 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
37481 **     the EXCLUSIVE lock, thus signaling other connections on the same
37482 **     database to flush their caches.
37483 **
37484 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
37485 **      than one billion transactions.
37486 **
37487 ** (11) A database file is well-formed at the beginning and at the conclusion
37488 **      of every transaction.
37489 **
37490 ** (12) An EXCLUSIVE lock is held on the database file when writing to
37491 **      the database file.
37492 **
37493 ** (13) A SHARED lock is held on the database file while reading any
37494 **      content out of the database file.
37495 **
37496 ******************************************************************************/
37497
37498 /*
37499 ** Macros for troubleshooting.  Normally turned off
37500 */
37501 #if 0
37502 int sqlite3PagerTrace=1;  /* True to enable tracing */
37503 #define sqlite3DebugPrintf printf
37504 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
37505 #else
37506 #define PAGERTRACE(X)
37507 #endif
37508
37509 /*
37510 ** The following two macros are used within the PAGERTRACE() macros above
37511 ** to print out file-descriptors. 
37512 **
37513 ** PAGERID() takes a pointer to a Pager struct as its argument. The
37514 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
37515 ** struct as its argument.
37516 */
37517 #define PAGERID(p) ((int)(p->fd))
37518 #define FILEHANDLEID(fd) ((int)fd)
37519
37520 /*
37521 ** The Pager.eState variable stores the current 'state' of a pager. A
37522 ** pager may be in any one of the seven states shown in the following
37523 ** state diagram.
37524 **
37525 **                            OPEN <------+------+
37526 **                              |         |      |
37527 **                              V         |      |
37528 **               +---------> READER-------+      |
37529 **               |              |                |
37530 **               |              V                |
37531 **               |<-------WRITER_LOCKED------> ERROR
37532 **               |              |                ^  
37533 **               |              V                |
37534 **               |<------WRITER_CACHEMOD-------->|
37535 **               |              |                |
37536 **               |              V                |
37537 **               |<-------WRITER_DBMOD---------->|
37538 **               |              |                |
37539 **               |              V                |
37540 **               +<------WRITER_FINISHED-------->+
37541 **
37542 **
37543 ** List of state transitions and the C [function] that performs each:
37544 ** 
37545 **   OPEN              -> READER              [sqlite3PagerSharedLock]
37546 **   READER            -> OPEN                [pager_unlock]
37547 **
37548 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
37549 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
37550 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
37551 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
37552 **   WRITER_***        -> READER              [pager_end_transaction]
37553 **
37554 **   WRITER_***        -> ERROR               [pager_error]
37555 **   ERROR             -> OPEN                [pager_unlock]
37556 ** 
37557 **
37558 **  OPEN:
37559 **
37560 **    The pager starts up in this state. Nothing is guaranteed in this
37561 **    state - the file may or may not be locked and the database size is
37562 **    unknown. The database may not be read or written.
37563 **
37564 **    * No read or write transaction is active.
37565 **    * Any lock, or no lock at all, may be held on the database file.
37566 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
37567 **
37568 **  READER:
37569 **
37570 **    In this state all the requirements for reading the database in 
37571 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
37572 **    was) in exclusive-locking mode, a user-level read transaction is 
37573 **    open. The database size is known in this state.
37574 **
37575 **    A connection running with locking_mode=normal enters this state when
37576 **    it opens a read-transaction on the database and returns to state
37577 **    OPEN after the read-transaction is completed. However a connection
37578 **    running in locking_mode=exclusive (including temp databases) remains in
37579 **    this state even after the read-transaction is closed. The only way
37580 **    a locking_mode=exclusive connection can transition from READER to OPEN
37581 **    is via the ERROR state (see below).
37582 ** 
37583 **    * A read transaction may be active (but a write-transaction cannot).
37584 **    * A SHARED or greater lock is held on the database file.
37585 **    * The dbSize variable may be trusted (even if a user-level read 
37586 **      transaction is not active). The dbOrigSize and dbFileSize variables
37587 **      may not be trusted at this point.
37588 **    * If the database is a WAL database, then the WAL connection is open.
37589 **    * Even if a read-transaction is not open, it is guaranteed that 
37590 **      there is no hot-journal in the file-system.
37591 **
37592 **  WRITER_LOCKED:
37593 **
37594 **    The pager moves to this state from READER when a write-transaction
37595 **    is first opened on the database. In WRITER_LOCKED state, all locks 
37596 **    required to start a write-transaction are held, but no actual 
37597 **    modifications to the cache or database have taken place.
37598 **
37599 **    In rollback mode, a RESERVED or (if the transaction was opened with 
37600 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
37601 **    moving to this state, but the journal file is not written to or opened 
37602 **    to in this state. If the transaction is committed or rolled back while 
37603 **    in WRITER_LOCKED state, all that is required is to unlock the database 
37604 **    file.
37605 **
37606 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
37607 **    If the connection is running with locking_mode=exclusive, an attempt
37608 **    is made to obtain an EXCLUSIVE lock on the database file.
37609 **
37610 **    * A write transaction is active.
37611 **    * If the connection is open in rollback-mode, a RESERVED or greater 
37612 **      lock is held on the database file.
37613 **    * If the connection is open in WAL-mode, a WAL write transaction
37614 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
37615 **      called).
37616 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
37617 **    * The contents of the pager cache have not been modified.
37618 **    * The journal file may or may not be open.
37619 **    * Nothing (not even the first header) has been written to the journal.
37620 **
37621 **  WRITER_CACHEMOD:
37622 **
37623 **    A pager moves from WRITER_LOCKED state to this state when a page is
37624 **    first modified by the upper layer. In rollback mode the journal file
37625 **    is opened (if it is not already open) and a header written to the
37626 **    start of it. The database file on disk has not been modified.
37627 **
37628 **    * A write transaction is active.
37629 **    * A RESERVED or greater lock is held on the database file.
37630 **    * The journal file is open and the first header has been written 
37631 **      to it, but the header has not been synced to disk.
37632 **    * The contents of the page cache have been modified.
37633 **
37634 **  WRITER_DBMOD:
37635 **
37636 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
37637 **    when it modifies the contents of the database file. WAL connections
37638 **    never enter this state (since they do not modify the database file,
37639 **    just the log file).
37640 **
37641 **    * A write transaction is active.
37642 **    * An EXCLUSIVE or greater lock is held on the database file.
37643 **    * The journal file is open and the first header has been written 
37644 **      and synced to disk.
37645 **    * The contents of the page cache have been modified (and possibly
37646 **      written to disk).
37647 **
37648 **  WRITER_FINISHED:
37649 **
37650 **    It is not possible for a WAL connection to enter this state.
37651 **
37652 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
37653 **    state after the entire transaction has been successfully written into the
37654 **    database file. In this state the transaction may be committed simply
37655 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
37656 **    not possible to modify the database further. At this point, the upper 
37657 **    layer must either commit or rollback the transaction.
37658 **
37659 **    * A write transaction is active.
37660 **    * An EXCLUSIVE or greater lock is held on the database file.
37661 **    * All writing and syncing of journal and database data has finished.
37662 **      If no error occurred, all that remains is to finalize the journal to
37663 **      commit the transaction. If an error did occur, the caller will need
37664 **      to rollback the transaction. 
37665 **
37666 **  ERROR:
37667 **
37668 **    The ERROR state is entered when an IO or disk-full error (including
37669 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
37670 **    difficult to be sure that the in-memory pager state (cache contents, 
37671 **    db size etc.) are consistent with the contents of the file-system.
37672 **
37673 **    Temporary pager files may enter the ERROR state, but in-memory pagers
37674 **    cannot.
37675 **
37676 **    For example, if an IO error occurs while performing a rollback, 
37677 **    the contents of the page-cache may be left in an inconsistent state.
37678 **    At this point it would be dangerous to change back to READER state
37679 **    (as usually happens after a rollback). Any subsequent readers might
37680 **    report database corruption (due to the inconsistent cache), and if
37681 **    they upgrade to writers, they may inadvertently corrupt the database
37682 **    file. To avoid this hazard, the pager switches into the ERROR state
37683 **    instead of READER following such an error.
37684 **
37685 **    Once it has entered the ERROR state, any attempt to use the pager
37686 **    to read or write data returns an error. Eventually, once all 
37687 **    outstanding transactions have been abandoned, the pager is able to
37688 **    transition back to OPEN state, discarding the contents of the 
37689 **    page-cache and any other in-memory state at the same time. Everything
37690 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
37691 **    when a read-transaction is next opened on the pager (transitioning
37692 **    the pager into READER state). At that point the system has recovered 
37693 **    from the error.
37694 **
37695 **    Specifically, the pager jumps into the ERROR state if:
37696 **
37697 **      1. An error occurs while attempting a rollback. This happens in
37698 **         function sqlite3PagerRollback().
37699 **
37700 **      2. An error occurs while attempting to finalize a journal file
37701 **         following a commit in function sqlite3PagerCommitPhaseTwo().
37702 **
37703 **      3. An error occurs while attempting to write to the journal or
37704 **         database file in function pagerStress() in order to free up
37705 **         memory.
37706 **
37707 **    In other cases, the error is returned to the b-tree layer. The b-tree
37708 **    layer then attempts a rollback operation. If the error condition 
37709 **    persists, the pager enters the ERROR state via condition (1) above.
37710 **
37711 **    Condition (3) is necessary because it can be triggered by a read-only
37712 **    statement executed within a transaction. In this case, if the error
37713 **    code were simply returned to the user, the b-tree layer would not
37714 **    automatically attempt a rollback, as it assumes that an error in a
37715 **    read-only statement cannot leave the pager in an internally inconsistent 
37716 **    state.
37717 **
37718 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
37719 **    * There are one or more outstanding references to pages (after the
37720 **      last reference is dropped the pager should move back to OPEN state).
37721 **    * The pager is not an in-memory pager.
37722 **    
37723 **
37724 ** Notes:
37725 **
37726 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
37727 **     connection is open in WAL mode. A WAL connection is always in one
37728 **     of the first four states.
37729 **
37730 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
37731 **     state. There are two exceptions: immediately after exclusive-mode has
37732 **     been turned on (and before any read or write transactions are 
37733 **     executed), and when the pager is leaving the "error state".
37734 **
37735 **   * See also: assert_pager_state().
37736 */
37737 #define PAGER_OPEN                  0
37738 #define PAGER_READER                1
37739 #define PAGER_WRITER_LOCKED         2
37740 #define PAGER_WRITER_CACHEMOD       3
37741 #define PAGER_WRITER_DBMOD          4
37742 #define PAGER_WRITER_FINISHED       5
37743 #define PAGER_ERROR                 6
37744
37745 /*
37746 ** The Pager.eLock variable is almost always set to one of the 
37747 ** following locking-states, according to the lock currently held on
37748 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37749 ** This variable is kept up to date as locks are taken and released by
37750 ** the pagerLockDb() and pagerUnlockDb() wrappers.
37751 **
37752 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
37753 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
37754 ** the operation was successful. In these circumstances pagerLockDb() and
37755 ** pagerUnlockDb() take a conservative approach - eLock is always updated
37756 ** when unlocking the file, and only updated when locking the file if the
37757 ** VFS call is successful. This way, the Pager.eLock variable may be set
37758 ** to a less exclusive (lower) value than the lock that is actually held
37759 ** at the system level, but it is never set to a more exclusive value.
37760 **
37761 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
37762 ** be a few redundant xLock() calls or a lock may be held for longer than
37763 ** required, but nothing really goes wrong.
37764 **
37765 ** The exception is when the database file is unlocked as the pager moves
37766 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
37767 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
37768 ** transition, by the same pager or any other). If the call to xUnlock()
37769 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
37770 ** can confuse the call to xCheckReservedLock() call made later as part
37771 ** of hot-journal detection.
37772 **
37773 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
37774 ** lock held by this process or any others". So xCheckReservedLock may 
37775 ** return true because the caller itself is holding an EXCLUSIVE lock (but
37776 ** doesn't know it because of a previous error in xUnlock). If this happens
37777 ** a hot-journal may be mistaken for a journal being created by an active
37778 ** transaction in another process, causing SQLite to read from the database
37779 ** without rolling it back.
37780 **
37781 ** To work around this, if a call to xUnlock() fails when unlocking the
37782 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
37783 ** is only changed back to a real locking state after a successful call
37784 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
37785 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
37786 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
37787 ** lock on the database file before attempting to roll it back. See function
37788 ** PagerSharedLock() for more detail.
37789 **
37790 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
37791 ** PAGER_OPEN state.
37792 */
37793 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
37794
37795 /*
37796 ** A macro used for invoking the codec if there is one
37797 */
37798 #ifdef SQLITE_HAS_CODEC
37799 # define CODEC1(P,D,N,X,E) \
37800     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
37801 # define CODEC2(P,D,N,X,E,O) \
37802     if( P->xCodec==0 ){ O=(char*)D; }else \
37803     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
37804 #else
37805 # define CODEC1(P,D,N,X,E)   /* NO-OP */
37806 # define CODEC2(P,D,N,X,E,O) O=(char*)D
37807 #endif
37808
37809 /*
37810 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
37811 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
37812 ** This could conceivably cause corruption following a power failure on
37813 ** such a system. This is currently an undocumented limit.
37814 */
37815 #define MAX_SECTOR_SIZE 0x10000
37816
37817 /*
37818 ** An instance of the following structure is allocated for each active
37819 ** savepoint and statement transaction in the system. All such structures
37820 ** are stored in the Pager.aSavepoint[] array, which is allocated and
37821 ** resized using sqlite3Realloc().
37822 **
37823 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
37824 ** set to 0. If a journal-header is written into the main journal while
37825 ** the savepoint is active, then iHdrOffset is set to the byte offset 
37826 ** immediately following the last journal record written into the main
37827 ** journal before the journal-header. This is required during savepoint
37828 ** rollback (see pagerPlaybackSavepoint()).
37829 */
37830 typedef struct PagerSavepoint PagerSavepoint;
37831 struct PagerSavepoint {
37832   i64 iOffset;                 /* Starting offset in main journal */
37833   i64 iHdrOffset;              /* See above */
37834   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
37835   Pgno nOrig;                  /* Original number of pages in file */
37836   Pgno iSubRec;                /* Index of first record in sub-journal */
37837 #ifndef SQLITE_OMIT_WAL
37838   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
37839 #endif
37840 };
37841
37842 /*
37843 ** A open page cache is an instance of struct Pager. A description of
37844 ** some of the more important member variables follows:
37845 **
37846 ** eState
37847 **
37848 **   The current 'state' of the pager object. See the comment and state
37849 **   diagram above for a description of the pager state.
37850 **
37851 ** eLock
37852 **
37853 **   For a real on-disk database, the current lock held on the database file -
37854 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37855 **
37856 **   For a temporary or in-memory database (neither of which require any
37857 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
37858 **   databases always have Pager.exclusiveMode==1, this tricks the pager
37859 **   logic into thinking that it already has all the locks it will ever
37860 **   need (and no reason to release them).
37861 **
37862 **   In some (obscure) circumstances, this variable may also be set to
37863 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
37864 **   details.
37865 **
37866 ** changeCountDone
37867 **
37868 **   This boolean variable is used to make sure that the change-counter 
37869 **   (the 4-byte header field at byte offset 24 of the database file) is 
37870 **   not updated more often than necessary. 
37871 **
37872 **   It is set to true when the change-counter field is updated, which 
37873 **   can only happen if an exclusive lock is held on the database file.
37874 **   It is cleared (set to false) whenever an exclusive lock is 
37875 **   relinquished on the database file. Each time a transaction is committed,
37876 **   The changeCountDone flag is inspected. If it is true, the work of
37877 **   updating the change-counter is omitted for the current transaction.
37878 **
37879 **   This mechanism means that when running in exclusive mode, a connection 
37880 **   need only update the change-counter once, for the first transaction
37881 **   committed.
37882 **
37883 ** setMaster
37884 **
37885 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
37886 **   (or may not) specify a master-journal name to be written into the 
37887 **   journal file before it is synced to disk.
37888 **
37889 **   Whether or not a journal file contains a master-journal pointer affects 
37890 **   the way in which the journal file is finalized after the transaction is 
37891 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
37892 **   If a journal file does not contain a master-journal pointer, it is
37893 **   finalized by overwriting the first journal header with zeroes. If
37894 **   it does contain a master-journal pointer the journal file is finalized 
37895 **   by truncating it to zero bytes, just as if the connection were 
37896 **   running in "journal_mode=truncate" mode.
37897 **
37898 **   Journal files that contain master journal pointers cannot be finalized
37899 **   simply by overwriting the first journal-header with zeroes, as the
37900 **   master journal pointer could interfere with hot-journal rollback of any
37901 **   subsequently interrupted transaction that reuses the journal file.
37902 **
37903 **   The flag is cleared as soon as the journal file is finalized (either
37904 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
37905 **   journal file from being successfully finalized, the setMaster flag
37906 **   is cleared anyway (and the pager will move to ERROR state).
37907 **
37908 ** doNotSpill, doNotSyncSpill
37909 **
37910 **   These two boolean variables control the behavior of cache-spills
37911 **   (calls made by the pcache module to the pagerStress() routine to
37912 **   write cached data to the file-system in order to free up memory).
37913 **
37914 **   When doNotSpill is non-zero, writing to the database from pagerStress()
37915 **   is disabled altogether. This is done in a very obscure case that
37916 **   comes up during savepoint rollback that requires the pcache module
37917 **   to allocate a new page to prevent the journal file from being written
37918 **   while it is being traversed by code in pager_playback().
37919 ** 
37920 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
37921 **   is permitted, but syncing the journal file is not. This flag is set
37922 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
37923 **   the database page-size in order to prevent a journal sync from happening 
37924 **   in between the journalling of two pages on the same sector. 
37925 **
37926 ** subjInMemory
37927 **
37928 **   This is a boolean variable. If true, then any required sub-journal
37929 **   is opened as an in-memory journal file. If false, then in-memory
37930 **   sub-journals are only used for in-memory pager files.
37931 **
37932 **   This variable is updated by the upper layer each time a new 
37933 **   write-transaction is opened.
37934 **
37935 ** dbSize, dbOrigSize, dbFileSize
37936 **
37937 **   Variable dbSize is set to the number of pages in the database file.
37938 **   It is valid in PAGER_READER and higher states (all states except for
37939 **   OPEN and ERROR). 
37940 **
37941 **   dbSize is set based on the size of the database file, which may be 
37942 **   larger than the size of the database (the value stored at offset
37943 **   28 of the database header by the btree). If the size of the file
37944 **   is not an integer multiple of the page-size, the value stored in
37945 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
37946 **   Except, any file that is greater than 0 bytes in size is considered
37947 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
37948 **   to dbSize==1).
37949 **
37950 **   During a write-transaction, if pages with page-numbers greater than
37951 **   dbSize are modified in the cache, dbSize is updated accordingly.
37952 **   Similarly, if the database is truncated using PagerTruncateImage(), 
37953 **   dbSize is updated.
37954 **
37955 **   Variables dbOrigSize and dbFileSize are valid in states 
37956 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
37957 **   variable at the start of the transaction. It is used during rollback,
37958 **   and to determine whether or not pages need to be journalled before
37959 **   being modified.
37960 **
37961 **   Throughout a write-transaction, dbFileSize contains the size of
37962 **   the file on disk in pages. It is set to a copy of dbSize when the
37963 **   write-transaction is first opened, and updated when VFS calls are made
37964 **   to write or truncate the database file on disk. 
37965 **
37966 **   The only reason the dbFileSize variable is required is to suppress 
37967 **   unnecessary calls to xTruncate() after committing a transaction. If, 
37968 **   when a transaction is committed, the dbFileSize variable indicates 
37969 **   that the database file is larger than the database image (Pager.dbSize), 
37970 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
37971 **   to measure the database file on disk, and then truncates it if required.
37972 **   dbFileSize is not used when rolling back a transaction. In this case
37973 **   pager_truncate() is called unconditionally (which means there may be
37974 **   a call to xFilesize() that is not strictly required). In either case,
37975 **   pager_truncate() may cause the file to become smaller or larger.
37976 **
37977 ** dbHintSize
37978 **
37979 **   The dbHintSize variable is used to limit the number of calls made to
37980 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
37981 **
37982 **   dbHintSize is set to a copy of the dbSize variable when a
37983 **   write-transaction is opened (at the same time as dbFileSize and
37984 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
37985 **   dbHintSize is increased to the number of pages that correspond to the
37986 **   size-hint passed to the method call. See pager_write_pagelist() for 
37987 **   details.
37988 **
37989 ** errCode
37990 **
37991 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
37992 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
37993 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
37994 **   sub-codes.
37995 */
37996 struct Pager {
37997   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
37998   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
37999   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
38000   u8 useJournal;              /* Use a rollback journal on this file */
38001   u8 noSync;                  /* Do not sync the journal if true */
38002   u8 fullSync;                /* Do extra syncs of the journal for robustness */
38003   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
38004   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
38005   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
38006   u8 tempFile;                /* zFilename is a temporary file */
38007   u8 readOnly;                /* True for a read-only database */
38008   u8 memDb;                   /* True to inhibit all file I/O */
38009
38010   /**************************************************************************
38011   ** The following block contains those class members that change during
38012   ** routine opertion.  Class members not in this block are either fixed
38013   ** when the pager is first created or else only change when there is a
38014   ** significant mode change (such as changing the page_size, locking_mode,
38015   ** or the journal_mode).  From another view, these class members describe
38016   ** the "state" of the pager, while other class members describe the
38017   ** "configuration" of the pager.
38018   */
38019   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
38020   u8 eLock;                   /* Current lock held on database file */
38021   u8 changeCountDone;         /* Set after incrementing the change-counter */
38022   u8 setMaster;               /* True if a m-j name has been written to jrnl */
38023   u8 doNotSpill;              /* Do not spill the cache when non-zero */
38024   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
38025   u8 subjInMemory;            /* True to use in-memory sub-journals */
38026   Pgno dbSize;                /* Number of pages in the database */
38027   Pgno dbOrigSize;            /* dbSize before the current transaction */
38028   Pgno dbFileSize;            /* Number of pages in the database file */
38029   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
38030   int errCode;                /* One of several kinds of errors */
38031   int nRec;                   /* Pages journalled since last j-header written */
38032   u32 cksumInit;              /* Quasi-random value added to every checksum */
38033   u32 nSubRec;                /* Number of records written to sub-journal */
38034   Bitvec *pInJournal;         /* One bit for each page in the database file */
38035   sqlite3_file *fd;           /* File descriptor for database */
38036   sqlite3_file *jfd;          /* File descriptor for main journal */
38037   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
38038   i64 journalOff;             /* Current write offset in the journal file */
38039   i64 journalHdr;             /* Byte offset to previous journal header */
38040   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
38041   PagerSavepoint *aSavepoint; /* Array of active savepoints */
38042   int nSavepoint;             /* Number of elements in aSavepoint[] */
38043   char dbFileVers[16];        /* Changes whenever database file changes */
38044   /*
38045   ** End of the routinely-changing class members
38046   ***************************************************************************/
38047
38048   u16 nExtra;                 /* Add this many bytes to each in-memory page */
38049   i16 nReserve;               /* Number of unused bytes at end of each page */
38050   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
38051   u32 sectorSize;             /* Assumed sector size during rollback */
38052   int pageSize;               /* Number of bytes in a page */
38053   Pgno mxPgno;                /* Maximum allowed size of the database */
38054   i64 journalSizeLimit;       /* Size limit for persistent journal files */
38055   char *zFilename;            /* Name of the database file */
38056   char *zJournal;             /* Name of the journal file */
38057   int (*xBusyHandler)(void*); /* Function to call when busy */
38058   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
38059   int aStat[3];               /* Total cache hits, misses and writes */
38060 #ifdef SQLITE_TEST
38061   int nRead;                  /* Database pages read */
38062 #endif
38063   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
38064 #ifdef SQLITE_HAS_CODEC
38065   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
38066   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
38067   void (*xCodecFree)(void*);             /* Destructor for the codec */
38068   void *pCodec;               /* First argument to xCodec... methods */
38069 #endif
38070   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
38071   PCache *pPCache;            /* Pointer to page cache object */
38072 #ifndef SQLITE_OMIT_WAL
38073   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
38074   char *zWal;                 /* File name for write-ahead log */
38075 #endif
38076 };
38077
38078 /*
38079 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
38080 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS 
38081 ** or CACHE_WRITE to sqlite3_db_status().
38082 */
38083 #define PAGER_STAT_HIT   0
38084 #define PAGER_STAT_MISS  1
38085 #define PAGER_STAT_WRITE 2
38086
38087 /*
38088 ** The following global variables hold counters used for
38089 ** testing purposes only.  These variables do not exist in
38090 ** a non-testing build.  These variables are not thread-safe.
38091 */
38092 #ifdef SQLITE_TEST
38093 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
38094 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
38095 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
38096 # define PAGER_INCR(v)  v++
38097 #else
38098 # define PAGER_INCR(v)
38099 #endif
38100
38101
38102
38103 /*
38104 ** Journal files begin with the following magic string.  The data
38105 ** was obtained from /dev/random.  It is used only as a sanity check.
38106 **
38107 ** Since version 2.8.0, the journal format contains additional sanity
38108 ** checking information.  If the power fails while the journal is being
38109 ** written, semi-random garbage data might appear in the journal
38110 ** file after power is restored.  If an attempt is then made
38111 ** to roll the journal back, the database could be corrupted.  The additional
38112 ** sanity checking data is an attempt to discover the garbage in the
38113 ** journal and ignore it.
38114 **
38115 ** The sanity checking information for the new journal format consists
38116 ** of a 32-bit checksum on each page of data.  The checksum covers both
38117 ** the page number and the pPager->pageSize bytes of data for the page.
38118 ** This cksum is initialized to a 32-bit random value that appears in the
38119 ** journal file right after the header.  The random initializer is important,
38120 ** because garbage data that appears at the end of a journal is likely
38121 ** data that was once in other files that have now been deleted.  If the
38122 ** garbage data came from an obsolete journal file, the checksums might
38123 ** be correct.  But by initializing the checksum to random value which
38124 ** is different for every journal, we minimize that risk.
38125 */
38126 static const unsigned char aJournalMagic[] = {
38127   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
38128 };
38129
38130 /*
38131 ** The size of the of each page record in the journal is given by
38132 ** the following macro.
38133 */
38134 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
38135
38136 /*
38137 ** The journal header size for this pager. This is usually the same 
38138 ** size as a single disk sector. See also setSectorSize().
38139 */
38140 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
38141
38142 /*
38143 ** The macro MEMDB is true if we are dealing with an in-memory database.
38144 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
38145 ** the value of MEMDB will be a constant and the compiler will optimize
38146 ** out code that would never execute.
38147 */
38148 #ifdef SQLITE_OMIT_MEMORYDB
38149 # define MEMDB 0
38150 #else
38151 # define MEMDB pPager->memDb
38152 #endif
38153
38154 /*
38155 ** The maximum legal page number is (2^31 - 1).
38156 */
38157 #define PAGER_MAX_PGNO 2147483647
38158
38159 /*
38160 ** The argument to this macro is a file descriptor (type sqlite3_file*).
38161 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
38162 **
38163 ** This is so that expressions can be written as:
38164 **
38165 **   if( isOpen(pPager->jfd) ){ ...
38166 **
38167 ** instead of
38168 **
38169 **   if( pPager->jfd->pMethods ){ ...
38170 */
38171 #define isOpen(pFd) ((pFd)->pMethods)
38172
38173 /*
38174 ** Return true if this pager uses a write-ahead log instead of the usual
38175 ** rollback journal. Otherwise false.
38176 */
38177 #ifndef SQLITE_OMIT_WAL
38178 static int pagerUseWal(Pager *pPager){
38179   return (pPager->pWal!=0);
38180 }
38181 #else
38182 # define pagerUseWal(x) 0
38183 # define pagerRollbackWal(x) 0
38184 # define pagerWalFrames(v,w,x,y) 0
38185 # define pagerOpenWalIfPresent(z) SQLITE_OK
38186 # define pagerBeginReadTransaction(z) SQLITE_OK
38187 #endif
38188
38189 #ifndef NDEBUG 
38190 /*
38191 ** Usage:
38192 **
38193 **   assert( assert_pager_state(pPager) );
38194 **
38195 ** This function runs many asserts to try to find inconsistencies in
38196 ** the internal state of the Pager object.
38197 */
38198 static int assert_pager_state(Pager *p){
38199   Pager *pPager = p;
38200
38201   /* State must be valid. */
38202   assert( p->eState==PAGER_OPEN
38203        || p->eState==PAGER_READER
38204        || p->eState==PAGER_WRITER_LOCKED
38205        || p->eState==PAGER_WRITER_CACHEMOD
38206        || p->eState==PAGER_WRITER_DBMOD
38207        || p->eState==PAGER_WRITER_FINISHED
38208        || p->eState==PAGER_ERROR
38209   );
38210
38211   /* Regardless of the current state, a temp-file connection always behaves
38212   ** as if it has an exclusive lock on the database file. It never updates
38213   ** the change-counter field, so the changeCountDone flag is always set.
38214   */
38215   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
38216   assert( p->tempFile==0 || pPager->changeCountDone );
38217
38218   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
38219   ** And if the journal-mode is "OFF", the journal file must not be open.
38220   */
38221   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
38222   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
38223
38224   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
38225   ** this means an in-memory pager performs no IO at all, it cannot encounter 
38226   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
38227   ** a journal file. (although the in-memory journal implementation may 
38228   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
38229   ** is therefore not possible for an in-memory pager to enter the ERROR 
38230   ** state.
38231   */
38232   if( MEMDB ){
38233     assert( p->noSync );
38234     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
38235          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
38236     );
38237     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
38238     assert( pagerUseWal(p)==0 );
38239   }
38240
38241   /* If changeCountDone is set, a RESERVED lock or greater must be held
38242   ** on the file.
38243   */
38244   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
38245   assert( p->eLock!=PENDING_LOCK );
38246
38247   switch( p->eState ){
38248     case PAGER_OPEN:
38249       assert( !MEMDB );
38250       assert( pPager->errCode==SQLITE_OK );
38251       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
38252       break;
38253
38254     case PAGER_READER:
38255       assert( pPager->errCode==SQLITE_OK );
38256       assert( p->eLock!=UNKNOWN_LOCK );
38257       assert( p->eLock>=SHARED_LOCK );
38258       break;
38259
38260     case PAGER_WRITER_LOCKED:
38261       assert( p->eLock!=UNKNOWN_LOCK );
38262       assert( pPager->errCode==SQLITE_OK );
38263       if( !pagerUseWal(pPager) ){
38264         assert( p->eLock>=RESERVED_LOCK );
38265       }
38266       assert( pPager->dbSize==pPager->dbOrigSize );
38267       assert( pPager->dbOrigSize==pPager->dbFileSize );
38268       assert( pPager->dbOrigSize==pPager->dbHintSize );
38269       assert( pPager->setMaster==0 );
38270       break;
38271
38272     case PAGER_WRITER_CACHEMOD:
38273       assert( p->eLock!=UNKNOWN_LOCK );
38274       assert( pPager->errCode==SQLITE_OK );
38275       if( !pagerUseWal(pPager) ){
38276         /* It is possible that if journal_mode=wal here that neither the
38277         ** journal file nor the WAL file are open. This happens during
38278         ** a rollback transaction that switches from journal_mode=off
38279         ** to journal_mode=wal.
38280         */
38281         assert( p->eLock>=RESERVED_LOCK );
38282         assert( isOpen(p->jfd) 
38283              || p->journalMode==PAGER_JOURNALMODE_OFF 
38284              || p->journalMode==PAGER_JOURNALMODE_WAL 
38285         );
38286       }
38287       assert( pPager->dbOrigSize==pPager->dbFileSize );
38288       assert( pPager->dbOrigSize==pPager->dbHintSize );
38289       break;
38290
38291     case PAGER_WRITER_DBMOD:
38292       assert( p->eLock==EXCLUSIVE_LOCK );
38293       assert( pPager->errCode==SQLITE_OK );
38294       assert( !pagerUseWal(pPager) );
38295       assert( p->eLock>=EXCLUSIVE_LOCK );
38296       assert( isOpen(p->jfd) 
38297            || p->journalMode==PAGER_JOURNALMODE_OFF 
38298            || p->journalMode==PAGER_JOURNALMODE_WAL 
38299       );
38300       assert( pPager->dbOrigSize<=pPager->dbHintSize );
38301       break;
38302
38303     case PAGER_WRITER_FINISHED:
38304       assert( p->eLock==EXCLUSIVE_LOCK );
38305       assert( pPager->errCode==SQLITE_OK );
38306       assert( !pagerUseWal(pPager) );
38307       assert( isOpen(p->jfd) 
38308            || p->journalMode==PAGER_JOURNALMODE_OFF 
38309            || p->journalMode==PAGER_JOURNALMODE_WAL 
38310       );
38311       break;
38312
38313     case PAGER_ERROR:
38314       /* There must be at least one outstanding reference to the pager if
38315       ** in ERROR state. Otherwise the pager should have already dropped
38316       ** back to OPEN state.
38317       */
38318       assert( pPager->errCode!=SQLITE_OK );
38319       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
38320       break;
38321   }
38322
38323   return 1;
38324 }
38325 #endif /* ifndef NDEBUG */
38326
38327 #ifdef SQLITE_DEBUG 
38328 /*
38329 ** Return a pointer to a human readable string in a static buffer
38330 ** containing the state of the Pager object passed as an argument. This
38331 ** is intended to be used within debuggers. For example, as an alternative
38332 ** to "print *pPager" in gdb:
38333 **
38334 ** (gdb) printf "%s", print_pager_state(pPager)
38335 */
38336 static char *print_pager_state(Pager *p){
38337   static char zRet[1024];
38338
38339   sqlite3_snprintf(1024, zRet,
38340       "Filename:      %s\n"
38341       "State:         %s errCode=%d\n"
38342       "Lock:          %s\n"
38343       "Locking mode:  locking_mode=%s\n"
38344       "Journal mode:  journal_mode=%s\n"
38345       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
38346       "Journal:       journalOff=%lld journalHdr=%lld\n"
38347       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
38348       , p->zFilename
38349       , p->eState==PAGER_OPEN            ? "OPEN" :
38350         p->eState==PAGER_READER          ? "READER" :
38351         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
38352         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
38353         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
38354         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
38355         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
38356       , (int)p->errCode
38357       , p->eLock==NO_LOCK         ? "NO_LOCK" :
38358         p->eLock==RESERVED_LOCK   ? "RESERVED" :
38359         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
38360         p->eLock==SHARED_LOCK     ? "SHARED" :
38361         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
38362       , p->exclusiveMode ? "exclusive" : "normal"
38363       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
38364         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
38365         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
38366         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
38367         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
38368         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
38369       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
38370       , p->journalOff, p->journalHdr
38371       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
38372   );
38373
38374   return zRet;
38375 }
38376 #endif
38377
38378 /*
38379 ** Return true if it is necessary to write page *pPg into the sub-journal.
38380 ** A page needs to be written into the sub-journal if there exists one
38381 ** or more open savepoints for which:
38382 **
38383 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
38384 **   * The bit corresponding to the page-number is not set in
38385 **     PagerSavepoint.pInSavepoint.
38386 */
38387 static int subjRequiresPage(PgHdr *pPg){
38388   Pgno pgno = pPg->pgno;
38389   Pager *pPager = pPg->pPager;
38390   int i;
38391   for(i=0; i<pPager->nSavepoint; i++){
38392     PagerSavepoint *p = &pPager->aSavepoint[i];
38393     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
38394       return 1;
38395     }
38396   }
38397   return 0;
38398 }
38399
38400 /*
38401 ** Return true if the page is already in the journal file.
38402 */
38403 static int pageInJournal(PgHdr *pPg){
38404   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
38405 }
38406
38407 /*
38408 ** Read a 32-bit integer from the given file descriptor.  Store the integer
38409 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
38410 ** error code is something goes wrong.
38411 **
38412 ** All values are stored on disk as big-endian.
38413 */
38414 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
38415   unsigned char ac[4];
38416   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
38417   if( rc==SQLITE_OK ){
38418     *pRes = sqlite3Get4byte(ac);
38419   }
38420   return rc;
38421 }
38422
38423 /*
38424 ** Write a 32-bit integer into a string buffer in big-endian byte order.
38425 */
38426 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
38427
38428
38429 /*
38430 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
38431 ** on success or an error code is something goes wrong.
38432 */
38433 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
38434   char ac[4];
38435   put32bits(ac, val);
38436   return sqlite3OsWrite(fd, ac, 4, offset);
38437 }
38438
38439 /*
38440 ** Unlock the database file to level eLock, which must be either NO_LOCK
38441 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
38442 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
38443 **
38444 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
38445 ** called, do not modify it. See the comment above the #define of 
38446 ** UNKNOWN_LOCK for an explanation of this.
38447 */
38448 static int pagerUnlockDb(Pager *pPager, int eLock){
38449   int rc = SQLITE_OK;
38450
38451   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
38452   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
38453   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
38454   if( isOpen(pPager->fd) ){
38455     assert( pPager->eLock>=eLock );
38456     rc = sqlite3OsUnlock(pPager->fd, eLock);
38457     if( pPager->eLock!=UNKNOWN_LOCK ){
38458       pPager->eLock = (u8)eLock;
38459     }
38460     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
38461   }
38462   return rc;
38463 }
38464
38465 /*
38466 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
38467 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
38468 ** Pager.eLock variable to the new locking state. 
38469 **
38470 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
38471 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
38472 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
38473 ** of this.
38474 */
38475 static int pagerLockDb(Pager *pPager, int eLock){
38476   int rc = SQLITE_OK;
38477
38478   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
38479   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
38480     rc = sqlite3OsLock(pPager->fd, eLock);
38481     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
38482       pPager->eLock = (u8)eLock;
38483       IOTRACE(("LOCK %p %d\n", pPager, eLock))
38484     }
38485   }
38486   return rc;
38487 }
38488
38489 /*
38490 ** This function determines whether or not the atomic-write optimization
38491 ** can be used with this pager. The optimization can be used if:
38492 **
38493 **  (a) the value returned by OsDeviceCharacteristics() indicates that
38494 **      a database page may be written atomically, and
38495 **  (b) the value returned by OsSectorSize() is less than or equal
38496 **      to the page size.
38497 **
38498 ** The optimization is also always enabled for temporary files. It is
38499 ** an error to call this function if pPager is opened on an in-memory
38500 ** database.
38501 **
38502 ** If the optimization cannot be used, 0 is returned. If it can be used,
38503 ** then the value returned is the size of the journal file when it
38504 ** contains rollback data for exactly one page.
38505 */
38506 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
38507 static int jrnlBufferSize(Pager *pPager){
38508   assert( !MEMDB );
38509   if( !pPager->tempFile ){
38510     int dc;                           /* Device characteristics */
38511     int nSector;                      /* Sector size */
38512     int szPage;                       /* Page size */
38513
38514     assert( isOpen(pPager->fd) );
38515     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
38516     nSector = pPager->sectorSize;
38517     szPage = pPager->pageSize;
38518
38519     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
38520     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
38521     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
38522       return 0;
38523     }
38524   }
38525
38526   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
38527 }
38528 #endif
38529
38530 /*
38531 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
38532 ** on the cache using a hash function.  This is used for testing
38533 ** and debugging only.
38534 */
38535 #ifdef SQLITE_CHECK_PAGES
38536 /*
38537 ** Return a 32-bit hash of the page data for pPage.
38538 */
38539 static u32 pager_datahash(int nByte, unsigned char *pData){
38540   u32 hash = 0;
38541   int i;
38542   for(i=0; i<nByte; i++){
38543     hash = (hash*1039) + pData[i];
38544   }
38545   return hash;
38546 }
38547 static u32 pager_pagehash(PgHdr *pPage){
38548   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
38549 }
38550 static void pager_set_pagehash(PgHdr *pPage){
38551   pPage->pageHash = pager_pagehash(pPage);
38552 }
38553
38554 /*
38555 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
38556 ** is defined, and NDEBUG is not defined, an assert() statement checks
38557 ** that the page is either dirty or still matches the calculated page-hash.
38558 */
38559 #define CHECK_PAGE(x) checkPage(x)
38560 static void checkPage(PgHdr *pPg){
38561   Pager *pPager = pPg->pPager;
38562   assert( pPager->eState!=PAGER_ERROR );
38563   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
38564 }
38565
38566 #else
38567 #define pager_datahash(X,Y)  0
38568 #define pager_pagehash(X)  0
38569 #define pager_set_pagehash(X)
38570 #define CHECK_PAGE(x)
38571 #endif  /* SQLITE_CHECK_PAGES */
38572
38573 /*
38574 ** When this is called the journal file for pager pPager must be open.
38575 ** This function attempts to read a master journal file name from the 
38576 ** end of the file and, if successful, copies it into memory supplied 
38577 ** by the caller. See comments above writeMasterJournal() for the format
38578 ** used to store a master journal file name at the end of a journal file.
38579 **
38580 ** zMaster must point to a buffer of at least nMaster bytes allocated by
38581 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
38582 ** enough space to write the master journal name). If the master journal
38583 ** name in the journal is longer than nMaster bytes (including a
38584 ** nul-terminator), then this is handled as if no master journal name
38585 ** were present in the journal.
38586 **
38587 ** If a master journal file name is present at the end of the journal
38588 ** file, then it is copied into the buffer pointed to by zMaster. A
38589 ** nul-terminator byte is appended to the buffer following the master
38590 ** journal file name.
38591 **
38592 ** If it is determined that no master journal file name is present 
38593 ** zMaster[0] is set to 0 and SQLITE_OK returned.
38594 **
38595 ** If an error occurs while reading from the journal file, an SQLite
38596 ** error code is returned.
38597 */
38598 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
38599   int rc;                    /* Return code */
38600   u32 len;                   /* Length in bytes of master journal name */
38601   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
38602   u32 cksum;                 /* MJ checksum value read from journal */
38603   u32 u;                     /* Unsigned loop counter */
38604   unsigned char aMagic[8];   /* A buffer to hold the magic header */
38605   zMaster[0] = '\0';
38606
38607   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
38608    || szJ<16
38609    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
38610    || len>=nMaster 
38611    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
38612    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
38613    || memcmp(aMagic, aJournalMagic, 8)
38614    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
38615   ){
38616     return rc;
38617   }
38618
38619   /* See if the checksum matches the master journal name */
38620   for(u=0; u<len; u++){
38621     cksum -= zMaster[u];
38622   }
38623   if( cksum ){
38624     /* If the checksum doesn't add up, then one or more of the disk sectors
38625     ** containing the master journal filename is corrupted. This means
38626     ** definitely roll back, so just return SQLITE_OK and report a (nul)
38627     ** master-journal filename.
38628     */
38629     len = 0;
38630   }
38631   zMaster[len] = '\0';
38632    
38633   return SQLITE_OK;
38634 }
38635
38636 /*
38637 ** Return the offset of the sector boundary at or immediately 
38638 ** following the value in pPager->journalOff, assuming a sector 
38639 ** size of pPager->sectorSize bytes.
38640 **
38641 ** i.e for a sector size of 512:
38642 **
38643 **   Pager.journalOff          Return value
38644 **   ---------------------------------------
38645 **   0                         0
38646 **   512                       512
38647 **   100                       512
38648 **   2000                      2048
38649 ** 
38650 */
38651 static i64 journalHdrOffset(Pager *pPager){
38652   i64 offset = 0;
38653   i64 c = pPager->journalOff;
38654   if( c ){
38655     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
38656   }
38657   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
38658   assert( offset>=c );
38659   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
38660   return offset;
38661 }
38662
38663 /*
38664 ** The journal file must be open when this function is called.
38665 **
38666 ** This function is a no-op if the journal file has not been written to
38667 ** within the current transaction (i.e. if Pager.journalOff==0).
38668 **
38669 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
38670 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
38671 ** zero the 28-byte header at the start of the journal file. In either case, 
38672 ** if the pager is not in no-sync mode, sync the journal file immediately 
38673 ** after writing or truncating it.
38674 **
38675 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
38676 ** following the truncation or zeroing described above the size of the 
38677 ** journal file in bytes is larger than this value, then truncate the
38678 ** journal file to Pager.journalSizeLimit bytes. The journal file does
38679 ** not need to be synced following this operation.
38680 **
38681 ** If an IO error occurs, abandon processing and return the IO error code.
38682 ** Otherwise, return SQLITE_OK.
38683 */
38684 static int zeroJournalHdr(Pager *pPager, int doTruncate){
38685   int rc = SQLITE_OK;                               /* Return code */
38686   assert( isOpen(pPager->jfd) );
38687   if( pPager->journalOff ){
38688     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
38689
38690     IOTRACE(("JZEROHDR %p\n", pPager))
38691     if( doTruncate || iLimit==0 ){
38692       rc = sqlite3OsTruncate(pPager->jfd, 0);
38693     }else{
38694       static const char zeroHdr[28] = {0};
38695       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
38696     }
38697     if( rc==SQLITE_OK && !pPager->noSync ){
38698       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
38699     }
38700
38701     /* At this point the transaction is committed but the write lock 
38702     ** is still held on the file. If there is a size limit configured for 
38703     ** the persistent journal and the journal file currently consumes more
38704     ** space than that limit allows for, truncate it now. There is no need
38705     ** to sync the file following this operation.
38706     */
38707     if( rc==SQLITE_OK && iLimit>0 ){
38708       i64 sz;
38709       rc = sqlite3OsFileSize(pPager->jfd, &sz);
38710       if( rc==SQLITE_OK && sz>iLimit ){
38711         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
38712       }
38713     }
38714   }
38715   return rc;
38716 }
38717
38718 /*
38719 ** The journal file must be open when this routine is called. A journal
38720 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
38721 ** current location.
38722 **
38723 ** The format for the journal header is as follows:
38724 ** - 8 bytes: Magic identifying journal format.
38725 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
38726 ** - 4 bytes: Random number used for page hash.
38727 ** - 4 bytes: Initial database page count.
38728 ** - 4 bytes: Sector size used by the process that wrote this journal.
38729 ** - 4 bytes: Database page size.
38730 ** 
38731 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
38732 */
38733 static int writeJournalHdr(Pager *pPager){
38734   int rc = SQLITE_OK;                 /* Return code */
38735   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
38736   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
38737   u32 nWrite;                         /* Bytes of header sector written */
38738   int ii;                             /* Loop counter */
38739
38740   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
38741
38742   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
38743     nHeader = JOURNAL_HDR_SZ(pPager);
38744   }
38745
38746   /* If there are active savepoints and any of them were created 
38747   ** since the most recent journal header was written, update the 
38748   ** PagerSavepoint.iHdrOffset fields now.
38749   */
38750   for(ii=0; ii<pPager->nSavepoint; ii++){
38751     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
38752       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
38753     }
38754   }
38755
38756   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
38757
38758   /* 
38759   ** Write the nRec Field - the number of page records that follow this
38760   ** journal header. Normally, zero is written to this value at this time.
38761   ** After the records are added to the journal (and the journal synced, 
38762   ** if in full-sync mode), the zero is overwritten with the true number
38763   ** of records (see syncJournal()).
38764   **
38765   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
38766   ** reading the journal this value tells SQLite to assume that the
38767   ** rest of the journal file contains valid page records. This assumption
38768   ** is dangerous, as if a failure occurred whilst writing to the journal
38769   ** file it may contain some garbage data. There are two scenarios
38770   ** where this risk can be ignored:
38771   **
38772   **   * When the pager is in no-sync mode. Corruption can follow a
38773   **     power failure in this case anyway.
38774   **
38775   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
38776   **     that garbage data is never appended to the journal file.
38777   */
38778   assert( isOpen(pPager->fd) || pPager->noSync );
38779   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
38780    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
38781   ){
38782     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
38783     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
38784   }else{
38785     memset(zHeader, 0, sizeof(aJournalMagic)+4);
38786   }
38787
38788   /* The random check-hash initializer */ 
38789   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
38790   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
38791   /* The initial database size */
38792   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
38793   /* The assumed sector size for this process */
38794   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
38795
38796   /* The page size */
38797   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
38798
38799   /* Initializing the tail of the buffer is not necessary.  Everything
38800   ** works find if the following memset() is omitted.  But initializing
38801   ** the memory prevents valgrind from complaining, so we are willing to
38802   ** take the performance hit.
38803   */
38804   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
38805          nHeader-(sizeof(aJournalMagic)+20));
38806
38807   /* In theory, it is only necessary to write the 28 bytes that the 
38808   ** journal header consumes to the journal file here. Then increment the 
38809   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
38810   ** record is written to the following sector (leaving a gap in the file
38811   ** that will be implicitly filled in by the OS).
38812   **
38813   ** However it has been discovered that on some systems this pattern can 
38814   ** be significantly slower than contiguously writing data to the file,
38815   ** even if that means explicitly writing data to the block of 
38816   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
38817   ** is done. 
38818   **
38819   ** The loop is required here in case the sector-size is larger than the 
38820   ** database page size. Since the zHeader buffer is only Pager.pageSize
38821   ** bytes in size, more than one call to sqlite3OsWrite() may be required
38822   ** to populate the entire journal header sector.
38823   */ 
38824   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
38825     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
38826     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
38827     assert( pPager->journalHdr <= pPager->journalOff );
38828     pPager->journalOff += nHeader;
38829   }
38830
38831   return rc;
38832 }
38833
38834 /*
38835 ** The journal file must be open when this is called. A journal header file
38836 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
38837 ** file. The current location in the journal file is given by
38838 ** pPager->journalOff. See comments above function writeJournalHdr() for
38839 ** a description of the journal header format.
38840 **
38841 ** If the header is read successfully, *pNRec is set to the number of
38842 ** page records following this header and *pDbSize is set to the size of the
38843 ** database before the transaction began, in pages. Also, pPager->cksumInit
38844 ** is set to the value read from the journal header. SQLITE_OK is returned
38845 ** in this case.
38846 **
38847 ** If the journal header file appears to be corrupted, SQLITE_DONE is
38848 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
38849 ** cannot be read from the journal file an error code is returned.
38850 */
38851 static int readJournalHdr(
38852   Pager *pPager,               /* Pager object */
38853   int isHot,
38854   i64 journalSize,             /* Size of the open journal file in bytes */
38855   u32 *pNRec,                  /* OUT: Value read from the nRec field */
38856   u32 *pDbSize                 /* OUT: Value of original database size field */
38857 ){
38858   int rc;                      /* Return code */
38859   unsigned char aMagic[8];     /* A buffer to hold the magic header */
38860   i64 iHdrOff;                 /* Offset of journal header being read */
38861
38862   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
38863
38864   /* Advance Pager.journalOff to the start of the next sector. If the
38865   ** journal file is too small for there to be a header stored at this
38866   ** point, return SQLITE_DONE.
38867   */
38868   pPager->journalOff = journalHdrOffset(pPager);
38869   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
38870     return SQLITE_DONE;
38871   }
38872   iHdrOff = pPager->journalOff;
38873
38874   /* Read in the first 8 bytes of the journal header. If they do not match
38875   ** the  magic string found at the start of each journal header, return
38876   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
38877   ** proceed.
38878   */
38879   if( isHot || iHdrOff!=pPager->journalHdr ){
38880     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
38881     if( rc ){
38882       return rc;
38883     }
38884     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
38885       return SQLITE_DONE;
38886     }
38887   }
38888
38889   /* Read the first three 32-bit fields of the journal header: The nRec
38890   ** field, the checksum-initializer and the database size at the start
38891   ** of the transaction. Return an error code if anything goes wrong.
38892   */
38893   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
38894    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
38895    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
38896   ){
38897     return rc;
38898   }
38899
38900   if( pPager->journalOff==0 ){
38901     u32 iPageSize;               /* Page-size field of journal header */
38902     u32 iSectorSize;             /* Sector-size field of journal header */
38903
38904     /* Read the page-size and sector-size journal header fields. */
38905     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
38906      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
38907     ){
38908       return rc;
38909     }
38910
38911     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
38912     ** journal header to zero. In this case, assume that the Pager.pageSize
38913     ** variable is already set to the correct page size.
38914     */
38915     if( iPageSize==0 ){
38916       iPageSize = pPager->pageSize;
38917     }
38918
38919     /* Check that the values read from the page-size and sector-size fields
38920     ** are within range. To be 'in range', both values need to be a power
38921     ** of two greater than or equal to 512 or 32, and not greater than their 
38922     ** respective compile time maximum limits.
38923     */
38924     if( iPageSize<512                  || iSectorSize<32
38925      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
38926      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
38927     ){
38928       /* If the either the page-size or sector-size in the journal-header is 
38929       ** invalid, then the process that wrote the journal-header must have 
38930       ** crashed before the header was synced. In this case stop reading 
38931       ** the journal file here.
38932       */
38933       return SQLITE_DONE;
38934     }
38935
38936     /* Update the page-size to match the value read from the journal. 
38937     ** Use a testcase() macro to make sure that malloc failure within 
38938     ** PagerSetPagesize() is tested.
38939     */
38940     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
38941     testcase( rc!=SQLITE_OK );
38942
38943     /* Update the assumed sector-size to match the value used by 
38944     ** the process that created this journal. If this journal was
38945     ** created by a process other than this one, then this routine
38946     ** is being called from within pager_playback(). The local value
38947     ** of Pager.sectorSize is restored at the end of that routine.
38948     */
38949     pPager->sectorSize = iSectorSize;
38950   }
38951
38952   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
38953   return rc;
38954 }
38955
38956
38957 /*
38958 ** Write the supplied master journal name into the journal file for pager
38959 ** pPager at the current location. The master journal name must be the last
38960 ** thing written to a journal file. If the pager is in full-sync mode, the
38961 ** journal file descriptor is advanced to the next sector boundary before
38962 ** anything is written. The format is:
38963 **
38964 **   + 4 bytes: PAGER_MJ_PGNO.
38965 **   + N bytes: Master journal filename in utf-8.
38966 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
38967 **   + 4 bytes: Master journal name checksum.
38968 **   + 8 bytes: aJournalMagic[].
38969 **
38970 ** The master journal page checksum is the sum of the bytes in the master
38971 ** journal name, where each byte is interpreted as a signed 8-bit integer.
38972 **
38973 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
38974 ** this call is a no-op.
38975 */
38976 static int writeMasterJournal(Pager *pPager, const char *zMaster){
38977   int rc;                          /* Return code */
38978   int nMaster;                     /* Length of string zMaster */
38979   i64 iHdrOff;                     /* Offset of header in journal file */
38980   i64 jrnlSize;                    /* Size of journal file on disk */
38981   u32 cksum = 0;                   /* Checksum of string zMaster */
38982
38983   assert( pPager->setMaster==0 );
38984   assert( !pagerUseWal(pPager) );
38985
38986   if( !zMaster 
38987    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
38988    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
38989   ){
38990     return SQLITE_OK;
38991   }
38992   pPager->setMaster = 1;
38993   assert( isOpen(pPager->jfd) );
38994   assert( pPager->journalHdr <= pPager->journalOff );
38995
38996   /* Calculate the length in bytes and the checksum of zMaster */
38997   for(nMaster=0; zMaster[nMaster]; nMaster++){
38998     cksum += zMaster[nMaster];
38999   }
39000
39001   /* If in full-sync mode, advance to the next disk sector before writing
39002   ** the master journal name. This is in case the previous page written to
39003   ** the journal has already been synced.
39004   */
39005   if( pPager->fullSync ){
39006     pPager->journalOff = journalHdrOffset(pPager);
39007   }
39008   iHdrOff = pPager->journalOff;
39009
39010   /* Write the master journal data to the end of the journal file. If
39011   ** an error occurs, return the error code to the caller.
39012   */
39013   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
39014    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
39015    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
39016    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
39017    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
39018   ){
39019     return rc;
39020   }
39021   pPager->journalOff += (nMaster+20);
39022
39023   /* If the pager is in peristent-journal mode, then the physical 
39024   ** journal-file may extend past the end of the master-journal name
39025   ** and 8 bytes of magic data just written to the file. This is 
39026   ** dangerous because the code to rollback a hot-journal file
39027   ** will not be able to find the master-journal name to determine 
39028   ** whether or not the journal is hot. 
39029   **
39030   ** Easiest thing to do in this scenario is to truncate the journal 
39031   ** file to the required size.
39032   */ 
39033   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
39034    && jrnlSize>pPager->journalOff
39035   ){
39036     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
39037   }
39038   return rc;
39039 }
39040
39041 /*
39042 ** Find a page in the hash table given its page number. Return
39043 ** a pointer to the page or NULL if the requested page is not 
39044 ** already in memory.
39045 */
39046 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
39047   PgHdr *p;                         /* Return value */
39048
39049   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
39050   ** fail, since no attempt to allocate dynamic memory will be made.
39051   */
39052   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
39053   return p;
39054 }
39055
39056 /*
39057 ** Discard the entire contents of the in-memory page-cache.
39058 */
39059 static void pager_reset(Pager *pPager){
39060   sqlite3BackupRestart(pPager->pBackup);
39061   sqlite3PcacheClear(pPager->pPCache);
39062 }
39063
39064 /*
39065 ** Free all structures in the Pager.aSavepoint[] array and set both
39066 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
39067 ** if it is open and the pager is not in exclusive mode.
39068 */
39069 static void releaseAllSavepoints(Pager *pPager){
39070   int ii;               /* Iterator for looping through Pager.aSavepoint */
39071   for(ii=0; ii<pPager->nSavepoint; ii++){
39072     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
39073   }
39074   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
39075     sqlite3OsClose(pPager->sjfd);
39076   }
39077   sqlite3_free(pPager->aSavepoint);
39078   pPager->aSavepoint = 0;
39079   pPager->nSavepoint = 0;
39080   pPager->nSubRec = 0;
39081 }
39082
39083 /*
39084 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
39085 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
39086 ** or SQLITE_NOMEM if a malloc failure occurs.
39087 */
39088 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
39089   int ii;                   /* Loop counter */
39090   int rc = SQLITE_OK;       /* Result code */
39091
39092   for(ii=0; ii<pPager->nSavepoint; ii++){
39093     PagerSavepoint *p = &pPager->aSavepoint[ii];
39094     if( pgno<=p->nOrig ){
39095       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
39096       testcase( rc==SQLITE_NOMEM );
39097       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
39098     }
39099   }
39100   return rc;
39101 }
39102
39103 /*
39104 ** This function is a no-op if the pager is in exclusive mode and not
39105 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
39106 ** state.
39107 **
39108 ** If the pager is not in exclusive-access mode, the database file is
39109 ** completely unlocked. If the file is unlocked and the file-system does
39110 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
39111 ** closed (if it is open).
39112 **
39113 ** If the pager is in ERROR state when this function is called, the 
39114 ** contents of the pager cache are discarded before switching back to 
39115 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
39116 ** or not, any journal file left in the file-system will be treated
39117 ** as a hot-journal and rolled back the next time a read-transaction
39118 ** is opened (by this or by any other connection).
39119 */
39120 static void pager_unlock(Pager *pPager){
39121
39122   assert( pPager->eState==PAGER_READER 
39123        || pPager->eState==PAGER_OPEN 
39124        || pPager->eState==PAGER_ERROR 
39125   );
39126
39127   sqlite3BitvecDestroy(pPager->pInJournal);
39128   pPager->pInJournal = 0;
39129   releaseAllSavepoints(pPager);
39130
39131   if( pagerUseWal(pPager) ){
39132     assert( !isOpen(pPager->jfd) );
39133     sqlite3WalEndReadTransaction(pPager->pWal);
39134     pPager->eState = PAGER_OPEN;
39135   }else if( !pPager->exclusiveMode ){
39136     int rc;                       /* Error code returned by pagerUnlockDb() */
39137     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
39138
39139     /* If the operating system support deletion of open files, then
39140     ** close the journal file when dropping the database lock.  Otherwise
39141     ** another connection with journal_mode=delete might delete the file
39142     ** out from under us.
39143     */
39144     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
39145     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
39146     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
39147     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
39148     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
39149     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
39150     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
39151      || 1!=(pPager->journalMode & 5)
39152     ){
39153       sqlite3OsClose(pPager->jfd);
39154     }
39155
39156     /* If the pager is in the ERROR state and the call to unlock the database
39157     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
39158     ** above the #define for UNKNOWN_LOCK for an explanation of why this
39159     ** is necessary.
39160     */
39161     rc = pagerUnlockDb(pPager, NO_LOCK);
39162     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
39163       pPager->eLock = UNKNOWN_LOCK;
39164     }
39165
39166     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
39167     ** without clearing the error code. This is intentional - the error
39168     ** code is cleared and the cache reset in the block below.
39169     */
39170     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
39171     pPager->changeCountDone = 0;
39172     pPager->eState = PAGER_OPEN;
39173   }
39174
39175   /* If Pager.errCode is set, the contents of the pager cache cannot be
39176   ** trusted. Now that there are no outstanding references to the pager,
39177   ** it can safely move back to PAGER_OPEN state. This happens in both
39178   ** normal and exclusive-locking mode.
39179   */
39180   if( pPager->errCode ){
39181     assert( !MEMDB );
39182     pager_reset(pPager);
39183     pPager->changeCountDone = pPager->tempFile;
39184     pPager->eState = PAGER_OPEN;
39185     pPager->errCode = SQLITE_OK;
39186   }
39187
39188   pPager->journalOff = 0;
39189   pPager->journalHdr = 0;
39190   pPager->setMaster = 0;
39191 }
39192
39193 /*
39194 ** This function is called whenever an IOERR or FULL error that requires
39195 ** the pager to transition into the ERROR state may ahve occurred.
39196 ** The first argument is a pointer to the pager structure, the second 
39197 ** the error-code about to be returned by a pager API function. The 
39198 ** value returned is a copy of the second argument to this function. 
39199 **
39200 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
39201 ** IOERR sub-codes, the pager enters the ERROR state and the error code
39202 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
39203 ** all major API calls on the Pager will immediately return Pager.errCode.
39204 **
39205 ** The ERROR state indicates that the contents of the pager-cache 
39206 ** cannot be trusted. This state can be cleared by completely discarding 
39207 ** the contents of the pager-cache. If a transaction was active when
39208 ** the persistent error occurred, then the rollback journal may need
39209 ** to be replayed to restore the contents of the database file (as if
39210 ** it were a hot-journal).
39211 */
39212 static int pager_error(Pager *pPager, int rc){
39213   int rc2 = rc & 0xff;
39214   assert( rc==SQLITE_OK || !MEMDB );
39215   assert(
39216        pPager->errCode==SQLITE_FULL ||
39217        pPager->errCode==SQLITE_OK ||
39218        (pPager->errCode & 0xff)==SQLITE_IOERR
39219   );
39220   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
39221     pPager->errCode = rc;
39222     pPager->eState = PAGER_ERROR;
39223   }
39224   return rc;
39225 }
39226
39227 static int pager_truncate(Pager *pPager, Pgno nPage);
39228
39229 /*
39230 ** This routine ends a transaction. A transaction is usually ended by 
39231 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
39232 ** after rollback of a hot-journal, or if an error occurs while opening
39233 ** the journal file or writing the very first journal-header of a
39234 ** database transaction.
39235 ** 
39236 ** This routine is never called in PAGER_ERROR state. If it is called
39237 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
39238 ** exclusive than a RESERVED lock, it is a no-op.
39239 **
39240 ** Otherwise, any active savepoints are released.
39241 **
39242 ** If the journal file is open, then it is "finalized". Once a journal 
39243 ** file has been finalized it is not possible to use it to roll back a 
39244 ** transaction. Nor will it be considered to be a hot-journal by this
39245 ** or any other database connection. Exactly how a journal is finalized
39246 ** depends on whether or not the pager is running in exclusive mode and
39247 ** the current journal-mode (Pager.journalMode value), as follows:
39248 **
39249 **   journalMode==MEMORY
39250 **     Journal file descriptor is simply closed. This destroys an 
39251 **     in-memory journal.
39252 **
39253 **   journalMode==TRUNCATE
39254 **     Journal file is truncated to zero bytes in size.
39255 **
39256 **   journalMode==PERSIST
39257 **     The first 28 bytes of the journal file are zeroed. This invalidates
39258 **     the first journal header in the file, and hence the entire journal
39259 **     file. An invalid journal file cannot be rolled back.
39260 **
39261 **   journalMode==DELETE
39262 **     The journal file is closed and deleted using sqlite3OsDelete().
39263 **
39264 **     If the pager is running in exclusive mode, this method of finalizing
39265 **     the journal file is never used. Instead, if the journalMode is
39266 **     DELETE and the pager is in exclusive mode, the method described under
39267 **     journalMode==PERSIST is used instead.
39268 **
39269 ** After the journal is finalized, the pager moves to PAGER_READER state.
39270 ** If running in non-exclusive rollback mode, the lock on the file is 
39271 ** downgraded to a SHARED_LOCK.
39272 **
39273 ** SQLITE_OK is returned if no error occurs. If an error occurs during
39274 ** any of the IO operations to finalize the journal file or unlock the
39275 ** database then the IO error code is returned to the user. If the 
39276 ** operation to finalize the journal file fails, then the code still
39277 ** tries to unlock the database file if not in exclusive mode. If the
39278 ** unlock operation fails as well, then the first error code related
39279 ** to the first error encountered (the journal finalization one) is
39280 ** returned.
39281 */
39282 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
39283   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
39284   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
39285
39286   /* Do nothing if the pager does not have an open write transaction
39287   ** or at least a RESERVED lock. This function may be called when there
39288   ** is no write-transaction active but a RESERVED or greater lock is
39289   ** held under two circumstances:
39290   **
39291   **   1. After a successful hot-journal rollback, it is called with
39292   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
39293   **
39294   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
39295   **      lock switches back to locking_mode=normal and then executes a
39296   **      read-transaction, this function is called with eState==PAGER_READER 
39297   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
39298   */
39299   assert( assert_pager_state(pPager) );
39300   assert( pPager->eState!=PAGER_ERROR );
39301   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
39302     return SQLITE_OK;
39303   }
39304
39305   releaseAllSavepoints(pPager);
39306   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
39307   if( isOpen(pPager->jfd) ){
39308     assert( !pagerUseWal(pPager) );
39309
39310     /* Finalize the journal file. */
39311     if( sqlite3IsMemJournal(pPager->jfd) ){
39312       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
39313       sqlite3OsClose(pPager->jfd);
39314     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
39315       if( pPager->journalOff==0 ){
39316         rc = SQLITE_OK;
39317       }else{
39318         rc = sqlite3OsTruncate(pPager->jfd, 0);
39319       }
39320       pPager->journalOff = 0;
39321     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
39322       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
39323     ){
39324       rc = zeroJournalHdr(pPager, hasMaster);
39325       pPager->journalOff = 0;
39326     }else{
39327       /* This branch may be executed with Pager.journalMode==MEMORY if
39328       ** a hot-journal was just rolled back. In this case the journal
39329       ** file should be closed and deleted. If this connection writes to
39330       ** the database file, it will do so using an in-memory journal. 
39331       */
39332       int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
39333       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
39334            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
39335            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
39336       );
39337       sqlite3OsClose(pPager->jfd);
39338       if( bDelete ){
39339         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
39340       }
39341     }
39342   }
39343
39344 #ifdef SQLITE_CHECK_PAGES
39345   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
39346   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
39347     PgHdr *p = pager_lookup(pPager, 1);
39348     if( p ){
39349       p->pageHash = 0;
39350       sqlite3PagerUnref(p);
39351     }
39352   }
39353 #endif
39354
39355   sqlite3BitvecDestroy(pPager->pInJournal);
39356   pPager->pInJournal = 0;
39357   pPager->nRec = 0;
39358   sqlite3PcacheCleanAll(pPager->pPCache);
39359   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
39360
39361   if( pagerUseWal(pPager) ){
39362     /* Drop the WAL write-lock, if any. Also, if the connection was in 
39363     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
39364     ** lock held on the database file.
39365     */
39366     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
39367     assert( rc2==SQLITE_OK );
39368   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
39369     /* This branch is taken when committing a transaction in rollback-journal
39370     ** mode if the database file on disk is larger than the database image.
39371     ** At this point the journal has been finalized and the transaction 
39372     ** successfully committed, but the EXCLUSIVE lock is still held on the
39373     ** file. So it is safe to truncate the database file to its minimum
39374     ** required size.  */
39375     assert( pPager->eLock==EXCLUSIVE_LOCK );
39376     rc = pager_truncate(pPager, pPager->dbSize);
39377   }
39378
39379   if( !pPager->exclusiveMode 
39380    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
39381   ){
39382     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
39383     pPager->changeCountDone = 0;
39384   }
39385   pPager->eState = PAGER_READER;
39386   pPager->setMaster = 0;
39387
39388   return (rc==SQLITE_OK?rc2:rc);
39389 }
39390
39391 /*
39392 ** Execute a rollback if a transaction is active and unlock the 
39393 ** database file. 
39394 **
39395 ** If the pager has already entered the ERROR state, do not attempt 
39396 ** the rollback at this time. Instead, pager_unlock() is called. The
39397 ** call to pager_unlock() will discard all in-memory pages, unlock
39398 ** the database file and move the pager back to OPEN state. If this 
39399 ** means that there is a hot-journal left in the file-system, the next 
39400 ** connection to obtain a shared lock on the pager (which may be this one) 
39401 ** will roll it back.
39402 **
39403 ** If the pager has not already entered the ERROR state, but an IO or
39404 ** malloc error occurs during a rollback, then this will itself cause 
39405 ** the pager to enter the ERROR state. Which will be cleared by the
39406 ** call to pager_unlock(), as described above.
39407 */
39408 static void pagerUnlockAndRollback(Pager *pPager){
39409   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
39410     assert( assert_pager_state(pPager) );
39411     if( pPager->eState>=PAGER_WRITER_LOCKED ){
39412       sqlite3BeginBenignMalloc();
39413       sqlite3PagerRollback(pPager);
39414       sqlite3EndBenignMalloc();
39415     }else if( !pPager->exclusiveMode ){
39416       assert( pPager->eState==PAGER_READER );
39417       pager_end_transaction(pPager, 0, 0);
39418     }
39419   }
39420   pager_unlock(pPager);
39421 }
39422
39423 /*
39424 ** Parameter aData must point to a buffer of pPager->pageSize bytes
39425 ** of data. Compute and return a checksum based ont the contents of the 
39426 ** page of data and the current value of pPager->cksumInit.
39427 **
39428 ** This is not a real checksum. It is really just the sum of the 
39429 ** random initial value (pPager->cksumInit) and every 200th byte
39430 ** of the page data, starting with byte offset (pPager->pageSize%200).
39431 ** Each byte is interpreted as an 8-bit unsigned integer.
39432 **
39433 ** Changing the formula used to compute this checksum results in an
39434 ** incompatible journal file format.
39435 **
39436 ** If journal corruption occurs due to a power failure, the most likely 
39437 ** scenario is that one end or the other of the record will be changed. 
39438 ** It is much less likely that the two ends of the journal record will be
39439 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
39440 ** though fast and simple, catches the mostly likely kind of corruption.
39441 */
39442 static u32 pager_cksum(Pager *pPager, const u8 *aData){
39443   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
39444   int i = pPager->pageSize-200;          /* Loop counter */
39445   while( i>0 ){
39446     cksum += aData[i];
39447     i -= 200;
39448   }
39449   return cksum;
39450 }
39451
39452 /*
39453 ** Report the current page size and number of reserved bytes back
39454 ** to the codec.
39455 */
39456 #ifdef SQLITE_HAS_CODEC
39457 static void pagerReportSize(Pager *pPager){
39458   if( pPager->xCodecSizeChng ){
39459     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
39460                            (int)pPager->nReserve);
39461   }
39462 }
39463 #else
39464 # define pagerReportSize(X)     /* No-op if we do not support a codec */
39465 #endif
39466
39467 /*
39468 ** Read a single page from either the journal file (if isMainJrnl==1) or
39469 ** from the sub-journal (if isMainJrnl==0) and playback that page.
39470 ** The page begins at offset *pOffset into the file. The *pOffset
39471 ** value is increased to the start of the next page in the journal.
39472 **
39473 ** The main rollback journal uses checksums - the statement journal does 
39474 ** not.
39475 **
39476 ** If the page number of the page record read from the (sub-)journal file
39477 ** is greater than the current value of Pager.dbSize, then playback is
39478 ** skipped and SQLITE_OK is returned.
39479 **
39480 ** If pDone is not NULL, then it is a record of pages that have already
39481 ** been played back.  If the page at *pOffset has already been played back
39482 ** (if the corresponding pDone bit is set) then skip the playback.
39483 ** Make sure the pDone bit corresponding to the *pOffset page is set
39484 ** prior to returning.
39485 **
39486 ** If the page record is successfully read from the (sub-)journal file
39487 ** and played back, then SQLITE_OK is returned. If an IO error occurs
39488 ** while reading the record from the (sub-)journal file or while writing
39489 ** to the database file, then the IO error code is returned. If data
39490 ** is successfully read from the (sub-)journal file but appears to be
39491 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
39492 ** two circumstances:
39493 ** 
39494 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
39495 **   * If the record is being rolled back from the main journal file
39496 **     and the checksum field does not match the record content.
39497 **
39498 ** Neither of these two scenarios are possible during a savepoint rollback.
39499 **
39500 ** If this is a savepoint rollback, then memory may have to be dynamically
39501 ** allocated by this function. If this is the case and an allocation fails,
39502 ** SQLITE_NOMEM is returned.
39503 */
39504 static int pager_playback_one_page(
39505   Pager *pPager,                /* The pager being played back */
39506   i64 *pOffset,                 /* Offset of record to playback */
39507   Bitvec *pDone,                /* Bitvec of pages already played back */
39508   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
39509   int isSavepnt                 /* True for a savepoint rollback */
39510 ){
39511   int rc;
39512   PgHdr *pPg;                   /* An existing page in the cache */
39513   Pgno pgno;                    /* The page number of a page in journal */
39514   u32 cksum;                    /* Checksum used for sanity checking */
39515   char *aData;                  /* Temporary storage for the page */
39516   sqlite3_file *jfd;            /* The file descriptor for the journal file */
39517   int isSynced;                 /* True if journal page is synced */
39518
39519   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
39520   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
39521   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
39522   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
39523
39524   aData = pPager->pTmpSpace;
39525   assert( aData );         /* Temp storage must have already been allocated */
39526   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
39527
39528   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
39529   ** or savepoint rollback done at the request of the caller) or this is
39530   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
39531   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
39532   ** only reads from the main journal, not the sub-journal.
39533   */
39534   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
39535        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
39536   );
39537   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
39538
39539   /* Read the page number and page data from the journal or sub-journal
39540   ** file. Return an error code to the caller if an IO error occurs.
39541   */
39542   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
39543   rc = read32bits(jfd, *pOffset, &pgno);
39544   if( rc!=SQLITE_OK ) return rc;
39545   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
39546   if( rc!=SQLITE_OK ) return rc;
39547   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
39548
39549   /* Sanity checking on the page.  This is more important that I originally
39550   ** thought.  If a power failure occurs while the journal is being written,
39551   ** it could cause invalid data to be written into the journal.  We need to
39552   ** detect this invalid data (with high probability) and ignore it.
39553   */
39554   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
39555     assert( !isSavepnt );
39556     return SQLITE_DONE;
39557   }
39558   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
39559     return SQLITE_OK;
39560   }
39561   if( isMainJrnl ){
39562     rc = read32bits(jfd, (*pOffset)-4, &cksum);
39563     if( rc ) return rc;
39564     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
39565       return SQLITE_DONE;
39566     }
39567   }
39568
39569   /* If this page has already been played by before during the current
39570   ** rollback, then don't bother to play it back again.
39571   */
39572   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
39573     return rc;
39574   }
39575
39576   /* When playing back page 1, restore the nReserve setting
39577   */
39578   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
39579     pPager->nReserve = ((u8*)aData)[20];
39580     pagerReportSize(pPager);
39581   }
39582
39583   /* If the pager is in CACHEMOD state, then there must be a copy of this
39584   ** page in the pager cache. In this case just update the pager cache,
39585   ** not the database file. The page is left marked dirty in this case.
39586   **
39587   ** An exception to the above rule: If the database is in no-sync mode
39588   ** and a page is moved during an incremental vacuum then the page may
39589   ** not be in the pager cache. Later: if a malloc() or IO error occurs
39590   ** during a Movepage() call, then the page may not be in the cache
39591   ** either. So the condition described in the above paragraph is not
39592   ** assert()able.
39593   **
39594   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
39595   ** pager cache if it exists and the main file. The page is then marked 
39596   ** not dirty. Since this code is only executed in PAGER_OPEN state for
39597   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
39598   ** if the pager is in OPEN state.
39599   **
39600   ** Ticket #1171:  The statement journal might contain page content that is
39601   ** different from the page content at the start of the transaction.
39602   ** This occurs when a page is changed prior to the start of a statement
39603   ** then changed again within the statement.  When rolling back such a
39604   ** statement we must not write to the original database unless we know
39605   ** for certain that original page contents are synced into the main rollback
39606   ** journal.  Otherwise, a power loss might leave modified data in the
39607   ** database file without an entry in the rollback journal that can
39608   ** restore the database to its original form.  Two conditions must be
39609   ** met before writing to the database files. (1) the database must be
39610   ** locked.  (2) we know that the original page content is fully synced
39611   ** in the main journal either because the page is not in cache or else
39612   ** the page is marked as needSync==0.
39613   **
39614   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
39615   ** is possible to fail a statement on a database that does not yet exist.
39616   ** Do not attempt to write if database file has never been opened.
39617   */
39618   if( pagerUseWal(pPager) ){
39619     pPg = 0;
39620   }else{
39621     pPg = pager_lookup(pPager, pgno);
39622   }
39623   assert( pPg || !MEMDB );
39624   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
39625   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
39626            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
39627            (isMainJrnl?"main-journal":"sub-journal")
39628   ));
39629   if( isMainJrnl ){
39630     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
39631   }else{
39632     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
39633   }
39634   if( isOpen(pPager->fd)
39635    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39636    && isSynced
39637   ){
39638     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
39639     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
39640     assert( !pagerUseWal(pPager) );
39641     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
39642     if( pgno>pPager->dbFileSize ){
39643       pPager->dbFileSize = pgno;
39644     }
39645     if( pPager->pBackup ){
39646       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
39647       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
39648       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
39649     }
39650   }else if( !isMainJrnl && pPg==0 ){
39651     /* If this is a rollback of a savepoint and data was not written to
39652     ** the database and the page is not in-memory, there is a potential
39653     ** problem. When the page is next fetched by the b-tree layer, it 
39654     ** will be read from the database file, which may or may not be 
39655     ** current. 
39656     **
39657     ** There are a couple of different ways this can happen. All are quite
39658     ** obscure. When running in synchronous mode, this can only happen 
39659     ** if the page is on the free-list at the start of the transaction, then
39660     ** populated, then moved using sqlite3PagerMovepage().
39661     **
39662     ** The solution is to add an in-memory page to the cache containing
39663     ** the data just read from the sub-journal. Mark the page as dirty 
39664     ** and if the pager requires a journal-sync, then mark the page as 
39665     ** requiring a journal-sync before it is written.
39666     */
39667     assert( isSavepnt );
39668     assert( pPager->doNotSpill==0 );
39669     pPager->doNotSpill++;
39670     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
39671     assert( pPager->doNotSpill==1 );
39672     pPager->doNotSpill--;
39673     if( rc!=SQLITE_OK ) return rc;
39674     pPg->flags &= ~PGHDR_NEED_READ;
39675     sqlite3PcacheMakeDirty(pPg);
39676   }
39677   if( pPg ){
39678     /* No page should ever be explicitly rolled back that is in use, except
39679     ** for page 1 which is held in use in order to keep the lock on the
39680     ** database active. However such a page may be rolled back as a result
39681     ** of an internal error resulting in an automatic call to
39682     ** sqlite3PagerRollback().
39683     */
39684     void *pData;
39685     pData = pPg->pData;
39686     memcpy(pData, (u8*)aData, pPager->pageSize);
39687     pPager->xReiniter(pPg);
39688     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
39689       /* If the contents of this page were just restored from the main 
39690       ** journal file, then its content must be as they were when the 
39691       ** transaction was first opened. In this case we can mark the page
39692       ** as clean, since there will be no need to write it out to the
39693       ** database.
39694       **
39695       ** There is one exception to this rule. If the page is being rolled
39696       ** back as part of a savepoint (or statement) rollback from an 
39697       ** unsynced portion of the main journal file, then it is not safe
39698       ** to mark the page as clean. This is because marking the page as
39699       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
39700       ** already in the journal file (recorded in Pager.pInJournal) and
39701       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
39702       ** again within this transaction, it will be marked as dirty but
39703       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
39704       ** be written out into the database file before its journal file
39705       ** segment is synced. If a crash occurs during or following this,
39706       ** database corruption may ensue.
39707       */
39708       assert( !pagerUseWal(pPager) );
39709       sqlite3PcacheMakeClean(pPg);
39710     }
39711     pager_set_pagehash(pPg);
39712
39713     /* If this was page 1, then restore the value of Pager.dbFileVers.
39714     ** Do this before any decoding. */
39715     if( pgno==1 ){
39716       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
39717     }
39718
39719     /* Decode the page just read from disk */
39720     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
39721     sqlite3PcacheRelease(pPg);
39722   }
39723   return rc;
39724 }
39725
39726 /*
39727 ** Parameter zMaster is the name of a master journal file. A single journal
39728 ** file that referred to the master journal file has just been rolled back.
39729 ** This routine checks if it is possible to delete the master journal file,
39730 ** and does so if it is.
39731 **
39732 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
39733 ** available for use within this function.
39734 **
39735 ** When a master journal file is created, it is populated with the names 
39736 ** of all of its child journals, one after another, formatted as utf-8 
39737 ** encoded text. The end of each child journal file is marked with a 
39738 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
39739 ** file for a transaction involving two databases might be:
39740 **
39741 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
39742 **
39743 ** A master journal file may only be deleted once all of its child 
39744 ** journals have been rolled back.
39745 **
39746 ** This function reads the contents of the master-journal file into 
39747 ** memory and loops through each of the child journal names. For
39748 ** each child journal, it checks if:
39749 **
39750 **   * if the child journal exists, and if so
39751 **   * if the child journal contains a reference to master journal 
39752 **     file zMaster
39753 **
39754 ** If a child journal can be found that matches both of the criteria
39755 ** above, this function returns without doing anything. Otherwise, if
39756 ** no such child journal can be found, file zMaster is deleted from
39757 ** the file-system using sqlite3OsDelete().
39758 **
39759 ** If an IO error within this function, an error code is returned. This
39760 ** function allocates memory by calling sqlite3Malloc(). If an allocation
39761 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
39762 ** occur, SQLITE_OK is returned.
39763 **
39764 ** TODO: This function allocates a single block of memory to load
39765 ** the entire contents of the master journal file. This could be
39766 ** a couple of kilobytes or so - potentially larger than the page 
39767 ** size.
39768 */
39769 static int pager_delmaster(Pager *pPager, const char *zMaster){
39770   sqlite3_vfs *pVfs = pPager->pVfs;
39771   int rc;                   /* Return code */
39772   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
39773   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
39774   char *zMasterJournal = 0; /* Contents of master journal file */
39775   i64 nMasterJournal;       /* Size of master journal file */
39776   char *zJournal;           /* Pointer to one journal within MJ file */
39777   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
39778   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
39779
39780   /* Allocate space for both the pJournal and pMaster file descriptors.
39781   ** If successful, open the master journal file for reading.
39782   */
39783   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
39784   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
39785   if( !pMaster ){
39786     rc = SQLITE_NOMEM;
39787   }else{
39788     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
39789     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
39790   }
39791   if( rc!=SQLITE_OK ) goto delmaster_out;
39792
39793   /* Load the entire master journal file into space obtained from
39794   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
39795   ** sufficient space (in zMasterPtr) to hold the names of master
39796   ** journal files extracted from regular rollback-journals.
39797   */
39798   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
39799   if( rc!=SQLITE_OK ) goto delmaster_out;
39800   nMasterPtr = pVfs->mxPathname+1;
39801   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
39802   if( !zMasterJournal ){
39803     rc = SQLITE_NOMEM;
39804     goto delmaster_out;
39805   }
39806   zMasterPtr = &zMasterJournal[nMasterJournal+1];
39807   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
39808   if( rc!=SQLITE_OK ) goto delmaster_out;
39809   zMasterJournal[nMasterJournal] = 0;
39810
39811   zJournal = zMasterJournal;
39812   while( (zJournal-zMasterJournal)<nMasterJournal ){
39813     int exists;
39814     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
39815     if( rc!=SQLITE_OK ){
39816       goto delmaster_out;
39817     }
39818     if( exists ){
39819       /* One of the journals pointed to by the master journal exists.
39820       ** Open it and check if it points at the master journal. If
39821       ** so, return without deleting the master journal file.
39822       */
39823       int c;
39824       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
39825       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
39826       if( rc!=SQLITE_OK ){
39827         goto delmaster_out;
39828       }
39829
39830       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
39831       sqlite3OsClose(pJournal);
39832       if( rc!=SQLITE_OK ){
39833         goto delmaster_out;
39834       }
39835
39836       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
39837       if( c ){
39838         /* We have a match. Do not delete the master journal file. */
39839         goto delmaster_out;
39840       }
39841     }
39842     zJournal += (sqlite3Strlen30(zJournal)+1);
39843   }
39844  
39845   sqlite3OsClose(pMaster);
39846   rc = sqlite3OsDelete(pVfs, zMaster, 0);
39847
39848 delmaster_out:
39849   sqlite3_free(zMasterJournal);
39850   if( pMaster ){
39851     sqlite3OsClose(pMaster);
39852     assert( !isOpen(pJournal) );
39853     sqlite3_free(pMaster);
39854   }
39855   return rc;
39856 }
39857
39858
39859 /*
39860 ** This function is used to change the actual size of the database 
39861 ** file in the file-system. This only happens when committing a transaction,
39862 ** or rolling back a transaction (including rolling back a hot-journal).
39863 **
39864 ** If the main database file is not open, or the pager is not in either
39865 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
39866 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
39867 ** If the file on disk is currently larger than nPage pages, then use the VFS
39868 ** xTruncate() method to truncate it.
39869 **
39870 ** Or, it might might be the case that the file on disk is smaller than 
39871 ** nPage pages. Some operating system implementations can get confused if 
39872 ** you try to truncate a file to some size that is larger than it 
39873 ** currently is, so detect this case and write a single zero byte to 
39874 ** the end of the new file instead.
39875 **
39876 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
39877 ** the database file, return the error code to the caller.
39878 */
39879 static int pager_truncate(Pager *pPager, Pgno nPage){
39880   int rc = SQLITE_OK;
39881   assert( pPager->eState!=PAGER_ERROR );
39882   assert( pPager->eState!=PAGER_READER );
39883   
39884   if( isOpen(pPager->fd) 
39885    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
39886   ){
39887     i64 currentSize, newSize;
39888     int szPage = pPager->pageSize;
39889     assert( pPager->eLock==EXCLUSIVE_LOCK );
39890     /* TODO: Is it safe to use Pager.dbFileSize here? */
39891     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
39892     newSize = szPage*(i64)nPage;
39893     if( rc==SQLITE_OK && currentSize!=newSize ){
39894       if( currentSize>newSize ){
39895         rc = sqlite3OsTruncate(pPager->fd, newSize);
39896       }else if( (currentSize+szPage)<=newSize ){
39897         char *pTmp = pPager->pTmpSpace;
39898         memset(pTmp, 0, szPage);
39899         testcase( (newSize-szPage) == currentSize );
39900         testcase( (newSize-szPage) >  currentSize );
39901         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
39902       }
39903       if( rc==SQLITE_OK ){
39904         pPager->dbFileSize = nPage;
39905       }
39906     }
39907   }
39908   return rc;
39909 }
39910
39911 /*
39912 ** Return a sanitized version of the sector-size of OS file pFile. The
39913 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
39914 */
39915 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
39916   int iRet = sqlite3OsSectorSize(pFile);
39917   if( iRet<32 ){
39918     iRet = 512;
39919   }else if( iRet>MAX_SECTOR_SIZE ){
39920     assert( MAX_SECTOR_SIZE>=512 );
39921     iRet = MAX_SECTOR_SIZE;
39922   }
39923   return iRet;
39924 }
39925
39926 /*
39927 ** Set the value of the Pager.sectorSize variable for the given
39928 ** pager based on the value returned by the xSectorSize method
39929 ** of the open database file. The sector size will be used used 
39930 ** to determine the size and alignment of journal header and 
39931 ** master journal pointers within created journal files.
39932 **
39933 ** For temporary files the effective sector size is always 512 bytes.
39934 **
39935 ** Otherwise, for non-temporary files, the effective sector size is
39936 ** the value returned by the xSectorSize() method rounded up to 32 if
39937 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
39938 ** is greater than MAX_SECTOR_SIZE.
39939 **
39940 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
39941 ** the effective sector size to its minimum value (512).  The purpose of
39942 ** pPager->sectorSize is to define the "blast radius" of bytes that
39943 ** might change if a crash occurs while writing to a single byte in
39944 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
39945 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
39946 ** size.  For backwards compatibility of the rollback journal file format,
39947 ** we cannot reduce the effective sector size below 512.
39948 */
39949 static void setSectorSize(Pager *pPager){
39950   assert( isOpen(pPager->fd) || pPager->tempFile );
39951
39952   if( pPager->tempFile
39953    || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
39954               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
39955   ){
39956     /* Sector size doesn't matter for temporary files. Also, the file
39957     ** may not have been opened yet, in which case the OsSectorSize()
39958     ** call will segfault. */
39959     pPager->sectorSize = 512;
39960   }else{
39961     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
39962   }
39963 }
39964
39965 /*
39966 ** Playback the journal and thus restore the database file to
39967 ** the state it was in before we started making changes.  
39968 **
39969 ** The journal file format is as follows: 
39970 **
39971 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
39972 **  (2)  4 byte big-endian integer which is the number of valid page records
39973 **       in the journal.  If this value is 0xffffffff, then compute the
39974 **       number of page records from the journal size.
39975 **  (3)  4 byte big-endian integer which is the initial value for the 
39976 **       sanity checksum.
39977 **  (4)  4 byte integer which is the number of pages to truncate the
39978 **       database to during a rollback.
39979 **  (5)  4 byte big-endian integer which is the sector size.  The header
39980 **       is this many bytes in size.
39981 **  (6)  4 byte big-endian integer which is the page size.
39982 **  (7)  zero padding out to the next sector size.
39983 **  (8)  Zero or more pages instances, each as follows:
39984 **        +  4 byte page number.
39985 **        +  pPager->pageSize bytes of data.
39986 **        +  4 byte checksum
39987 **
39988 ** When we speak of the journal header, we mean the first 7 items above.
39989 ** Each entry in the journal is an instance of the 8th item.
39990 **
39991 ** Call the value from the second bullet "nRec".  nRec is the number of
39992 ** valid page entries in the journal.  In most cases, you can compute the
39993 ** value of nRec from the size of the journal file.  But if a power
39994 ** failure occurred while the journal was being written, it could be the
39995 ** case that the size of the journal file had already been increased but
39996 ** the extra entries had not yet made it safely to disk.  In such a case,
39997 ** the value of nRec computed from the file size would be too large.  For
39998 ** that reason, we always use the nRec value in the header.
39999 **
40000 ** If the nRec value is 0xffffffff it means that nRec should be computed
40001 ** from the file size.  This value is used when the user selects the
40002 ** no-sync option for the journal.  A power failure could lead to corruption
40003 ** in this case.  But for things like temporary table (which will be
40004 ** deleted when the power is restored) we don't care.  
40005 **
40006 ** If the file opened as the journal file is not a well-formed
40007 ** journal file then all pages up to the first corrupted page are rolled
40008 ** back (or no pages if the journal header is corrupted). The journal file
40009 ** is then deleted and SQLITE_OK returned, just as if no corruption had
40010 ** been encountered.
40011 **
40012 ** If an I/O or malloc() error occurs, the journal-file is not deleted
40013 ** and an error code is returned.
40014 **
40015 ** The isHot parameter indicates that we are trying to rollback a journal
40016 ** that might be a hot journal.  Or, it could be that the journal is 
40017 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
40018 ** If the journal really is hot, reset the pager cache prior rolling
40019 ** back any content.  If the journal is merely persistent, no reset is
40020 ** needed.
40021 */
40022 static int pager_playback(Pager *pPager, int isHot){
40023   sqlite3_vfs *pVfs = pPager->pVfs;
40024   i64 szJ;                 /* Size of the journal file in bytes */
40025   u32 nRec;                /* Number of Records in the journal */
40026   u32 u;                   /* Unsigned loop counter */
40027   Pgno mxPg = 0;           /* Size of the original file in pages */
40028   int rc;                  /* Result code of a subroutine */
40029   int res = 1;             /* Value returned by sqlite3OsAccess() */
40030   char *zMaster = 0;       /* Name of master journal file if any */
40031   int needPagerReset;      /* True to reset page prior to first page rollback */
40032
40033   /* Figure out how many records are in the journal.  Abort early if
40034   ** the journal is empty.
40035   */
40036   assert( isOpen(pPager->jfd) );
40037   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
40038   if( rc!=SQLITE_OK ){
40039     goto end_playback;
40040   }
40041
40042   /* Read the master journal name from the journal, if it is present.
40043   ** If a master journal file name is specified, but the file is not
40044   ** present on disk, then the journal is not hot and does not need to be
40045   ** played back.
40046   **
40047   ** TODO: Technically the following is an error because it assumes that
40048   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
40049   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
40050   **  mxPathname is 512, which is the same as the minimum allowable value
40051   ** for pageSize.
40052   */
40053   zMaster = pPager->pTmpSpace;
40054   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
40055   if( rc==SQLITE_OK && zMaster[0] ){
40056     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
40057   }
40058   zMaster = 0;
40059   if( rc!=SQLITE_OK || !res ){
40060     goto end_playback;
40061   }
40062   pPager->journalOff = 0;
40063   needPagerReset = isHot;
40064
40065   /* This loop terminates either when a readJournalHdr() or 
40066   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
40067   ** occurs. 
40068   */
40069   while( 1 ){
40070     /* Read the next journal header from the journal file.  If there are
40071     ** not enough bytes left in the journal file for a complete header, or
40072     ** it is corrupted, then a process must have failed while writing it.
40073     ** This indicates nothing more needs to be rolled back.
40074     */
40075     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
40076     if( rc!=SQLITE_OK ){ 
40077       if( rc==SQLITE_DONE ){
40078         rc = SQLITE_OK;
40079       }
40080       goto end_playback;
40081     }
40082
40083     /* If nRec is 0xffffffff, then this journal was created by a process
40084     ** working in no-sync mode. This means that the rest of the journal
40085     ** file consists of pages, there are no more journal headers. Compute
40086     ** the value of nRec based on this assumption.
40087     */
40088     if( nRec==0xffffffff ){
40089       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
40090       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
40091     }
40092
40093     /* If nRec is 0 and this rollback is of a transaction created by this
40094     ** process and if this is the final header in the journal, then it means
40095     ** that this part of the journal was being filled but has not yet been
40096     ** synced to disk.  Compute the number of pages based on the remaining
40097     ** size of the file.
40098     **
40099     ** The third term of the test was added to fix ticket #2565.
40100     ** When rolling back a hot journal, nRec==0 always means that the next
40101     ** chunk of the journal contains zero pages to be rolled back.  But
40102     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
40103     ** the journal, it means that the journal might contain additional
40104     ** pages that need to be rolled back and that the number of pages 
40105     ** should be computed based on the journal file size.
40106     */
40107     if( nRec==0 && !isHot &&
40108         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
40109       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
40110     }
40111
40112     /* If this is the first header read from the journal, truncate the
40113     ** database file back to its original size.
40114     */
40115     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
40116       rc = pager_truncate(pPager, mxPg);
40117       if( rc!=SQLITE_OK ){
40118         goto end_playback;
40119       }
40120       pPager->dbSize = mxPg;
40121     }
40122
40123     /* Copy original pages out of the journal and back into the 
40124     ** database file and/or page cache.
40125     */
40126     for(u=0; u<nRec; u++){
40127       if( needPagerReset ){
40128         pager_reset(pPager);
40129         needPagerReset = 0;
40130       }
40131       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
40132       if( rc!=SQLITE_OK ){
40133         if( rc==SQLITE_DONE ){
40134           pPager->journalOff = szJ;
40135           break;
40136         }else if( rc==SQLITE_IOERR_SHORT_READ ){
40137           /* If the journal has been truncated, simply stop reading and
40138           ** processing the journal. This might happen if the journal was
40139           ** not completely written and synced prior to a crash.  In that
40140           ** case, the database should have never been written in the
40141           ** first place so it is OK to simply abandon the rollback. */
40142           rc = SQLITE_OK;
40143           goto end_playback;
40144         }else{
40145           /* If we are unable to rollback, quit and return the error
40146           ** code.  This will cause the pager to enter the error state
40147           ** so that no further harm will be done.  Perhaps the next
40148           ** process to come along will be able to rollback the database.
40149           */
40150           goto end_playback;
40151         }
40152       }
40153     }
40154   }
40155   /*NOTREACHED*/
40156   assert( 0 );
40157
40158 end_playback:
40159   /* Following a rollback, the database file should be back in its original
40160   ** state prior to the start of the transaction, so invoke the
40161   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
40162   ** assertion that the transaction counter was modified.
40163   */
40164 #ifdef SQLITE_DEBUG
40165   if( pPager->fd->pMethods ){
40166     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
40167   }
40168 #endif
40169
40170   /* If this playback is happening automatically as a result of an IO or 
40171   ** malloc error that occurred after the change-counter was updated but 
40172   ** before the transaction was committed, then the change-counter 
40173   ** modification may just have been reverted. If this happens in exclusive 
40174   ** mode, then subsequent transactions performed by the connection will not
40175   ** update the change-counter at all. This may lead to cache inconsistency
40176   ** problems for other processes at some point in the future. So, just
40177   ** in case this has happened, clear the changeCountDone flag now.
40178   */
40179   pPager->changeCountDone = pPager->tempFile;
40180
40181   if( rc==SQLITE_OK ){
40182     zMaster = pPager->pTmpSpace;
40183     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
40184     testcase( rc!=SQLITE_OK );
40185   }
40186   if( rc==SQLITE_OK
40187    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40188   ){
40189     rc = sqlite3PagerSync(pPager);
40190   }
40191   if( rc==SQLITE_OK ){
40192     rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
40193     testcase( rc!=SQLITE_OK );
40194   }
40195   if( rc==SQLITE_OK && zMaster[0] && res ){
40196     /* If there was a master journal and this routine will return success,
40197     ** see if it is possible to delete the master journal.
40198     */
40199     rc = pager_delmaster(pPager, zMaster);
40200     testcase( rc!=SQLITE_OK );
40201   }
40202
40203   /* The Pager.sectorSize variable may have been updated while rolling
40204   ** back a journal created by a process with a different sector size
40205   ** value. Reset it to the correct value for this process.
40206   */
40207   setSectorSize(pPager);
40208   return rc;
40209 }
40210
40211
40212 /*
40213 ** Read the content for page pPg out of the database file and into 
40214 ** pPg->pData. A shared lock or greater must be held on the database
40215 ** file before this function is called.
40216 **
40217 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
40218 ** the value read from the database file.
40219 **
40220 ** If an IO error occurs, then the IO error is returned to the caller.
40221 ** Otherwise, SQLITE_OK is returned.
40222 */
40223 static int readDbPage(PgHdr *pPg){
40224   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
40225   Pgno pgno = pPg->pgno;       /* Page number to read */
40226   int rc = SQLITE_OK;          /* Return code */
40227   int isInWal = 0;             /* True if page is in log file */
40228   int pgsz = pPager->pageSize; /* Number of bytes to read */
40229
40230   assert( pPager->eState>=PAGER_READER && !MEMDB );
40231   assert( isOpen(pPager->fd) );
40232
40233   if( NEVER(!isOpen(pPager->fd)) ){
40234     assert( pPager->tempFile );
40235     memset(pPg->pData, 0, pPager->pageSize);
40236     return SQLITE_OK;
40237   }
40238
40239   if( pagerUseWal(pPager) ){
40240     /* Try to pull the page from the write-ahead log. */
40241     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
40242   }
40243   if( rc==SQLITE_OK && !isInWal ){
40244     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
40245     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
40246     if( rc==SQLITE_IOERR_SHORT_READ ){
40247       rc = SQLITE_OK;
40248     }
40249   }
40250
40251   if( pgno==1 ){
40252     if( rc ){
40253       /* If the read is unsuccessful, set the dbFileVers[] to something
40254       ** that will never be a valid file version.  dbFileVers[] is a copy
40255       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
40256       ** zero or the size of the database in page. Bytes 32..35 and 35..39
40257       ** should be page numbers which are never 0xffffffff.  So filling
40258       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
40259       **
40260       ** For an encrypted database, the situation is more complex:  bytes
40261       ** 24..39 of the database are white noise.  But the probability of
40262       ** white noising equaling 16 bytes of 0xff is vanishingly small so
40263       ** we should still be ok.
40264       */
40265       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
40266     }else{
40267       u8 *dbFileVers = &((u8*)pPg->pData)[24];
40268       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
40269     }
40270   }
40271   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
40272
40273   PAGER_INCR(sqlite3_pager_readdb_count);
40274   PAGER_INCR(pPager->nRead);
40275   IOTRACE(("PGIN %p %d\n", pPager, pgno));
40276   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
40277                PAGERID(pPager), pgno, pager_pagehash(pPg)));
40278
40279   return rc;
40280 }
40281
40282 /*
40283 ** Update the value of the change-counter at offsets 24 and 92 in
40284 ** the header and the sqlite version number at offset 96.
40285 **
40286 ** This is an unconditional update.  See also the pager_incr_changecounter()
40287 ** routine which only updates the change-counter if the update is actually
40288 ** needed, as determined by the pPager->changeCountDone state variable.
40289 */
40290 static void pager_write_changecounter(PgHdr *pPg){
40291   u32 change_counter;
40292
40293   /* Increment the value just read and write it back to byte 24. */
40294   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
40295   put32bits(((char*)pPg->pData)+24, change_counter);
40296
40297   /* Also store the SQLite version number in bytes 96..99 and in
40298   ** bytes 92..95 store the change counter for which the version number
40299   ** is valid. */
40300   put32bits(((char*)pPg->pData)+92, change_counter);
40301   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
40302 }
40303
40304 #ifndef SQLITE_OMIT_WAL
40305 /*
40306 ** This function is invoked once for each page that has already been 
40307 ** written into the log file when a WAL transaction is rolled back.
40308 ** Parameter iPg is the page number of said page. The pCtx argument 
40309 ** is actually a pointer to the Pager structure.
40310 **
40311 ** If page iPg is present in the cache, and has no outstanding references,
40312 ** it is discarded. Otherwise, if there are one or more outstanding
40313 ** references, the page content is reloaded from the database. If the
40314 ** attempt to reload content from the database is required and fails, 
40315 ** return an SQLite error code. Otherwise, SQLITE_OK.
40316 */
40317 static int pagerUndoCallback(void *pCtx, Pgno iPg){
40318   int rc = SQLITE_OK;
40319   Pager *pPager = (Pager *)pCtx;
40320   PgHdr *pPg;
40321
40322   pPg = sqlite3PagerLookup(pPager, iPg);
40323   if( pPg ){
40324     if( sqlite3PcachePageRefcount(pPg)==1 ){
40325       sqlite3PcacheDrop(pPg);
40326     }else{
40327       rc = readDbPage(pPg);
40328       if( rc==SQLITE_OK ){
40329         pPager->xReiniter(pPg);
40330       }
40331       sqlite3PagerUnref(pPg);
40332     }
40333   }
40334
40335   /* Normally, if a transaction is rolled back, any backup processes are
40336   ** updated as data is copied out of the rollback journal and into the
40337   ** database. This is not generally possible with a WAL database, as
40338   ** rollback involves simply truncating the log file. Therefore, if one
40339   ** or more frames have already been written to the log (and therefore 
40340   ** also copied into the backup databases) as part of this transaction,
40341   ** the backups must be restarted.
40342   */
40343   sqlite3BackupRestart(pPager->pBackup);
40344
40345   return rc;
40346 }
40347
40348 /*
40349 ** This function is called to rollback a transaction on a WAL database.
40350 */
40351 static int pagerRollbackWal(Pager *pPager){
40352   int rc;                         /* Return Code */
40353   PgHdr *pList;                   /* List of dirty pages to revert */
40354
40355   /* For all pages in the cache that are currently dirty or have already
40356   ** been written (but not committed) to the log file, do one of the 
40357   ** following:
40358   **
40359   **   + Discard the cached page (if refcount==0), or
40360   **   + Reload page content from the database (if refcount>0).
40361   */
40362   pPager->dbSize = pPager->dbOrigSize;
40363   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
40364   pList = sqlite3PcacheDirtyList(pPager->pPCache);
40365   while( pList && rc==SQLITE_OK ){
40366     PgHdr *pNext = pList->pDirty;
40367     rc = pagerUndoCallback((void *)pPager, pList->pgno);
40368     pList = pNext;
40369   }
40370
40371   return rc;
40372 }
40373
40374 /*
40375 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
40376 ** the contents of the list of pages headed by pList (connected by pDirty),
40377 ** this function notifies any active backup processes that the pages have
40378 ** changed. 
40379 **
40380 ** The list of pages passed into this routine is always sorted by page number.
40381 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
40382 */ 
40383 static int pagerWalFrames(
40384   Pager *pPager,                  /* Pager object */
40385   PgHdr *pList,                   /* List of frames to log */
40386   Pgno nTruncate,                 /* Database size after this commit */
40387   int isCommit                    /* True if this is a commit */
40388 ){
40389   int rc;                         /* Return code */
40390   int nList;                      /* Number of pages in pList */
40391 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
40392   PgHdr *p;                       /* For looping over pages */
40393 #endif
40394
40395   assert( pPager->pWal );
40396   assert( pList );
40397 #ifdef SQLITE_DEBUG
40398   /* Verify that the page list is in accending order */
40399   for(p=pList; p && p->pDirty; p=p->pDirty){
40400     assert( p->pgno < p->pDirty->pgno );
40401   }
40402 #endif
40403
40404   assert( pList->pDirty==0 || isCommit );
40405   if( isCommit ){
40406     /* If a WAL transaction is being committed, there is no point in writing
40407     ** any pages with page numbers greater than nTruncate into the WAL file.
40408     ** They will never be read by any client. So remove them from the pDirty
40409     ** list here. */
40410     PgHdr *p;
40411     PgHdr **ppNext = &pList;
40412     nList = 0;
40413     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
40414       if( p->pgno<=nTruncate ){
40415         ppNext = &p->pDirty;
40416         nList++;
40417       }
40418     }
40419     assert( pList );
40420   }else{
40421     nList = 1;
40422   }
40423   pPager->aStat[PAGER_STAT_WRITE] += nList;
40424
40425   if( pList->pgno==1 ) pager_write_changecounter(pList);
40426   rc = sqlite3WalFrames(pPager->pWal, 
40427       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
40428   );
40429   if( rc==SQLITE_OK && pPager->pBackup ){
40430     PgHdr *p;
40431     for(p=pList; p; p=p->pDirty){
40432       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
40433     }
40434   }
40435
40436 #ifdef SQLITE_CHECK_PAGES
40437   pList = sqlite3PcacheDirtyList(pPager->pPCache);
40438   for(p=pList; p; p=p->pDirty){
40439     pager_set_pagehash(p);
40440   }
40441 #endif
40442
40443   return rc;
40444 }
40445
40446 /*
40447 ** Begin a read transaction on the WAL.
40448 **
40449 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
40450 ** makes a snapshot of the database at the current point in time and preserves
40451 ** that snapshot for use by the reader in spite of concurrently changes by
40452 ** other writers or checkpointers.
40453 */
40454 static int pagerBeginReadTransaction(Pager *pPager){
40455   int rc;                         /* Return code */
40456   int changed = 0;                /* True if cache must be reset */
40457
40458   assert( pagerUseWal(pPager) );
40459   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
40460
40461   /* sqlite3WalEndReadTransaction() was not called for the previous
40462   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
40463   ** are in locking_mode=NORMAL and EndRead() was previously called,
40464   ** the duplicate call is harmless.
40465   */
40466   sqlite3WalEndReadTransaction(pPager->pWal);
40467
40468   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
40469   if( rc!=SQLITE_OK || changed ){
40470     pager_reset(pPager);
40471   }
40472
40473   return rc;
40474 }
40475 #endif
40476
40477 /*
40478 ** This function is called as part of the transition from PAGER_OPEN
40479 ** to PAGER_READER state to determine the size of the database file
40480 ** in pages (assuming the page size currently stored in Pager.pageSize).
40481 **
40482 ** If no error occurs, SQLITE_OK is returned and the size of the database
40483 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
40484 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
40485 */
40486 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
40487   Pgno nPage;                     /* Value to return via *pnPage */
40488
40489   /* Query the WAL sub-system for the database size. The WalDbsize()
40490   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
40491   ** if the database size is not available. The database size is not
40492   ** available from the WAL sub-system if the log file is empty or
40493   ** contains no valid committed transactions.
40494   */
40495   assert( pPager->eState==PAGER_OPEN );
40496   assert( pPager->eLock>=SHARED_LOCK );
40497   nPage = sqlite3WalDbsize(pPager->pWal);
40498
40499   /* If the database size was not available from the WAL sub-system,
40500   ** determine it based on the size of the database file. If the size
40501   ** of the database file is not an integer multiple of the page-size,
40502   ** round down to the nearest page. Except, any file larger than 0
40503   ** bytes in size is considered to contain at least one page.
40504   */
40505   if( nPage==0 ){
40506     i64 n = 0;                    /* Size of db file in bytes */
40507     assert( isOpen(pPager->fd) || pPager->tempFile );
40508     if( isOpen(pPager->fd) ){
40509       int rc = sqlite3OsFileSize(pPager->fd, &n);
40510       if( rc!=SQLITE_OK ){
40511         return rc;
40512       }
40513     }
40514     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
40515   }
40516
40517   /* If the current number of pages in the file is greater than the
40518   ** configured maximum pager number, increase the allowed limit so
40519   ** that the file can be read.
40520   */
40521   if( nPage>pPager->mxPgno ){
40522     pPager->mxPgno = (Pgno)nPage;
40523   }
40524
40525   *pnPage = nPage;
40526   return SQLITE_OK;
40527 }
40528
40529 #ifndef SQLITE_OMIT_WAL
40530 /*
40531 ** Check if the *-wal file that corresponds to the database opened by pPager
40532 ** exists if the database is not empy, or verify that the *-wal file does
40533 ** not exist (by deleting it) if the database file is empty.
40534 **
40535 ** If the database is not empty and the *-wal file exists, open the pager
40536 ** in WAL mode.  If the database is empty or if no *-wal file exists and
40537 ** if no error occurs, make sure Pager.journalMode is not set to
40538 ** PAGER_JOURNALMODE_WAL.
40539 **
40540 ** Return SQLITE_OK or an error code.
40541 **
40542 ** The caller must hold a SHARED lock on the database file to call this
40543 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
40544 ** a WAL on a none-empty database, this ensures there is no race condition 
40545 ** between the xAccess() below and an xDelete() being executed by some 
40546 ** other connection.
40547 */
40548 static int pagerOpenWalIfPresent(Pager *pPager){
40549   int rc = SQLITE_OK;
40550   assert( pPager->eState==PAGER_OPEN );
40551   assert( pPager->eLock>=SHARED_LOCK );
40552
40553   if( !pPager->tempFile ){
40554     int isWal;                    /* True if WAL file exists */
40555     Pgno nPage;                   /* Size of the database file */
40556
40557     rc = pagerPagecount(pPager, &nPage);
40558     if( rc ) return rc;
40559     if( nPage==0 ){
40560       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
40561       if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
40562       isWal = 0;
40563     }else{
40564       rc = sqlite3OsAccess(
40565           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
40566       );
40567     }
40568     if( rc==SQLITE_OK ){
40569       if( isWal ){
40570         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
40571         rc = sqlite3PagerOpenWal(pPager, 0);
40572       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
40573         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
40574       }
40575     }
40576   }
40577   return rc;
40578 }
40579 #endif
40580
40581 /*
40582 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
40583 ** the entire master journal file. The case pSavepoint==NULL occurs when 
40584 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
40585 ** savepoint.
40586 **
40587 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
40588 ** being rolled back), then the rollback consists of up to three stages,
40589 ** performed in the order specified:
40590 **
40591 **   * Pages are played back from the main journal starting at byte
40592 **     offset PagerSavepoint.iOffset and continuing to 
40593 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
40594 **     file if PagerSavepoint.iHdrOffset is zero.
40595 **
40596 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
40597 **     back starting from the journal header immediately following 
40598 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
40599 **
40600 **   * Pages are then played back from the sub-journal file, starting
40601 **     with the PagerSavepoint.iSubRec and continuing to the end of
40602 **     the journal file.
40603 **
40604 ** Throughout the rollback process, each time a page is rolled back, the
40605 ** corresponding bit is set in a bitvec structure (variable pDone in the
40606 ** implementation below). This is used to ensure that a page is only
40607 ** rolled back the first time it is encountered in either journal.
40608 **
40609 ** If pSavepoint is NULL, then pages are only played back from the main
40610 ** journal file. There is no need for a bitvec in this case.
40611 **
40612 ** In either case, before playback commences the Pager.dbSize variable
40613 ** is reset to the value that it held at the start of the savepoint 
40614 ** (or transaction). No page with a page-number greater than this value
40615 ** is played back. If one is encountered it is simply skipped.
40616 */
40617 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
40618   i64 szJ;                 /* Effective size of the main journal */
40619   i64 iHdrOff;             /* End of first segment of main-journal records */
40620   int rc = SQLITE_OK;      /* Return code */
40621   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
40622
40623   assert( pPager->eState!=PAGER_ERROR );
40624   assert( pPager->eState>=PAGER_WRITER_LOCKED );
40625
40626   /* Allocate a bitvec to use to store the set of pages rolled back */
40627   if( pSavepoint ){
40628     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
40629     if( !pDone ){
40630       return SQLITE_NOMEM;
40631     }
40632   }
40633
40634   /* Set the database size back to the value it was before the savepoint 
40635   ** being reverted was opened.
40636   */
40637   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
40638   pPager->changeCountDone = pPager->tempFile;
40639
40640   if( !pSavepoint && pagerUseWal(pPager) ){
40641     return pagerRollbackWal(pPager);
40642   }
40643
40644   /* Use pPager->journalOff as the effective size of the main rollback
40645   ** journal.  The actual file might be larger than this in
40646   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
40647   ** past pPager->journalOff is off-limits to us.
40648   */
40649   szJ = pPager->journalOff;
40650   assert( pagerUseWal(pPager)==0 || szJ==0 );
40651
40652   /* Begin by rolling back records from the main journal starting at
40653   ** PagerSavepoint.iOffset and continuing to the next journal header.
40654   ** There might be records in the main journal that have a page number
40655   ** greater than the current database size (pPager->dbSize) but those
40656   ** will be skipped automatically.  Pages are added to pDone as they
40657   ** are played back.
40658   */
40659   if( pSavepoint && !pagerUseWal(pPager) ){
40660     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
40661     pPager->journalOff = pSavepoint->iOffset;
40662     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
40663       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40664     }
40665     assert( rc!=SQLITE_DONE );
40666   }else{
40667     pPager->journalOff = 0;
40668   }
40669
40670   /* Continue rolling back records out of the main journal starting at
40671   ** the first journal header seen and continuing until the effective end
40672   ** of the main journal file.  Continue to skip out-of-range pages and
40673   ** continue adding pages rolled back to pDone.
40674   */
40675   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
40676     u32 ii;            /* Loop counter */
40677     u32 nJRec = 0;     /* Number of Journal Records */
40678     u32 dummy;
40679     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
40680     assert( rc!=SQLITE_DONE );
40681
40682     /*
40683     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
40684     ** test is related to ticket #2565.  See the discussion in the
40685     ** pager_playback() function for additional information.
40686     */
40687     if( nJRec==0 
40688      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
40689     ){
40690       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
40691     }
40692     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
40693       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40694     }
40695     assert( rc!=SQLITE_DONE );
40696   }
40697   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
40698
40699   /* Finally,  rollback pages from the sub-journal.  Page that were
40700   ** previously rolled back out of the main journal (and are hence in pDone)
40701   ** will be skipped.  Out-of-range pages are also skipped.
40702   */
40703   if( pSavepoint ){
40704     u32 ii;            /* Loop counter */
40705     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
40706
40707     if( pagerUseWal(pPager) ){
40708       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
40709     }
40710     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
40711       assert( offset==(i64)ii*(4+pPager->pageSize) );
40712       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
40713     }
40714     assert( rc!=SQLITE_DONE );
40715   }
40716
40717   sqlite3BitvecDestroy(pDone);
40718   if( rc==SQLITE_OK ){
40719     pPager->journalOff = szJ;
40720   }
40721
40722   return rc;
40723 }
40724
40725 /*
40726 ** Change the maximum number of in-memory pages that are allowed.
40727 */
40728 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
40729   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
40730 }
40731
40732 /*
40733 ** Free as much memory as possible from the pager.
40734 */
40735 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
40736   sqlite3PcacheShrink(pPager->pPCache);
40737 }
40738
40739 /*
40740 ** Adjust the robustness of the database to damage due to OS crashes
40741 ** or power failures by changing the number of syncs()s when writing
40742 ** the rollback journal.  There are three levels:
40743 **
40744 **    OFF       sqlite3OsSync() is never called.  This is the default
40745 **              for temporary and transient files.
40746 **
40747 **    NORMAL    The journal is synced once before writes begin on the
40748 **              database.  This is normally adequate protection, but
40749 **              it is theoretically possible, though very unlikely,
40750 **              that an inopertune power failure could leave the journal
40751 **              in a state which would cause damage to the database
40752 **              when it is rolled back.
40753 **
40754 **    FULL      The journal is synced twice before writes begin on the
40755 **              database (with some additional information - the nRec field
40756 **              of the journal header - being written in between the two
40757 **              syncs).  If we assume that writing a
40758 **              single disk sector is atomic, then this mode provides
40759 **              assurance that the journal will not be corrupted to the
40760 **              point of causing damage to the database during rollback.
40761 **
40762 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
40763 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
40764 ** prior to the start of checkpoint and that the database file is synced
40765 ** at the conclusion of the checkpoint if the entire content of the WAL
40766 ** was written back into the database.  But no sync operations occur for
40767 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
40768 ** file is synced following each commit operation, in addition to the
40769 ** syncs associated with NORMAL.
40770 **
40771 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
40772 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
40773 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
40774 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
40775 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
40776 ** synchronous=FULL versus synchronous=NORMAL setting determines when
40777 ** the xSync primitive is called and is relevant to all platforms.
40778 **
40779 ** Numeric values associated with these states are OFF==1, NORMAL=2,
40780 ** and FULL=3.
40781 */
40782 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
40783 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
40784   Pager *pPager,        /* The pager to set safety level for */
40785   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  
40786   int bFullFsync,       /* PRAGMA fullfsync */
40787   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
40788 ){
40789   assert( level>=1 && level<=3 );
40790   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
40791   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
40792   if( pPager->noSync ){
40793     pPager->syncFlags = 0;
40794     pPager->ckptSyncFlags = 0;
40795   }else if( bFullFsync ){
40796     pPager->syncFlags = SQLITE_SYNC_FULL;
40797     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40798   }else if( bCkptFullFsync ){
40799     pPager->syncFlags = SQLITE_SYNC_NORMAL;
40800     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40801   }else{
40802     pPager->syncFlags = SQLITE_SYNC_NORMAL;
40803     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
40804   }
40805   pPager->walSyncFlags = pPager->syncFlags;
40806   if( pPager->fullSync ){
40807     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
40808   }
40809 }
40810 #endif
40811
40812 /*
40813 ** The following global variable is incremented whenever the library
40814 ** attempts to open a temporary file.  This information is used for
40815 ** testing and analysis only.  
40816 */
40817 #ifdef SQLITE_TEST
40818 SQLITE_API int sqlite3_opentemp_count = 0;
40819 #endif
40820
40821 /*
40822 ** Open a temporary file.
40823 **
40824 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
40825 ** or some other error code if we fail. The OS will automatically 
40826 ** delete the temporary file when it is closed.
40827 **
40828 ** The flags passed to the VFS layer xOpen() call are those specified
40829 ** by parameter vfsFlags ORed with the following:
40830 **
40831 **     SQLITE_OPEN_READWRITE
40832 **     SQLITE_OPEN_CREATE
40833 **     SQLITE_OPEN_EXCLUSIVE
40834 **     SQLITE_OPEN_DELETEONCLOSE
40835 */
40836 static int pagerOpentemp(
40837   Pager *pPager,        /* The pager object */
40838   sqlite3_file *pFile,  /* Write the file descriptor here */
40839   int vfsFlags          /* Flags passed through to the VFS */
40840 ){
40841   int rc;               /* Return code */
40842
40843 #ifdef SQLITE_TEST
40844   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
40845 #endif
40846
40847   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
40848             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
40849   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
40850   assert( rc!=SQLITE_OK || isOpen(pFile) );
40851   return rc;
40852 }
40853
40854 /*
40855 ** Set the busy handler function.
40856 **
40857 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
40858 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
40859 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
40860 ** lock. It does *not* invoke the busy handler when upgrading from
40861 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
40862 ** (which occurs during hot-journal rollback). Summary:
40863 **
40864 **   Transition                        | Invokes xBusyHandler
40865 **   --------------------------------------------------------
40866 **   NO_LOCK       -> SHARED_LOCK      | Yes
40867 **   SHARED_LOCK   -> RESERVED_LOCK    | No
40868 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
40869 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
40870 **
40871 ** If the busy-handler callback returns non-zero, the lock is 
40872 ** retried. If it returns zero, then the SQLITE_BUSY error is
40873 ** returned to the caller of the pager API function.
40874 */
40875 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
40876   Pager *pPager,                       /* Pager object */
40877   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
40878   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
40879 ){
40880   pPager->xBusyHandler = xBusyHandler;
40881   pPager->pBusyHandlerArg = pBusyHandlerArg;
40882
40883   if( isOpen(pPager->fd) ){
40884     void **ap = (void **)&pPager->xBusyHandler;
40885     assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
40886     assert( ap[1]==pBusyHandlerArg );
40887     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
40888   }
40889 }
40890
40891 /*
40892 ** Change the page size used by the Pager object. The new page size 
40893 ** is passed in *pPageSize.
40894 **
40895 ** If the pager is in the error state when this function is called, it
40896 ** is a no-op. The value returned is the error state error code (i.e. 
40897 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
40898 **
40899 ** Otherwise, if all of the following are true:
40900 **
40901 **   * the new page size (value of *pPageSize) is valid (a power 
40902 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
40903 **
40904 **   * there are no outstanding page references, and
40905 **
40906 **   * the database is either not an in-memory database or it is
40907 **     an in-memory database that currently consists of zero pages.
40908 **
40909 ** then the pager object page size is set to *pPageSize.
40910 **
40911 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
40912 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
40913 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
40914 ** In all other cases, SQLITE_OK is returned.
40915 **
40916 ** If the page size is not changed, either because one of the enumerated
40917 ** conditions above is not true, the pager was in error state when this
40918 ** function was called, or because the memory allocation attempt failed, 
40919 ** then *pPageSize is set to the old, retained page size before returning.
40920 */
40921 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
40922   int rc = SQLITE_OK;
40923
40924   /* It is not possible to do a full assert_pager_state() here, as this
40925   ** function may be called from within PagerOpen(), before the state
40926   ** of the Pager object is internally consistent.
40927   **
40928   ** At one point this function returned an error if the pager was in 
40929   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
40930   ** there is at least one outstanding page reference, this function
40931   ** is a no-op for that case anyhow.
40932   */
40933
40934   u32 pageSize = *pPageSize;
40935   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
40936   if( (pPager->memDb==0 || pPager->dbSize==0)
40937    && sqlite3PcacheRefCount(pPager->pPCache)==0 
40938    && pageSize && pageSize!=(u32)pPager->pageSize 
40939   ){
40940     char *pNew = NULL;             /* New temp space */
40941     i64 nByte = 0;
40942
40943     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
40944       rc = sqlite3OsFileSize(pPager->fd, &nByte);
40945     }
40946     if( rc==SQLITE_OK ){
40947       pNew = (char *)sqlite3PageMalloc(pageSize);
40948       if( !pNew ) rc = SQLITE_NOMEM;
40949     }
40950
40951     if( rc==SQLITE_OK ){
40952       pager_reset(pPager);
40953       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
40954       pPager->pageSize = pageSize;
40955       sqlite3PageFree(pPager->pTmpSpace);
40956       pPager->pTmpSpace = pNew;
40957       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
40958     }
40959   }
40960
40961   *pPageSize = pPager->pageSize;
40962   if( rc==SQLITE_OK ){
40963     if( nReserve<0 ) nReserve = pPager->nReserve;
40964     assert( nReserve>=0 && nReserve<1000 );
40965     pPager->nReserve = (i16)nReserve;
40966     pagerReportSize(pPager);
40967   }
40968   return rc;
40969 }
40970
40971 /*
40972 ** Return a pointer to the "temporary page" buffer held internally
40973 ** by the pager.  This is a buffer that is big enough to hold the
40974 ** entire content of a database page.  This buffer is used internally
40975 ** during rollback and will be overwritten whenever a rollback
40976 ** occurs.  But other modules are free to use it too, as long as
40977 ** no rollbacks are happening.
40978 */
40979 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
40980   return pPager->pTmpSpace;
40981 }
40982
40983 /*
40984 ** Attempt to set the maximum database page count if mxPage is positive. 
40985 ** Make no changes if mxPage is zero or negative.  And never reduce the
40986 ** maximum page count below the current size of the database.
40987 **
40988 ** Regardless of mxPage, return the current maximum page count.
40989 */
40990 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
40991   if( mxPage>0 ){
40992     pPager->mxPgno = mxPage;
40993   }
40994   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
40995   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
40996   return pPager->mxPgno;
40997 }
40998
40999 /*
41000 ** The following set of routines are used to disable the simulated
41001 ** I/O error mechanism.  These routines are used to avoid simulated
41002 ** errors in places where we do not care about errors.
41003 **
41004 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
41005 ** and generate no code.
41006 */
41007 #ifdef SQLITE_TEST
41008 SQLITE_API extern int sqlite3_io_error_pending;
41009 SQLITE_API extern int sqlite3_io_error_hit;
41010 static int saved_cnt;
41011 void disable_simulated_io_errors(void){
41012   saved_cnt = sqlite3_io_error_pending;
41013   sqlite3_io_error_pending = -1;
41014 }
41015 void enable_simulated_io_errors(void){
41016   sqlite3_io_error_pending = saved_cnt;
41017 }
41018 #else
41019 # define disable_simulated_io_errors()
41020 # define enable_simulated_io_errors()
41021 #endif
41022
41023 /*
41024 ** Read the first N bytes from the beginning of the file into memory
41025 ** that pDest points to. 
41026 **
41027 ** If the pager was opened on a transient file (zFilename==""), or
41028 ** opened on a file less than N bytes in size, the output buffer is
41029 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
41030 ** function is used to read database headers, and a new transient or
41031 ** zero sized database has a header than consists entirely of zeroes.
41032 **
41033 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
41034 ** the error code is returned to the caller and the contents of the
41035 ** output buffer undefined.
41036 */
41037 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
41038   int rc = SQLITE_OK;
41039   memset(pDest, 0, N);
41040   assert( isOpen(pPager->fd) || pPager->tempFile );
41041
41042   /* This routine is only called by btree immediately after creating
41043   ** the Pager object.  There has not been an opportunity to transition
41044   ** to WAL mode yet.
41045   */
41046   assert( !pagerUseWal(pPager) );
41047
41048   if( isOpen(pPager->fd) ){
41049     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
41050     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
41051     if( rc==SQLITE_IOERR_SHORT_READ ){
41052       rc = SQLITE_OK;
41053     }
41054   }
41055   return rc;
41056 }
41057
41058 /*
41059 ** This function may only be called when a read-transaction is open on
41060 ** the pager. It returns the total number of pages in the database.
41061 **
41062 ** However, if the file is between 1 and <page-size> bytes in size, then 
41063 ** this is considered a 1 page file.
41064 */
41065 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
41066   assert( pPager->eState>=PAGER_READER );
41067   assert( pPager->eState!=PAGER_WRITER_FINISHED );
41068   *pnPage = (int)pPager->dbSize;
41069 }
41070
41071
41072 /*
41073 ** Try to obtain a lock of type locktype on the database file. If
41074 ** a similar or greater lock is already held, this function is a no-op
41075 ** (returning SQLITE_OK immediately).
41076 **
41077 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
41078 ** the busy callback if the lock is currently not available. Repeat 
41079 ** until the busy callback returns false or until the attempt to 
41080 ** obtain the lock succeeds.
41081 **
41082 ** Return SQLITE_OK on success and an error code if we cannot obtain
41083 ** the lock. If the lock is obtained successfully, set the Pager.state 
41084 ** variable to locktype before returning.
41085 */
41086 static int pager_wait_on_lock(Pager *pPager, int locktype){
41087   int rc;                              /* Return code */
41088
41089   /* Check that this is either a no-op (because the requested lock is 
41090   ** already held, or one of the transistions that the busy-handler
41091   ** may be invoked during, according to the comment above
41092   ** sqlite3PagerSetBusyhandler().
41093   */
41094   assert( (pPager->eLock>=locktype)
41095        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
41096        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
41097   );
41098
41099   do {
41100     rc = pagerLockDb(pPager, locktype);
41101   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
41102   return rc;
41103 }
41104
41105 /*
41106 ** Function assertTruncateConstraint(pPager) checks that one of the 
41107 ** following is true for all dirty pages currently in the page-cache:
41108 **
41109 **   a) The page number is less than or equal to the size of the 
41110 **      current database image, in pages, OR
41111 **
41112 **   b) if the page content were written at this time, it would not
41113 **      be necessary to write the current content out to the sub-journal
41114 **      (as determined by function subjRequiresPage()).
41115 **
41116 ** If the condition asserted by this function were not true, and the
41117 ** dirty page were to be discarded from the cache via the pagerStress()
41118 ** routine, pagerStress() would not write the current page content to
41119 ** the database file. If a savepoint transaction were rolled back after
41120 ** this happened, the correct behavior would be to restore the current
41121 ** content of the page. However, since this content is not present in either
41122 ** the database file or the portion of the rollback journal and 
41123 ** sub-journal rolled back the content could not be restored and the
41124 ** database image would become corrupt. It is therefore fortunate that 
41125 ** this circumstance cannot arise.
41126 */
41127 #if defined(SQLITE_DEBUG)
41128 static void assertTruncateConstraintCb(PgHdr *pPg){
41129   assert( pPg->flags&PGHDR_DIRTY );
41130   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
41131 }
41132 static void assertTruncateConstraint(Pager *pPager){
41133   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
41134 }
41135 #else
41136 # define assertTruncateConstraint(pPager)
41137 #endif
41138
41139 /*
41140 ** Truncate the in-memory database file image to nPage pages. This 
41141 ** function does not actually modify the database file on disk. It 
41142 ** just sets the internal state of the pager object so that the 
41143 ** truncation will be done when the current transaction is committed.
41144 **
41145 ** This function is only called right before committing a transaction.
41146 ** Once this function has been called, the transaction must either be
41147 ** rolled back or committed. It is not safe to call this function and
41148 ** then continue writing to the database.
41149 */
41150 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
41151   assert( pPager->dbSize>=nPage );
41152   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
41153   pPager->dbSize = nPage;
41154
41155   /* At one point the code here called assertTruncateConstraint() to
41156   ** ensure that all pages being truncated away by this operation are,
41157   ** if one or more savepoints are open, present in the savepoint 
41158   ** journal so that they can be restored if the savepoint is rolled
41159   ** back. This is no longer necessary as this function is now only
41160   ** called right before committing a transaction. So although the 
41161   ** Pager object may still have open savepoints (Pager.nSavepoint!=0), 
41162   ** they cannot be rolled back. So the assertTruncateConstraint() call
41163   ** is no longer correct. */
41164 }
41165
41166
41167 /*
41168 ** This function is called before attempting a hot-journal rollback. It
41169 ** syncs the journal file to disk, then sets pPager->journalHdr to the
41170 ** size of the journal file so that the pager_playback() routine knows
41171 ** that the entire journal file has been synced.
41172 **
41173 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
41174 ** that if a power-failure occurs during the rollback, the process that
41175 ** attempts rollback following system recovery sees the same journal
41176 ** content as this process.
41177 **
41178 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
41179 ** an SQLite error code.
41180 */
41181 static int pagerSyncHotJournal(Pager *pPager){
41182   int rc = SQLITE_OK;
41183   if( !pPager->noSync ){
41184     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
41185   }
41186   if( rc==SQLITE_OK ){
41187     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
41188   }
41189   return rc;
41190 }
41191
41192 /*
41193 ** Shutdown the page cache.  Free all memory and close all files.
41194 **
41195 ** If a transaction was in progress when this routine is called, that
41196 ** transaction is rolled back.  All outstanding pages are invalidated
41197 ** and their memory is freed.  Any attempt to use a page associated
41198 ** with this page cache after this function returns will likely
41199 ** result in a coredump.
41200 **
41201 ** This function always succeeds. If a transaction is active an attempt
41202 ** is made to roll it back. If an error occurs during the rollback 
41203 ** a hot journal may be left in the filesystem but no error is returned
41204 ** to the caller.
41205 */
41206 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
41207   u8 *pTmp = (u8 *)pPager->pTmpSpace;
41208
41209   assert( assert_pager_state(pPager) );
41210   disable_simulated_io_errors();
41211   sqlite3BeginBenignMalloc();
41212   /* pPager->errCode = 0; */
41213   pPager->exclusiveMode = 0;
41214 #ifndef SQLITE_OMIT_WAL
41215   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
41216   pPager->pWal = 0;
41217 #endif
41218   pager_reset(pPager);
41219   if( MEMDB ){
41220     pager_unlock(pPager);
41221   }else{
41222     /* If it is open, sync the journal file before calling UnlockAndRollback.
41223     ** If this is not done, then an unsynced portion of the open journal 
41224     ** file may be played back into the database. If a power failure occurs 
41225     ** while this is happening, the database could become corrupt.
41226     **
41227     ** If an error occurs while trying to sync the journal, shift the pager
41228     ** into the ERROR state. This causes UnlockAndRollback to unlock the
41229     ** database and close the journal file without attempting to roll it
41230     ** back or finalize it. The next database user will have to do hot-journal
41231     ** rollback before accessing the database file.
41232     */
41233     if( isOpen(pPager->jfd) ){
41234       pager_error(pPager, pagerSyncHotJournal(pPager));
41235     }
41236     pagerUnlockAndRollback(pPager);
41237   }
41238   sqlite3EndBenignMalloc();
41239   enable_simulated_io_errors();
41240   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
41241   IOTRACE(("CLOSE %p\n", pPager))
41242   sqlite3OsClose(pPager->jfd);
41243   sqlite3OsClose(pPager->fd);
41244   sqlite3PageFree(pTmp);
41245   sqlite3PcacheClose(pPager->pPCache);
41246
41247 #ifdef SQLITE_HAS_CODEC
41248   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
41249 #endif
41250
41251   assert( !pPager->aSavepoint && !pPager->pInJournal );
41252   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
41253
41254   sqlite3_free(pPager);
41255   return SQLITE_OK;
41256 }
41257
41258 #if !defined(NDEBUG) || defined(SQLITE_TEST)
41259 /*
41260 ** Return the page number for page pPg.
41261 */
41262 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
41263   return pPg->pgno;
41264 }
41265 #endif
41266
41267 /*
41268 ** Increment the reference count for page pPg.
41269 */
41270 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
41271   sqlite3PcacheRef(pPg);
41272 }
41273
41274 /*
41275 ** Sync the journal. In other words, make sure all the pages that have
41276 ** been written to the journal have actually reached the surface of the
41277 ** disk and can be restored in the event of a hot-journal rollback.
41278 **
41279 ** If the Pager.noSync flag is set, then this function is a no-op.
41280 ** Otherwise, the actions required depend on the journal-mode and the 
41281 ** device characteristics of the file-system, as follows:
41282 **
41283 **   * If the journal file is an in-memory journal file, no action need
41284 **     be taken.
41285 **
41286 **   * Otherwise, if the device does not support the SAFE_APPEND property,
41287 **     then the nRec field of the most recently written journal header
41288 **     is updated to contain the number of journal records that have
41289 **     been written following it. If the pager is operating in full-sync
41290 **     mode, then the journal file is synced before this field is updated.
41291 **
41292 **   * If the device does not support the SEQUENTIAL property, then 
41293 **     journal file is synced.
41294 **
41295 ** Or, in pseudo-code:
41296 **
41297 **   if( NOT <in-memory journal> ){
41298 **     if( NOT SAFE_APPEND ){
41299 **       if( <full-sync mode> ) xSync(<journal file>);
41300 **       <update nRec field>
41301 **     } 
41302 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
41303 **   }
41304 **
41305 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
41306 ** page currently held in memory before returning SQLITE_OK. If an IO
41307 ** error is encountered, then the IO error code is returned to the caller.
41308 */
41309 static int syncJournal(Pager *pPager, int newHdr){
41310   int rc;                         /* Return code */
41311
41312   assert( pPager->eState==PAGER_WRITER_CACHEMOD
41313        || pPager->eState==PAGER_WRITER_DBMOD
41314   );
41315   assert( assert_pager_state(pPager) );
41316   assert( !pagerUseWal(pPager) );
41317
41318   rc = sqlite3PagerExclusiveLock(pPager);
41319   if( rc!=SQLITE_OK ) return rc;
41320
41321   if( !pPager->noSync ){
41322     assert( !pPager->tempFile );
41323     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
41324       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
41325       assert( isOpen(pPager->jfd) );
41326
41327       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
41328         /* This block deals with an obscure problem. If the last connection
41329         ** that wrote to this database was operating in persistent-journal
41330         ** mode, then the journal file may at this point actually be larger
41331         ** than Pager.journalOff bytes. If the next thing in the journal
41332         ** file happens to be a journal-header (written as part of the
41333         ** previous connection's transaction), and a crash or power-failure 
41334         ** occurs after nRec is updated but before this connection writes 
41335         ** anything else to the journal file (or commits/rolls back its 
41336         ** transaction), then SQLite may become confused when doing the 
41337         ** hot-journal rollback following recovery. It may roll back all
41338         ** of this connections data, then proceed to rolling back the old,
41339         ** out-of-date data that follows it. Database corruption.
41340         **
41341         ** To work around this, if the journal file does appear to contain
41342         ** a valid header following Pager.journalOff, then write a 0x00
41343         ** byte to the start of it to prevent it from being recognized.
41344         **
41345         ** Variable iNextHdrOffset is set to the offset at which this
41346         ** problematic header will occur, if it exists. aMagic is used 
41347         ** as a temporary buffer to inspect the first couple of bytes of
41348         ** the potential journal header.
41349         */
41350         i64 iNextHdrOffset;
41351         u8 aMagic[8];
41352         u8 zHeader[sizeof(aJournalMagic)+4];
41353
41354         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
41355         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
41356
41357         iNextHdrOffset = journalHdrOffset(pPager);
41358         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
41359         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
41360           static const u8 zerobyte = 0;
41361           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
41362         }
41363         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
41364           return rc;
41365         }
41366
41367         /* Write the nRec value into the journal file header. If in
41368         ** full-synchronous mode, sync the journal first. This ensures that
41369         ** all data has really hit the disk before nRec is updated to mark
41370         ** it as a candidate for rollback.
41371         **
41372         ** This is not required if the persistent media supports the
41373         ** SAFE_APPEND property. Because in this case it is not possible 
41374         ** for garbage data to be appended to the file, the nRec field
41375         ** is populated with 0xFFFFFFFF when the journal header is written
41376         ** and never needs to be updated.
41377         */
41378         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
41379           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
41380           IOTRACE(("JSYNC %p\n", pPager))
41381           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
41382           if( rc!=SQLITE_OK ) return rc;
41383         }
41384         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
41385         rc = sqlite3OsWrite(
41386             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
41387         );
41388         if( rc!=SQLITE_OK ) return rc;
41389       }
41390       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
41391         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
41392         IOTRACE(("JSYNC %p\n", pPager))
41393         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
41394           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
41395         );
41396         if( rc!=SQLITE_OK ) return rc;
41397       }
41398
41399       pPager->journalHdr = pPager->journalOff;
41400       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
41401         pPager->nRec = 0;
41402         rc = writeJournalHdr(pPager);
41403         if( rc!=SQLITE_OK ) return rc;
41404       }
41405     }else{
41406       pPager->journalHdr = pPager->journalOff;
41407     }
41408   }
41409
41410   /* Unless the pager is in noSync mode, the journal file was just 
41411   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
41412   ** all pages.
41413   */
41414   sqlite3PcacheClearSyncFlags(pPager->pPCache);
41415   pPager->eState = PAGER_WRITER_DBMOD;
41416   assert( assert_pager_state(pPager) );
41417   return SQLITE_OK;
41418 }
41419
41420 /*
41421 ** The argument is the first in a linked list of dirty pages connected
41422 ** by the PgHdr.pDirty pointer. This function writes each one of the
41423 ** in-memory pages in the list to the database file. The argument may
41424 ** be NULL, representing an empty list. In this case this function is
41425 ** a no-op.
41426 **
41427 ** The pager must hold at least a RESERVED lock when this function
41428 ** is called. Before writing anything to the database file, this lock
41429 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
41430 ** SQLITE_BUSY is returned and no data is written to the database file.
41431 ** 
41432 ** If the pager is a temp-file pager and the actual file-system file
41433 ** is not yet open, it is created and opened before any data is 
41434 ** written out.
41435 **
41436 ** Once the lock has been upgraded and, if necessary, the file opened,
41437 ** the pages are written out to the database file in list order. Writing
41438 ** a page is skipped if it meets either of the following criteria:
41439 **
41440 **   * The page number is greater than Pager.dbSize, or
41441 **   * The PGHDR_DONT_WRITE flag is set on the page.
41442 **
41443 ** If writing out a page causes the database file to grow, Pager.dbFileSize
41444 ** is updated accordingly. If page 1 is written out, then the value cached
41445 ** in Pager.dbFileVers[] is updated to match the new value stored in
41446 ** the database file.
41447 **
41448 ** If everything is successful, SQLITE_OK is returned. If an IO error 
41449 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
41450 ** be obtained, SQLITE_BUSY is returned.
41451 */
41452 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
41453   int rc = SQLITE_OK;                  /* Return code */
41454
41455   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
41456   assert( !pagerUseWal(pPager) );
41457   assert( pPager->eState==PAGER_WRITER_DBMOD );
41458   assert( pPager->eLock==EXCLUSIVE_LOCK );
41459
41460   /* If the file is a temp-file has not yet been opened, open it now. It
41461   ** is not possible for rc to be other than SQLITE_OK if this branch
41462   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
41463   */
41464   if( !isOpen(pPager->fd) ){
41465     assert( pPager->tempFile && rc==SQLITE_OK );
41466     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
41467   }
41468
41469   /* Before the first write, give the VFS a hint of what the final
41470   ** file size will be.
41471   */
41472   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
41473   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
41474     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
41475     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
41476     pPager->dbHintSize = pPager->dbSize;
41477   }
41478
41479   while( rc==SQLITE_OK && pList ){
41480     Pgno pgno = pList->pgno;
41481
41482     /* If there are dirty pages in the page cache with page numbers greater
41483     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
41484     ** make the file smaller (presumably by auto-vacuum code). Do not write
41485     ** any such pages to the file.
41486     **
41487     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
41488     ** set (set by sqlite3PagerDontWrite()).
41489     */
41490     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
41491       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
41492       char *pData;                                   /* Data to write */    
41493
41494       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
41495       if( pList->pgno==1 ) pager_write_changecounter(pList);
41496
41497       /* Encode the database */
41498       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
41499
41500       /* Write out the page data. */
41501       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
41502
41503       /* If page 1 was just written, update Pager.dbFileVers to match
41504       ** the value now stored in the database file. If writing this 
41505       ** page caused the database file to grow, update dbFileSize. 
41506       */
41507       if( pgno==1 ){
41508         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
41509       }
41510       if( pgno>pPager->dbFileSize ){
41511         pPager->dbFileSize = pgno;
41512       }
41513       pPager->aStat[PAGER_STAT_WRITE]++;
41514
41515       /* Update any backup objects copying the contents of this pager. */
41516       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
41517
41518       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
41519                    PAGERID(pPager), pgno, pager_pagehash(pList)));
41520       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
41521       PAGER_INCR(sqlite3_pager_writedb_count);
41522     }else{
41523       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
41524     }
41525     pager_set_pagehash(pList);
41526     pList = pList->pDirty;
41527   }
41528
41529   return rc;
41530 }
41531
41532 /*
41533 ** Ensure that the sub-journal file is open. If it is already open, this 
41534 ** function is a no-op.
41535 **
41536 ** SQLITE_OK is returned if everything goes according to plan. An 
41537 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
41538 ** fails.
41539 */
41540 static int openSubJournal(Pager *pPager){
41541   int rc = SQLITE_OK;
41542   if( !isOpen(pPager->sjfd) ){
41543     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
41544       sqlite3MemJournalOpen(pPager->sjfd);
41545     }else{
41546       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
41547     }
41548   }
41549   return rc;
41550 }
41551
41552 /*
41553 ** Append a record of the current state of page pPg to the sub-journal. 
41554 ** It is the callers responsibility to use subjRequiresPage() to check 
41555 ** that it is really required before calling this function.
41556 **
41557 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
41558 ** for all open savepoints before returning.
41559 **
41560 ** This function returns SQLITE_OK if everything is successful, an IO
41561 ** error code if the attempt to write to the sub-journal fails, or 
41562 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
41563 ** bitvec.
41564 */
41565 static int subjournalPage(PgHdr *pPg){
41566   int rc = SQLITE_OK;
41567   Pager *pPager = pPg->pPager;
41568   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
41569
41570     /* Open the sub-journal, if it has not already been opened */
41571     assert( pPager->useJournal );
41572     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
41573     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
41574     assert( pagerUseWal(pPager) 
41575          || pageInJournal(pPg) 
41576          || pPg->pgno>pPager->dbOrigSize 
41577     );
41578     rc = openSubJournal(pPager);
41579
41580     /* If the sub-journal was opened successfully (or was already open),
41581     ** write the journal record into the file.  */
41582     if( rc==SQLITE_OK ){
41583       void *pData = pPg->pData;
41584       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
41585       char *pData2;
41586   
41587       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
41588       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
41589       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
41590       if( rc==SQLITE_OK ){
41591         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
41592       }
41593     }
41594   }
41595   if( rc==SQLITE_OK ){
41596     pPager->nSubRec++;
41597     assert( pPager->nSavepoint>0 );
41598     rc = addToSavepointBitvecs(pPager, pPg->pgno);
41599   }
41600   return rc;
41601 }
41602
41603 /*
41604 ** This function is called by the pcache layer when it has reached some
41605 ** soft memory limit. The first argument is a pointer to a Pager object
41606 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
41607 ** database). The second argument is a reference to a page that is 
41608 ** currently dirty but has no outstanding references. The page
41609 ** is always associated with the Pager object passed as the first 
41610 ** argument.
41611 **
41612 ** The job of this function is to make pPg clean by writing its contents
41613 ** out to the database file, if possible. This may involve syncing the
41614 ** journal file. 
41615 **
41616 ** If successful, sqlite3PcacheMakeClean() is called on the page and
41617 ** SQLITE_OK returned. If an IO error occurs while trying to make the
41618 ** page clean, the IO error code is returned. If the page cannot be
41619 ** made clean for some other reason, but no error occurs, then SQLITE_OK
41620 ** is returned by sqlite3PcacheMakeClean() is not called.
41621 */
41622 static int pagerStress(void *p, PgHdr *pPg){
41623   Pager *pPager = (Pager *)p;
41624   int rc = SQLITE_OK;
41625
41626   assert( pPg->pPager==pPager );
41627   assert( pPg->flags&PGHDR_DIRTY );
41628
41629   /* The doNotSyncSpill flag is set during times when doing a sync of
41630   ** journal (and adding a new header) is not allowed.  This occurs
41631   ** during calls to sqlite3PagerWrite() while trying to journal multiple
41632   ** pages belonging to the same sector.
41633   **
41634   ** The doNotSpill flag inhibits all cache spilling regardless of whether
41635   ** or not a sync is required.  This is set during a rollback.
41636   **
41637   ** Spilling is also prohibited when in an error state since that could
41638   ** lead to database corruption.   In the current implementaton it 
41639   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
41640   ** while in the error state, hence it is impossible for this routine to
41641   ** be called in the error state.  Nevertheless, we include a NEVER()
41642   ** test for the error state as a safeguard against future changes.
41643   */
41644   if( NEVER(pPager->errCode) ) return SQLITE_OK;
41645   if( pPager->doNotSpill ) return SQLITE_OK;
41646   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
41647     return SQLITE_OK;
41648   }
41649
41650   pPg->pDirty = 0;
41651   if( pagerUseWal(pPager) ){
41652     /* Write a single frame for this page to the log. */
41653     if( subjRequiresPage(pPg) ){ 
41654       rc = subjournalPage(pPg); 
41655     }
41656     if( rc==SQLITE_OK ){
41657       rc = pagerWalFrames(pPager, pPg, 0, 0);
41658     }
41659   }else{
41660   
41661     /* Sync the journal file if required. */
41662     if( pPg->flags&PGHDR_NEED_SYNC 
41663      || pPager->eState==PAGER_WRITER_CACHEMOD
41664     ){
41665       rc = syncJournal(pPager, 1);
41666     }
41667   
41668     /* If the page number of this page is larger than the current size of
41669     ** the database image, it may need to be written to the sub-journal.
41670     ** This is because the call to pager_write_pagelist() below will not
41671     ** actually write data to the file in this case.
41672     **
41673     ** Consider the following sequence of events:
41674     **
41675     **   BEGIN;
41676     **     <journal page X>
41677     **     <modify page X>
41678     **     SAVEPOINT sp;
41679     **       <shrink database file to Y pages>
41680     **       pagerStress(page X)
41681     **     ROLLBACK TO sp;
41682     **
41683     ** If (X>Y), then when pagerStress is called page X will not be written
41684     ** out to the database file, but will be dropped from the cache. Then,
41685     ** following the "ROLLBACK TO sp" statement, reading page X will read
41686     ** data from the database file. This will be the copy of page X as it
41687     ** was when the transaction started, not as it was when "SAVEPOINT sp"
41688     ** was executed.
41689     **
41690     ** The solution is to write the current data for page X into the 
41691     ** sub-journal file now (if it is not already there), so that it will
41692     ** be restored to its current value when the "ROLLBACK TO sp" is 
41693     ** executed.
41694     */
41695     if( NEVER(
41696         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
41697     ) ){
41698       rc = subjournalPage(pPg);
41699     }
41700   
41701     /* Write the contents of the page out to the database file. */
41702     if( rc==SQLITE_OK ){
41703       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
41704       rc = pager_write_pagelist(pPager, pPg);
41705     }
41706   }
41707
41708   /* Mark the page as clean. */
41709   if( rc==SQLITE_OK ){
41710     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
41711     sqlite3PcacheMakeClean(pPg);
41712   }
41713
41714   return pager_error(pPager, rc); 
41715 }
41716
41717
41718 /*
41719 ** Allocate and initialize a new Pager object and put a pointer to it
41720 ** in *ppPager. The pager should eventually be freed by passing it
41721 ** to sqlite3PagerClose().
41722 **
41723 ** The zFilename argument is the path to the database file to open.
41724 ** If zFilename is NULL then a randomly-named temporary file is created
41725 ** and used as the file to be cached. Temporary files are be deleted
41726 ** automatically when they are closed. If zFilename is ":memory:" then 
41727 ** all information is held in cache. It is never written to disk. 
41728 ** This can be used to implement an in-memory database.
41729 **
41730 ** The nExtra parameter specifies the number of bytes of space allocated
41731 ** along with each page reference. This space is available to the user
41732 ** via the sqlite3PagerGetExtra() API.
41733 **
41734 ** The flags argument is used to specify properties that affect the
41735 ** operation of the pager. It should be passed some bitwise combination
41736 ** of the PAGER_* flags.
41737 **
41738 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
41739 ** of the xOpen() method of the supplied VFS when opening files. 
41740 **
41741 ** If the pager object is allocated and the specified file opened 
41742 ** successfully, SQLITE_OK is returned and *ppPager set to point to
41743 ** the new pager object. If an error occurs, *ppPager is set to NULL
41744 ** and error code returned. This function may return SQLITE_NOMEM
41745 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
41746 ** various SQLITE_IO_XXX errors.
41747 */
41748 SQLITE_PRIVATE int sqlite3PagerOpen(
41749   sqlite3_vfs *pVfs,       /* The virtual file system to use */
41750   Pager **ppPager,         /* OUT: Return the Pager structure here */
41751   const char *zFilename,   /* Name of the database file to open */
41752   int nExtra,              /* Extra bytes append to each in-memory page */
41753   int flags,               /* flags controlling this file */
41754   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
41755   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
41756 ){
41757   u8 *pPtr;
41758   Pager *pPager = 0;       /* Pager object to allocate and return */
41759   int rc = SQLITE_OK;      /* Return code */
41760   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
41761   int memDb = 0;           /* True if this is an in-memory file */
41762   int readOnly = 0;        /* True if this is a read-only file */
41763   int journalFileSize;     /* Bytes to allocate for each journal fd */
41764   char *zPathname = 0;     /* Full path to database file */
41765   int nPathname = 0;       /* Number of bytes in zPathname */
41766   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
41767   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
41768   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
41769   const char *zUri = 0;    /* URI args to copy */
41770   int nUri = 0;            /* Number of bytes of URI args at *zUri */
41771
41772   /* Figure out how much space is required for each journal file-handle
41773   ** (there are two of them, the main journal and the sub-journal). This
41774   ** is the maximum space required for an in-memory journal file handle 
41775   ** and a regular journal file-handle. Note that a "regular journal-handle"
41776   ** may be a wrapper capable of caching the first portion of the journal
41777   ** file in memory to implement the atomic-write optimization (see 
41778   ** source file journal.c).
41779   */
41780   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
41781     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
41782   }else{
41783     journalFileSize = ROUND8(sqlite3MemJournalSize());
41784   }
41785
41786   /* Set the output variable to NULL in case an error occurs. */
41787   *ppPager = 0;
41788
41789 #ifndef SQLITE_OMIT_MEMORYDB
41790   if( flags & PAGER_MEMORY ){
41791     memDb = 1;
41792     if( zFilename && zFilename[0] ){
41793       zPathname = sqlite3DbStrDup(0, zFilename);
41794       if( zPathname==0  ) return SQLITE_NOMEM;
41795       nPathname = sqlite3Strlen30(zPathname);
41796       zFilename = 0;
41797     }
41798   }
41799 #endif
41800
41801   /* Compute and store the full pathname in an allocated buffer pointed
41802   ** to by zPathname, length nPathname. Or, if this is a temporary file,
41803   ** leave both nPathname and zPathname set to 0.
41804   */
41805   if( zFilename && zFilename[0] ){
41806     const char *z;
41807     nPathname = pVfs->mxPathname+1;
41808     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
41809     if( zPathname==0 ){
41810       return SQLITE_NOMEM;
41811     }
41812     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
41813     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
41814     nPathname = sqlite3Strlen30(zPathname);
41815     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
41816     while( *z ){
41817       z += sqlite3Strlen30(z)+1;
41818       z += sqlite3Strlen30(z)+1;
41819     }
41820     nUri = (int)(&z[1] - zUri);
41821     assert( nUri>=0 );
41822     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
41823       /* This branch is taken when the journal path required by
41824       ** the database being opened will be more than pVfs->mxPathname
41825       ** bytes in length. This means the database cannot be opened,
41826       ** as it will not be possible to open the journal file or even
41827       ** check for a hot-journal before reading.
41828       */
41829       rc = SQLITE_CANTOPEN_BKPT;
41830     }
41831     if( rc!=SQLITE_OK ){
41832       sqlite3DbFree(0, zPathname);
41833       return rc;
41834     }
41835   }
41836
41837   /* Allocate memory for the Pager structure, PCache object, the
41838   ** three file descriptors, the database file name and the journal 
41839   ** file name. The layout in memory is as follows:
41840   **
41841   **     Pager object                    (sizeof(Pager) bytes)
41842   **     PCache object                   (sqlite3PcacheSize() bytes)
41843   **     Database file handle            (pVfs->szOsFile bytes)
41844   **     Sub-journal file handle         (journalFileSize bytes)
41845   **     Main journal file handle        (journalFileSize bytes)
41846   **     Database file name              (nPathname+1 bytes)
41847   **     Journal file name               (nPathname+8+1 bytes)
41848   */
41849   pPtr = (u8 *)sqlite3MallocZero(
41850     ROUND8(sizeof(*pPager)) +      /* Pager structure */
41851     ROUND8(pcacheSize) +           /* PCache object */
41852     ROUND8(pVfs->szOsFile) +       /* The main db file */
41853     journalFileSize * 2 +          /* The two journal files */ 
41854     nPathname + 1 + nUri +         /* zFilename */
41855     nPathname + 8 + 2              /* zJournal */
41856 #ifndef SQLITE_OMIT_WAL
41857     + nPathname + 4 + 2            /* zWal */
41858 #endif
41859   );
41860   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
41861   if( !pPtr ){
41862     sqlite3DbFree(0, zPathname);
41863     return SQLITE_NOMEM;
41864   }
41865   pPager =              (Pager*)(pPtr);
41866   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
41867   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
41868   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
41869   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
41870   pPager->zFilename =    (char*)(pPtr += journalFileSize);
41871   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
41872
41873   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
41874   if( zPathname ){
41875     assert( nPathname>0 );
41876     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
41877     memcpy(pPager->zFilename, zPathname, nPathname);
41878     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
41879     memcpy(pPager->zJournal, zPathname, nPathname);
41880     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
41881     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
41882 #ifndef SQLITE_OMIT_WAL
41883     pPager->zWal = &pPager->zJournal[nPathname+8+1];
41884     memcpy(pPager->zWal, zPathname, nPathname);
41885     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
41886     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
41887 #endif
41888     sqlite3DbFree(0, zPathname);
41889   }
41890   pPager->pVfs = pVfs;
41891   pPager->vfsFlags = vfsFlags;
41892
41893   /* Open the pager file.
41894   */
41895   if( zFilename && zFilename[0] ){
41896     int fout = 0;                    /* VFS flags returned by xOpen() */
41897     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
41898     assert( !memDb );
41899     readOnly = (fout&SQLITE_OPEN_READONLY);
41900
41901     /* If the file was successfully opened for read/write access,
41902     ** choose a default page size in case we have to create the
41903     ** database file. The default page size is the maximum of:
41904     **
41905     **    + SQLITE_DEFAULT_PAGE_SIZE,
41906     **    + The value returned by sqlite3OsSectorSize()
41907     **    + The largest page size that can be written atomically.
41908     */
41909     if( rc==SQLITE_OK && !readOnly ){
41910       setSectorSize(pPager);
41911       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
41912       if( szPageDflt<pPager->sectorSize ){
41913         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
41914           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
41915         }else{
41916           szPageDflt = (u32)pPager->sectorSize;
41917         }
41918       }
41919 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41920       {
41921         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
41922         int ii;
41923         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
41924         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
41925         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
41926         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
41927           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
41928             szPageDflt = ii;
41929           }
41930         }
41931       }
41932 #endif
41933     }
41934   }else{
41935     /* If a temporary file is requested, it is not opened immediately.
41936     ** In this case we accept the default page size and delay actually
41937     ** opening the file until the first call to OsWrite().
41938     **
41939     ** This branch is also run for an in-memory database. An in-memory
41940     ** database is the same as a temp-file that is never written out to
41941     ** disk and uses an in-memory rollback journal.
41942     */ 
41943     tempFile = 1;
41944     pPager->eState = PAGER_READER;
41945     pPager->eLock = EXCLUSIVE_LOCK;
41946     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
41947   }
41948
41949   /* The following call to PagerSetPagesize() serves to set the value of 
41950   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
41951   */
41952   if( rc==SQLITE_OK ){
41953     assert( pPager->memDb==0 );
41954     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
41955     testcase( rc!=SQLITE_OK );
41956   }
41957
41958   /* If an error occurred in either of the blocks above, free the 
41959   ** Pager structure and close the file.
41960   */
41961   if( rc!=SQLITE_OK ){
41962     assert( !pPager->pTmpSpace );
41963     sqlite3OsClose(pPager->fd);
41964     sqlite3_free(pPager);
41965     return rc;
41966   }
41967
41968   /* Initialize the PCache object. */
41969   assert( nExtra<1000 );
41970   nExtra = ROUND8(nExtra);
41971   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
41972                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
41973
41974   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
41975   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
41976
41977   pPager->useJournal = (u8)useJournal;
41978   /* pPager->stmtOpen = 0; */
41979   /* pPager->stmtInUse = 0; */
41980   /* pPager->nRef = 0; */
41981   /* pPager->stmtSize = 0; */
41982   /* pPager->stmtJSize = 0; */
41983   /* pPager->nPage = 0; */
41984   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
41985   /* pPager->state = PAGER_UNLOCK; */
41986 #if 0
41987   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
41988 #endif
41989   /* pPager->errMask = 0; */
41990   pPager->tempFile = (u8)tempFile;
41991   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
41992           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
41993   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
41994   pPager->exclusiveMode = (u8)tempFile; 
41995   pPager->changeCountDone = pPager->tempFile;
41996   pPager->memDb = (u8)memDb;
41997   pPager->readOnly = (u8)readOnly;
41998   assert( useJournal || pPager->tempFile );
41999   pPager->noSync = pPager->tempFile;
42000   if( pPager->noSync ){
42001     assert( pPager->fullSync==0 );
42002     assert( pPager->syncFlags==0 );
42003     assert( pPager->walSyncFlags==0 );
42004     assert( pPager->ckptSyncFlags==0 );
42005   }else{
42006     pPager->fullSync = 1;
42007     pPager->syncFlags = SQLITE_SYNC_NORMAL;
42008     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
42009     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
42010   }
42011   /* pPager->pFirst = 0; */
42012   /* pPager->pFirstSynced = 0; */
42013   /* pPager->pLast = 0; */
42014   pPager->nExtra = (u16)nExtra;
42015   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
42016   assert( isOpen(pPager->fd) || tempFile );
42017   setSectorSize(pPager);
42018   if( !useJournal ){
42019     pPager->journalMode = PAGER_JOURNALMODE_OFF;
42020   }else if( memDb ){
42021     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
42022   }
42023   /* pPager->xBusyHandler = 0; */
42024   /* pPager->pBusyHandlerArg = 0; */
42025   pPager->xReiniter = xReinit;
42026   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
42027
42028   *ppPager = pPager;
42029   return SQLITE_OK;
42030 }
42031
42032
42033
42034 /*
42035 ** This function is called after transitioning from PAGER_UNLOCK to
42036 ** PAGER_SHARED state. It tests if there is a hot journal present in
42037 ** the file-system for the given pager. A hot journal is one that 
42038 ** needs to be played back. According to this function, a hot-journal
42039 ** file exists if the following criteria are met:
42040 **
42041 **   * The journal file exists in the file system, and
42042 **   * No process holds a RESERVED or greater lock on the database file, and
42043 **   * The database file itself is greater than 0 bytes in size, and
42044 **   * The first byte of the journal file exists and is not 0x00.
42045 **
42046 ** If the current size of the database file is 0 but a journal file
42047 ** exists, that is probably an old journal left over from a prior
42048 ** database with the same name. In this case the journal file is
42049 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
42050 ** is returned.
42051 **
42052 ** This routine does not check if there is a master journal filename
42053 ** at the end of the file. If there is, and that master journal file
42054 ** does not exist, then the journal file is not really hot. In this
42055 ** case this routine will return a false-positive. The pager_playback()
42056 ** routine will discover that the journal file is not really hot and 
42057 ** will not roll it back. 
42058 **
42059 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
42060 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
42061 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
42062 ** to determine whether or not a hot-journal file exists, the IO error
42063 ** code is returned and the value of *pExists is undefined.
42064 */
42065 static int hasHotJournal(Pager *pPager, int *pExists){
42066   sqlite3_vfs * const pVfs = pPager->pVfs;
42067   int rc = SQLITE_OK;           /* Return code */
42068   int exists = 1;               /* True if a journal file is present */
42069   int jrnlOpen = !!isOpen(pPager->jfd);
42070
42071   assert( pPager->useJournal );
42072   assert( isOpen(pPager->fd) );
42073   assert( pPager->eState==PAGER_OPEN );
42074
42075   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
42076     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
42077   ));
42078
42079   *pExists = 0;
42080   if( !jrnlOpen ){
42081     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
42082   }
42083   if( rc==SQLITE_OK && exists ){
42084     int locked = 0;             /* True if some process holds a RESERVED lock */
42085
42086     /* Race condition here:  Another process might have been holding the
42087     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
42088     ** call above, but then delete the journal and drop the lock before
42089     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
42090     ** is the case, this routine might think there is a hot journal when
42091     ** in fact there is none.  This results in a false-positive which will
42092     ** be dealt with by the playback routine.  Ticket #3883.
42093     */
42094     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
42095     if( rc==SQLITE_OK && !locked ){
42096       Pgno nPage;                 /* Number of pages in database file */
42097
42098       /* Check the size of the database file. If it consists of 0 pages,
42099       ** then delete the journal file. See the header comment above for 
42100       ** the reasoning here.  Delete the obsolete journal file under
42101       ** a RESERVED lock to avoid race conditions and to avoid violating
42102       ** [H33020].
42103       */
42104       rc = pagerPagecount(pPager, &nPage);
42105       if( rc==SQLITE_OK ){
42106         if( nPage==0 ){
42107           sqlite3BeginBenignMalloc();
42108           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
42109             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
42110             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
42111           }
42112           sqlite3EndBenignMalloc();
42113         }else{
42114           /* The journal file exists and no other connection has a reserved
42115           ** or greater lock on the database file. Now check that there is
42116           ** at least one non-zero bytes at the start of the journal file.
42117           ** If there is, then we consider this journal to be hot. If not, 
42118           ** it can be ignored.
42119           */
42120           if( !jrnlOpen ){
42121             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
42122             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
42123           }
42124           if( rc==SQLITE_OK ){
42125             u8 first = 0;
42126             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
42127             if( rc==SQLITE_IOERR_SHORT_READ ){
42128               rc = SQLITE_OK;
42129             }
42130             if( !jrnlOpen ){
42131               sqlite3OsClose(pPager->jfd);
42132             }
42133             *pExists = (first!=0);
42134           }else if( rc==SQLITE_CANTOPEN ){
42135             /* If we cannot open the rollback journal file in order to see if
42136             ** its has a zero header, that might be due to an I/O error, or
42137             ** it might be due to the race condition described above and in
42138             ** ticket #3883.  Either way, assume that the journal is hot.
42139             ** This might be a false positive.  But if it is, then the
42140             ** automatic journal playback and recovery mechanism will deal
42141             ** with it under an EXCLUSIVE lock where we do not need to
42142             ** worry so much with race conditions.
42143             */
42144             *pExists = 1;
42145             rc = SQLITE_OK;
42146           }
42147         }
42148       }
42149     }
42150   }
42151
42152   return rc;
42153 }
42154
42155 /*
42156 ** This function is called to obtain a shared lock on the database file.
42157 ** It is illegal to call sqlite3PagerAcquire() until after this function
42158 ** has been successfully called. If a shared-lock is already held when
42159 ** this function is called, it is a no-op.
42160 **
42161 ** The following operations are also performed by this function.
42162 **
42163 **   1) If the pager is currently in PAGER_OPEN state (no lock held
42164 **      on the database file), then an attempt is made to obtain a
42165 **      SHARED lock on the database file. Immediately after obtaining
42166 **      the SHARED lock, the file-system is checked for a hot-journal,
42167 **      which is played back if present. Following any hot-journal 
42168 **      rollback, the contents of the cache are validated by checking
42169 **      the 'change-counter' field of the database file header and
42170 **      discarded if they are found to be invalid.
42171 **
42172 **   2) If the pager is running in exclusive-mode, and there are currently
42173 **      no outstanding references to any pages, and is in the error state,
42174 **      then an attempt is made to clear the error state by discarding
42175 **      the contents of the page cache and rolling back any open journal
42176 **      file.
42177 **
42178 ** If everything is successful, SQLITE_OK is returned. If an IO error 
42179 ** occurs while locking the database, checking for a hot-journal file or 
42180 ** rolling back a journal file, the IO error code is returned.
42181 */
42182 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
42183   int rc = SQLITE_OK;                /* Return code */
42184
42185   /* This routine is only called from b-tree and only when there are no
42186   ** outstanding pages. This implies that the pager state should either
42187   ** be OPEN or READER. READER is only possible if the pager is or was in 
42188   ** exclusive access mode.
42189   */
42190   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
42191   assert( assert_pager_state(pPager) );
42192   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
42193   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
42194
42195   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
42196     int bHotJournal = 1;          /* True if there exists a hot journal-file */
42197
42198     assert( !MEMDB );
42199
42200     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
42201     if( rc!=SQLITE_OK ){
42202       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
42203       goto failed;
42204     }
42205
42206     /* If a journal file exists, and there is no RESERVED lock on the
42207     ** database file, then it either needs to be played back or deleted.
42208     */
42209     if( pPager->eLock<=SHARED_LOCK ){
42210       rc = hasHotJournal(pPager, &bHotJournal);
42211     }
42212     if( rc!=SQLITE_OK ){
42213       goto failed;
42214     }
42215     if( bHotJournal ){
42216       if( pPager->readOnly ){
42217         rc = SQLITE_READONLY_ROLLBACK;
42218         goto failed;
42219       }
42220
42221       /* Get an EXCLUSIVE lock on the database file. At this point it is
42222       ** important that a RESERVED lock is not obtained on the way to the
42223       ** EXCLUSIVE lock. If it were, another process might open the
42224       ** database file, detect the RESERVED lock, and conclude that the
42225       ** database is safe to read while this process is still rolling the 
42226       ** hot-journal back.
42227       ** 
42228       ** Because the intermediate RESERVED lock is not requested, any
42229       ** other process attempting to access the database file will get to 
42230       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
42231       ** on the database file.
42232       **
42233       ** Unless the pager is in locking_mode=exclusive mode, the lock is
42234       ** downgraded to SHARED_LOCK before this function returns.
42235       */
42236       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42237       if( rc!=SQLITE_OK ){
42238         goto failed;
42239       }
42240  
42241       /* If it is not already open and the file exists on disk, open the 
42242       ** journal for read/write access. Write access is required because 
42243       ** in exclusive-access mode the file descriptor will be kept open 
42244       ** and possibly used for a transaction later on. Also, write-access 
42245       ** is usually required to finalize the journal in journal_mode=persist 
42246       ** mode (and also for journal_mode=truncate on some systems).
42247       **
42248       ** If the journal does not exist, it usually means that some 
42249       ** other connection managed to get in and roll it back before 
42250       ** this connection obtained the exclusive lock above. Or, it 
42251       ** may mean that the pager was in the error-state when this
42252       ** function was called and the journal file does not exist.
42253       */
42254       if( !isOpen(pPager->jfd) ){
42255         sqlite3_vfs * const pVfs = pPager->pVfs;
42256         int bExists;              /* True if journal file exists */
42257         rc = sqlite3OsAccess(
42258             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
42259         if( rc==SQLITE_OK && bExists ){
42260           int fout = 0;
42261           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
42262           assert( !pPager->tempFile );
42263           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
42264           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
42265           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
42266             rc = SQLITE_CANTOPEN_BKPT;
42267             sqlite3OsClose(pPager->jfd);
42268           }
42269         }
42270       }
42271  
42272       /* Playback and delete the journal.  Drop the database write
42273       ** lock and reacquire the read lock. Purge the cache before
42274       ** playing back the hot-journal so that we don't end up with
42275       ** an inconsistent cache.  Sync the hot journal before playing
42276       ** it back since the process that crashed and left the hot journal
42277       ** probably did not sync it and we are required to always sync
42278       ** the journal before playing it back.
42279       */
42280       if( isOpen(pPager->jfd) ){
42281         assert( rc==SQLITE_OK );
42282         rc = pagerSyncHotJournal(pPager);
42283         if( rc==SQLITE_OK ){
42284           rc = pager_playback(pPager, 1);
42285           pPager->eState = PAGER_OPEN;
42286         }
42287       }else if( !pPager->exclusiveMode ){
42288         pagerUnlockDb(pPager, SHARED_LOCK);
42289       }
42290
42291       if( rc!=SQLITE_OK ){
42292         /* This branch is taken if an error occurs while trying to open
42293         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
42294         ** pager_unlock() routine will be called before returning to unlock
42295         ** the file. If the unlock attempt fails, then Pager.eLock must be
42296         ** set to UNKNOWN_LOCK (see the comment above the #define for 
42297         ** UNKNOWN_LOCK above for an explanation). 
42298         **
42299         ** In order to get pager_unlock() to do this, set Pager.eState to
42300         ** PAGER_ERROR now. This is not actually counted as a transition
42301         ** to ERROR state in the state diagram at the top of this file,
42302         ** since we know that the same call to pager_unlock() will very
42303         ** shortly transition the pager object to the OPEN state. Calling
42304         ** assert_pager_state() would fail now, as it should not be possible
42305         ** to be in ERROR state when there are zero outstanding page 
42306         ** references.
42307         */
42308         pager_error(pPager, rc);
42309         goto failed;
42310       }
42311
42312       assert( pPager->eState==PAGER_OPEN );
42313       assert( (pPager->eLock==SHARED_LOCK)
42314            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
42315       );
42316     }
42317
42318     if( !pPager->tempFile 
42319      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0) 
42320     ){
42321       /* The shared-lock has just been acquired on the database file
42322       ** and there are already pages in the cache (from a previous
42323       ** read or write transaction).  Check to see if the database
42324       ** has been modified.  If the database has changed, flush the
42325       ** cache.
42326       **
42327       ** Database changes is detected by looking at 15 bytes beginning
42328       ** at offset 24 into the file.  The first 4 of these 16 bytes are
42329       ** a 32-bit counter that is incremented with each change.  The
42330       ** other bytes change randomly with each file change when
42331       ** a codec is in use.
42332       ** 
42333       ** There is a vanishingly small chance that a change will not be 
42334       ** detected.  The chance of an undetected change is so small that
42335       ** it can be neglected.
42336       */
42337       Pgno nPage = 0;
42338       char dbFileVers[sizeof(pPager->dbFileVers)];
42339
42340       rc = pagerPagecount(pPager, &nPage);
42341       if( rc ) goto failed;
42342
42343       if( nPage>0 ){
42344         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
42345         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
42346         if( rc!=SQLITE_OK ){
42347           goto failed;
42348         }
42349       }else{
42350         memset(dbFileVers, 0, sizeof(dbFileVers));
42351       }
42352
42353       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
42354         pager_reset(pPager);
42355       }
42356     }
42357
42358     /* If there is a WAL file in the file-system, open this database in WAL
42359     ** mode. Otherwise, the following function call is a no-op.
42360     */
42361     rc = pagerOpenWalIfPresent(pPager);
42362 #ifndef SQLITE_OMIT_WAL
42363     assert( pPager->pWal==0 || rc==SQLITE_OK );
42364 #endif
42365   }
42366
42367   if( pagerUseWal(pPager) ){
42368     assert( rc==SQLITE_OK );
42369     rc = pagerBeginReadTransaction(pPager);
42370   }
42371
42372   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
42373     rc = pagerPagecount(pPager, &pPager->dbSize);
42374   }
42375
42376  failed:
42377   if( rc!=SQLITE_OK ){
42378     assert( !MEMDB );
42379     pager_unlock(pPager);
42380     assert( pPager->eState==PAGER_OPEN );
42381   }else{
42382     pPager->eState = PAGER_READER;
42383   }
42384   return rc;
42385 }
42386
42387 /*
42388 ** If the reference count has reached zero, rollback any active
42389 ** transaction and unlock the pager.
42390 **
42391 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
42392 ** the rollback journal, the unlock is not performed and there is
42393 ** nothing to rollback, so this routine is a no-op.
42394 */ 
42395 static void pagerUnlockIfUnused(Pager *pPager){
42396   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
42397     pagerUnlockAndRollback(pPager);
42398   }
42399 }
42400
42401 /*
42402 ** Acquire a reference to page number pgno in pager pPager (a page
42403 ** reference has type DbPage*). If the requested reference is 
42404 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
42405 **
42406 ** If the requested page is already in the cache, it is returned. 
42407 ** Otherwise, a new page object is allocated and populated with data
42408 ** read from the database file. In some cases, the pcache module may
42409 ** choose not to allocate a new page object and may reuse an existing
42410 ** object with no outstanding references.
42411 **
42412 ** The extra data appended to a page is always initialized to zeros the 
42413 ** first time a page is loaded into memory. If the page requested is 
42414 ** already in the cache when this function is called, then the extra
42415 ** data is left as it was when the page object was last used.
42416 **
42417 ** If the database image is smaller than the requested page or if a 
42418 ** non-zero value is passed as the noContent parameter and the 
42419 ** requested page is not already stored in the cache, then no 
42420 ** actual disk read occurs. In this case the memory image of the 
42421 ** page is initialized to all zeros. 
42422 **
42423 ** If noContent is true, it means that we do not care about the contents
42424 ** of the page. This occurs in two seperate scenarios:
42425 **
42426 **   a) When reading a free-list leaf page from the database, and
42427 **
42428 **   b) When a savepoint is being rolled back and we need to load
42429 **      a new page into the cache to be filled with the data read
42430 **      from the savepoint journal.
42431 **
42432 ** If noContent is true, then the data returned is zeroed instead of
42433 ** being read from the database. Additionally, the bits corresponding
42434 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
42435 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
42436 ** savepoints are set. This means if the page is made writable at any
42437 ** point in the future, using a call to sqlite3PagerWrite(), its contents
42438 ** will not be journaled. This saves IO.
42439 **
42440 ** The acquisition might fail for several reasons.  In all cases,
42441 ** an appropriate error code is returned and *ppPage is set to NULL.
42442 **
42443 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
42444 ** to find a page in the in-memory cache first.  If the page is not already
42445 ** in memory, this routine goes to disk to read it in whereas Lookup()
42446 ** just returns 0.  This routine acquires a read-lock the first time it
42447 ** has to go to disk, and could also playback an old journal if necessary.
42448 ** Since Lookup() never goes to disk, it never has to deal with locks
42449 ** or journal files.
42450 */
42451 SQLITE_PRIVATE int sqlite3PagerAcquire(
42452   Pager *pPager,      /* The pager open on the database file */
42453   Pgno pgno,          /* Page number to fetch */
42454   DbPage **ppPage,    /* Write a pointer to the page here */
42455   int noContent       /* Do not bother reading content from disk if true */
42456 ){
42457   int rc;
42458   PgHdr *pPg;
42459
42460   assert( pPager->eState>=PAGER_READER );
42461   assert( assert_pager_state(pPager) );
42462
42463   if( pgno==0 ){
42464     return SQLITE_CORRUPT_BKPT;
42465   }
42466
42467   /* If the pager is in the error state, return an error immediately. 
42468   ** Otherwise, request the page from the PCache layer. */
42469   if( pPager->errCode!=SQLITE_OK ){
42470     rc = pPager->errCode;
42471   }else{
42472     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
42473   }
42474
42475   if( rc!=SQLITE_OK ){
42476     /* Either the call to sqlite3PcacheFetch() returned an error or the
42477     ** pager was already in the error-state when this function was called.
42478     ** Set pPg to 0 and jump to the exception handler.  */
42479     pPg = 0;
42480     goto pager_acquire_err;
42481   }
42482   assert( (*ppPage)->pgno==pgno );
42483   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
42484
42485   if( (*ppPage)->pPager && !noContent ){
42486     /* In this case the pcache already contains an initialized copy of
42487     ** the page. Return without further ado.  */
42488     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
42489     pPager->aStat[PAGER_STAT_HIT]++;
42490     return SQLITE_OK;
42491
42492   }else{
42493     /* The pager cache has created a new page. Its content needs to 
42494     ** be initialized.  */
42495
42496     pPg = *ppPage;
42497     pPg->pPager = pPager;
42498
42499     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
42500     ** number greater than this, or the unused locking-page, is requested. */
42501     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
42502       rc = SQLITE_CORRUPT_BKPT;
42503       goto pager_acquire_err;
42504     }
42505
42506     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
42507       if( pgno>pPager->mxPgno ){
42508         rc = SQLITE_FULL;
42509         goto pager_acquire_err;
42510       }
42511       if( noContent ){
42512         /* Failure to set the bits in the InJournal bit-vectors is benign.
42513         ** It merely means that we might do some extra work to journal a 
42514         ** page that does not need to be journaled.  Nevertheless, be sure 
42515         ** to test the case where a malloc error occurs while trying to set 
42516         ** a bit in a bit vector.
42517         */
42518         sqlite3BeginBenignMalloc();
42519         if( pgno<=pPager->dbOrigSize ){
42520           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
42521           testcase( rc==SQLITE_NOMEM );
42522         }
42523         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
42524         testcase( rc==SQLITE_NOMEM );
42525         sqlite3EndBenignMalloc();
42526       }
42527       memset(pPg->pData, 0, pPager->pageSize);
42528       IOTRACE(("ZERO %p %d\n", pPager, pgno));
42529     }else{
42530       assert( pPg->pPager==pPager );
42531       pPager->aStat[PAGER_STAT_MISS]++;
42532       rc = readDbPage(pPg);
42533       if( rc!=SQLITE_OK ){
42534         goto pager_acquire_err;
42535       }
42536     }
42537     pager_set_pagehash(pPg);
42538   }
42539
42540   return SQLITE_OK;
42541
42542 pager_acquire_err:
42543   assert( rc!=SQLITE_OK );
42544   if( pPg ){
42545     sqlite3PcacheDrop(pPg);
42546   }
42547   pagerUnlockIfUnused(pPager);
42548
42549   *ppPage = 0;
42550   return rc;
42551 }
42552
42553 /*
42554 ** Acquire a page if it is already in the in-memory cache.  Do
42555 ** not read the page from disk.  Return a pointer to the page,
42556 ** or 0 if the page is not in cache. 
42557 **
42558 ** See also sqlite3PagerGet().  The difference between this routine
42559 ** and sqlite3PagerGet() is that _get() will go to the disk and read
42560 ** in the page if the page is not already in cache.  This routine
42561 ** returns NULL if the page is not in cache or if a disk I/O error 
42562 ** has ever happened.
42563 */
42564 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
42565   PgHdr *pPg = 0;
42566   assert( pPager!=0 );
42567   assert( pgno!=0 );
42568   assert( pPager->pPCache!=0 );
42569   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
42570   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
42571   return pPg;
42572 }
42573
42574 /*
42575 ** Release a page reference.
42576 **
42577 ** If the number of references to the page drop to zero, then the
42578 ** page is added to the LRU list.  When all references to all pages
42579 ** are released, a rollback occurs and the lock on the database is
42580 ** removed.
42581 */
42582 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
42583   if( pPg ){
42584     Pager *pPager = pPg->pPager;
42585     sqlite3PcacheRelease(pPg);
42586     pagerUnlockIfUnused(pPager);
42587   }
42588 }
42589
42590 /*
42591 ** This function is called at the start of every write transaction.
42592 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
42593 ** file when this routine is called.
42594 **
42595 ** Open the journal file for pager pPager and write a journal header
42596 ** to the start of it. If there are active savepoints, open the sub-journal
42597 ** as well. This function is only used when the journal file is being 
42598 ** opened to write a rollback log for a transaction. It is not used 
42599 ** when opening a hot journal file to roll it back.
42600 **
42601 ** If the journal file is already open (as it may be in exclusive mode),
42602 ** then this function just writes a journal header to the start of the
42603 ** already open file. 
42604 **
42605 ** Whether or not the journal file is opened by this function, the
42606 ** Pager.pInJournal bitvec structure is allocated.
42607 **
42608 ** Return SQLITE_OK if everything is successful. Otherwise, return 
42609 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
42610 ** an IO error code if opening or writing the journal file fails.
42611 */
42612 static int pager_open_journal(Pager *pPager){
42613   int rc = SQLITE_OK;                        /* Return code */
42614   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
42615
42616   assert( pPager->eState==PAGER_WRITER_LOCKED );
42617   assert( assert_pager_state(pPager) );
42618   assert( pPager->pInJournal==0 );
42619   
42620   /* If already in the error state, this function is a no-op.  But on
42621   ** the other hand, this routine is never called if we are already in
42622   ** an error state. */
42623   if( NEVER(pPager->errCode) ) return pPager->errCode;
42624
42625   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
42626     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
42627     if( pPager->pInJournal==0 ){
42628       return SQLITE_NOMEM;
42629     }
42630   
42631     /* Open the journal file if it is not already open. */
42632     if( !isOpen(pPager->jfd) ){
42633       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
42634         sqlite3MemJournalOpen(pPager->jfd);
42635       }else{
42636         const int flags =                   /* VFS flags to open journal file */
42637           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
42638           (pPager->tempFile ? 
42639             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
42640             (SQLITE_OPEN_MAIN_JOURNAL)
42641           );
42642   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42643         rc = sqlite3JournalOpen(
42644             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
42645         );
42646   #else
42647         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
42648   #endif
42649       }
42650       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
42651     }
42652   
42653   
42654     /* Write the first journal header to the journal file and open 
42655     ** the sub-journal if necessary.
42656     */
42657     if( rc==SQLITE_OK ){
42658       /* TODO: Check if all of these are really required. */
42659       pPager->nRec = 0;
42660       pPager->journalOff = 0;
42661       pPager->setMaster = 0;
42662       pPager->journalHdr = 0;
42663       rc = writeJournalHdr(pPager);
42664     }
42665   }
42666
42667   if( rc!=SQLITE_OK ){
42668     sqlite3BitvecDestroy(pPager->pInJournal);
42669     pPager->pInJournal = 0;
42670   }else{
42671     assert( pPager->eState==PAGER_WRITER_LOCKED );
42672     pPager->eState = PAGER_WRITER_CACHEMOD;
42673   }
42674
42675   return rc;
42676 }
42677
42678 /*
42679 ** Begin a write-transaction on the specified pager object. If a 
42680 ** write-transaction has already been opened, this function is a no-op.
42681 **
42682 ** If the exFlag argument is false, then acquire at least a RESERVED
42683 ** lock on the database file. If exFlag is true, then acquire at least
42684 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
42685 ** functions need be called.
42686 **
42687 ** If the subjInMemory argument is non-zero, then any sub-journal opened
42688 ** within this transaction will be opened as an in-memory file. This
42689 ** has no effect if the sub-journal is already opened (as it may be when
42690 ** running in exclusive mode) or if the transaction does not require a
42691 ** sub-journal. If the subjInMemory argument is zero, then any required
42692 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
42693 ** or using a temporary file otherwise.
42694 */
42695 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
42696   int rc = SQLITE_OK;
42697
42698   if( pPager->errCode ) return pPager->errCode;
42699   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
42700   pPager->subjInMemory = (u8)subjInMemory;
42701
42702   if( ALWAYS(pPager->eState==PAGER_READER) ){
42703     assert( pPager->pInJournal==0 );
42704
42705     if( pagerUseWal(pPager) ){
42706       /* If the pager is configured to use locking_mode=exclusive, and an
42707       ** exclusive lock on the database is not already held, obtain it now.
42708       */
42709       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
42710         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42711         if( rc!=SQLITE_OK ){
42712           return rc;
42713         }
42714         sqlite3WalExclusiveMode(pPager->pWal, 1);
42715       }
42716
42717       /* Grab the write lock on the log file. If successful, upgrade to
42718       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
42719       ** The busy-handler is not invoked if another connection already
42720       ** holds the write-lock. If possible, the upper layer will call it.
42721       */
42722       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
42723     }else{
42724       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
42725       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
42726       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
42727       ** lock, but not when obtaining the RESERVED lock.
42728       */
42729       rc = pagerLockDb(pPager, RESERVED_LOCK);
42730       if( rc==SQLITE_OK && exFlag ){
42731         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42732       }
42733     }
42734
42735     if( rc==SQLITE_OK ){
42736       /* Change to WRITER_LOCKED state.
42737       **
42738       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
42739       ** when it has an open transaction, but never to DBMOD or FINISHED.
42740       ** This is because in those states the code to roll back savepoint 
42741       ** transactions may copy data from the sub-journal into the database 
42742       ** file as well as into the page cache. Which would be incorrect in 
42743       ** WAL mode.
42744       */
42745       pPager->eState = PAGER_WRITER_LOCKED;
42746       pPager->dbHintSize = pPager->dbSize;
42747       pPager->dbFileSize = pPager->dbSize;
42748       pPager->dbOrigSize = pPager->dbSize;
42749       pPager->journalOff = 0;
42750     }
42751
42752     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
42753     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
42754     assert( assert_pager_state(pPager) );
42755   }
42756
42757   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
42758   return rc;
42759 }
42760
42761 /*
42762 ** Mark a single data page as writeable. The page is written into the 
42763 ** main journal or sub-journal as required. If the page is written into
42764 ** one of the journals, the corresponding bit is set in the 
42765 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
42766 ** of any open savepoints as appropriate.
42767 */
42768 static int pager_write(PgHdr *pPg){
42769   void *pData = pPg->pData;
42770   Pager *pPager = pPg->pPager;
42771   int rc = SQLITE_OK;
42772
42773   /* This routine is not called unless a write-transaction has already 
42774   ** been started. The journal file may or may not be open at this point.
42775   ** It is never called in the ERROR state.
42776   */
42777   assert( pPager->eState==PAGER_WRITER_LOCKED
42778        || pPager->eState==PAGER_WRITER_CACHEMOD
42779        || pPager->eState==PAGER_WRITER_DBMOD
42780   );
42781   assert( assert_pager_state(pPager) );
42782
42783   /* If an error has been previously detected, report the same error
42784   ** again. This should not happen, but the check provides robustness. */
42785   if( NEVER(pPager->errCode) )  return pPager->errCode;
42786
42787   /* Higher-level routines never call this function if database is not
42788   ** writable.  But check anyway, just for robustness. */
42789   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
42790
42791   CHECK_PAGE(pPg);
42792
42793   /* The journal file needs to be opened. Higher level routines have already
42794   ** obtained the necessary locks to begin the write-transaction, but the
42795   ** rollback journal might not yet be open. Open it now if this is the case.
42796   **
42797   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
42798   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
42799   ** an error might occur and the pager would end up in WRITER_LOCKED state
42800   ** with pages marked as dirty in the cache.
42801   */
42802   if( pPager->eState==PAGER_WRITER_LOCKED ){
42803     rc = pager_open_journal(pPager);
42804     if( rc!=SQLITE_OK ) return rc;
42805   }
42806   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42807   assert( assert_pager_state(pPager) );
42808
42809   /* Mark the page as dirty.  If the page has already been written
42810   ** to the journal then we can return right away.
42811   */
42812   sqlite3PcacheMakeDirty(pPg);
42813   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
42814     assert( !pagerUseWal(pPager) );
42815   }else{
42816   
42817     /* The transaction journal now exists and we have a RESERVED or an
42818     ** EXCLUSIVE lock on the main database file.  Write the current page to
42819     ** the transaction journal if it is not there already.
42820     */
42821     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
42822       assert( pagerUseWal(pPager)==0 );
42823       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
42824         u32 cksum;
42825         char *pData2;
42826         i64 iOff = pPager->journalOff;
42827
42828         /* We should never write to the journal file the page that
42829         ** contains the database locks.  The following assert verifies
42830         ** that we do not. */
42831         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
42832
42833         assert( pPager->journalHdr<=pPager->journalOff );
42834         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
42835         cksum = pager_cksum(pPager, (u8*)pData2);
42836
42837         /* Even if an IO or diskfull error occurs while journalling the
42838         ** page in the block above, set the need-sync flag for the page.
42839         ** Otherwise, when the transaction is rolled back, the logic in
42840         ** playback_one_page() will think that the page needs to be restored
42841         ** in the database file. And if an IO error occurs while doing so,
42842         ** then corruption may follow.
42843         */
42844         pPg->flags |= PGHDR_NEED_SYNC;
42845
42846         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
42847         if( rc!=SQLITE_OK ) return rc;
42848         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
42849         if( rc!=SQLITE_OK ) return rc;
42850         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
42851         if( rc!=SQLITE_OK ) return rc;
42852
42853         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
42854                  pPager->journalOff, pPager->pageSize));
42855         PAGER_INCR(sqlite3_pager_writej_count);
42856         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
42857              PAGERID(pPager), pPg->pgno, 
42858              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
42859
42860         pPager->journalOff += 8 + pPager->pageSize;
42861         pPager->nRec++;
42862         assert( pPager->pInJournal!=0 );
42863         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
42864         testcase( rc==SQLITE_NOMEM );
42865         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
42866         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
42867         if( rc!=SQLITE_OK ){
42868           assert( rc==SQLITE_NOMEM );
42869           return rc;
42870         }
42871       }else{
42872         if( pPager->eState!=PAGER_WRITER_DBMOD ){
42873           pPg->flags |= PGHDR_NEED_SYNC;
42874         }
42875         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
42876                 PAGERID(pPager), pPg->pgno,
42877                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
42878       }
42879     }
42880   
42881     /* If the statement journal is open and the page is not in it,
42882     ** then write the current page to the statement journal.  Note that
42883     ** the statement journal format differs from the standard journal format
42884     ** in that it omits the checksums and the header.
42885     */
42886     if( subjRequiresPage(pPg) ){
42887       rc = subjournalPage(pPg);
42888     }
42889   }
42890
42891   /* Update the database size and return.
42892   */
42893   if( pPager->dbSize<pPg->pgno ){
42894     pPager->dbSize = pPg->pgno;
42895   }
42896   return rc;
42897 }
42898
42899 /*
42900 ** Mark a data page as writeable. This routine must be called before 
42901 ** making changes to a page. The caller must check the return value 
42902 ** of this function and be careful not to change any page data unless 
42903 ** this routine returns SQLITE_OK.
42904 **
42905 ** The difference between this function and pager_write() is that this
42906 ** function also deals with the special case where 2 or more pages
42907 ** fit on a single disk sector. In this case all co-resident pages
42908 ** must have been written to the journal file before returning.
42909 **
42910 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
42911 ** as appropriate. Otherwise, SQLITE_OK.
42912 */
42913 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
42914   int rc = SQLITE_OK;
42915
42916   PgHdr *pPg = pDbPage;
42917   Pager *pPager = pPg->pPager;
42918   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
42919
42920   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42921   assert( pPager->eState!=PAGER_ERROR );
42922   assert( assert_pager_state(pPager) );
42923
42924   if( nPagePerSector>1 ){
42925     Pgno nPageCount;          /* Total number of pages in database file */
42926     Pgno pg1;                 /* First page of the sector pPg is located on. */
42927     int nPage = 0;            /* Number of pages starting at pg1 to journal */
42928     int ii;                   /* Loop counter */
42929     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
42930
42931     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
42932     ** a journal header to be written between the pages journaled by
42933     ** this function.
42934     */
42935     assert( !MEMDB );
42936     assert( pPager->doNotSyncSpill==0 );
42937     pPager->doNotSyncSpill++;
42938
42939     /* This trick assumes that both the page-size and sector-size are
42940     ** an integer power of 2. It sets variable pg1 to the identifier
42941     ** of the first page of the sector pPg is located on.
42942     */
42943     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
42944
42945     nPageCount = pPager->dbSize;
42946     if( pPg->pgno>nPageCount ){
42947       nPage = (pPg->pgno - pg1)+1;
42948     }else if( (pg1+nPagePerSector-1)>nPageCount ){
42949       nPage = nPageCount+1-pg1;
42950     }else{
42951       nPage = nPagePerSector;
42952     }
42953     assert(nPage>0);
42954     assert(pg1<=pPg->pgno);
42955     assert((pg1+nPage)>pPg->pgno);
42956
42957     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
42958       Pgno pg = pg1+ii;
42959       PgHdr *pPage;
42960       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
42961         if( pg!=PAGER_MJ_PGNO(pPager) ){
42962           rc = sqlite3PagerGet(pPager, pg, &pPage);
42963           if( rc==SQLITE_OK ){
42964             rc = pager_write(pPage);
42965             if( pPage->flags&PGHDR_NEED_SYNC ){
42966               needSync = 1;
42967             }
42968             sqlite3PagerUnref(pPage);
42969           }
42970         }
42971       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
42972         if( pPage->flags&PGHDR_NEED_SYNC ){
42973           needSync = 1;
42974         }
42975         sqlite3PagerUnref(pPage);
42976       }
42977     }
42978
42979     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
42980     ** starting at pg1, then it needs to be set for all of them. Because
42981     ** writing to any of these nPage pages may damage the others, the
42982     ** journal file must contain sync()ed copies of all of them
42983     ** before any of them can be written out to the database file.
42984     */
42985     if( rc==SQLITE_OK && needSync ){
42986       assert( !MEMDB );
42987       for(ii=0; ii<nPage; ii++){
42988         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
42989         if( pPage ){
42990           pPage->flags |= PGHDR_NEED_SYNC;
42991           sqlite3PagerUnref(pPage);
42992         }
42993       }
42994     }
42995
42996     assert( pPager->doNotSyncSpill==1 );
42997     pPager->doNotSyncSpill--;
42998   }else{
42999     rc = pager_write(pDbPage);
43000   }
43001   return rc;
43002 }
43003
43004 /*
43005 ** Return TRUE if the page given in the argument was previously passed
43006 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
43007 ** to change the content of the page.
43008 */
43009 #ifndef NDEBUG
43010 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
43011   return pPg->flags&PGHDR_DIRTY;
43012 }
43013 #endif
43014
43015 /*
43016 ** A call to this routine tells the pager that it is not necessary to
43017 ** write the information on page pPg back to the disk, even though
43018 ** that page might be marked as dirty.  This happens, for example, when
43019 ** the page has been added as a leaf of the freelist and so its
43020 ** content no longer matters.
43021 **
43022 ** The overlying software layer calls this routine when all of the data
43023 ** on the given page is unused. The pager marks the page as clean so
43024 ** that it does not get written to disk.
43025 **
43026 ** Tests show that this optimization can quadruple the speed of large 
43027 ** DELETE operations.
43028 */
43029 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
43030   Pager *pPager = pPg->pPager;
43031   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
43032     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
43033     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
43034     pPg->flags |= PGHDR_DONT_WRITE;
43035     pager_set_pagehash(pPg);
43036   }
43037 }
43038
43039 /*
43040 ** This routine is called to increment the value of the database file 
43041 ** change-counter, stored as a 4-byte big-endian integer starting at 
43042 ** byte offset 24 of the pager file.  The secondary change counter at
43043 ** 92 is also updated, as is the SQLite version number at offset 96.
43044 **
43045 ** But this only happens if the pPager->changeCountDone flag is false.
43046 ** To avoid excess churning of page 1, the update only happens once.
43047 ** See also the pager_write_changecounter() routine that does an 
43048 ** unconditional update of the change counters.
43049 **
43050 ** If the isDirectMode flag is zero, then this is done by calling 
43051 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
43052 ** page data. In this case the file will be updated when the current
43053 ** transaction is committed.
43054 **
43055 ** The isDirectMode flag may only be non-zero if the library was compiled
43056 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
43057 ** if isDirect is non-zero, then the database file is updated directly
43058 ** by writing an updated version of page 1 using a call to the 
43059 ** sqlite3OsWrite() function.
43060 */
43061 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
43062   int rc = SQLITE_OK;
43063
43064   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43065        || pPager->eState==PAGER_WRITER_DBMOD
43066   );
43067   assert( assert_pager_state(pPager) );
43068
43069   /* Declare and initialize constant integer 'isDirect'. If the
43070   ** atomic-write optimization is enabled in this build, then isDirect
43071   ** is initialized to the value passed as the isDirectMode parameter
43072   ** to this function. Otherwise, it is always set to zero.
43073   **
43074   ** The idea is that if the atomic-write optimization is not
43075   ** enabled at compile time, the compiler can omit the tests of
43076   ** 'isDirect' below, as well as the block enclosed in the
43077   ** "if( isDirect )" condition.
43078   */
43079 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
43080 # define DIRECT_MODE 0
43081   assert( isDirectMode==0 );
43082   UNUSED_PARAMETER(isDirectMode);
43083 #else
43084 # define DIRECT_MODE isDirectMode
43085 #endif
43086
43087   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
43088     PgHdr *pPgHdr;                /* Reference to page 1 */
43089
43090     assert( !pPager->tempFile && isOpen(pPager->fd) );
43091
43092     /* Open page 1 of the file for writing. */
43093     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
43094     assert( pPgHdr==0 || rc==SQLITE_OK );
43095
43096     /* If page one was fetched successfully, and this function is not
43097     ** operating in direct-mode, make page 1 writable.  When not in 
43098     ** direct mode, page 1 is always held in cache and hence the PagerGet()
43099     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
43100     */
43101     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
43102       rc = sqlite3PagerWrite(pPgHdr);
43103     }
43104
43105     if( rc==SQLITE_OK ){
43106       /* Actually do the update of the change counter */
43107       pager_write_changecounter(pPgHdr);
43108
43109       /* If running in direct mode, write the contents of page 1 to the file. */
43110       if( DIRECT_MODE ){
43111         const void *zBuf;
43112         assert( pPager->dbFileSize>0 );
43113         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
43114         if( rc==SQLITE_OK ){
43115           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
43116           pPager->aStat[PAGER_STAT_WRITE]++;
43117         }
43118         if( rc==SQLITE_OK ){
43119           pPager->changeCountDone = 1;
43120         }
43121       }else{
43122         pPager->changeCountDone = 1;
43123       }
43124     }
43125
43126     /* Release the page reference. */
43127     sqlite3PagerUnref(pPgHdr);
43128   }
43129   return rc;
43130 }
43131
43132 /*
43133 ** Sync the database file to disk. This is a no-op for in-memory databases
43134 ** or pages with the Pager.noSync flag set.
43135 **
43136 ** If successful, or if called on a pager for which it is a no-op, this
43137 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
43138 */
43139 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
43140   int rc = SQLITE_OK;
43141   if( !pPager->noSync ){
43142     assert( !MEMDB );
43143     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
43144   }else if( isOpen(pPager->fd) ){
43145     assert( !MEMDB );
43146     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
43147     if( rc==SQLITE_NOTFOUND ){
43148       rc = SQLITE_OK;
43149     }
43150   }
43151   return rc;
43152 }
43153
43154 /*
43155 ** This function may only be called while a write-transaction is active in
43156 ** rollback. If the connection is in WAL mode, this call is a no-op. 
43157 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
43158 ** the database file, an attempt is made to obtain one.
43159 **
43160 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
43161 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
43162 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
43163 ** returned.
43164 */
43165 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
43166   int rc = SQLITE_OK;
43167   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
43168        || pPager->eState==PAGER_WRITER_DBMOD 
43169        || pPager->eState==PAGER_WRITER_LOCKED 
43170   );
43171   assert( assert_pager_state(pPager) );
43172   if( 0==pagerUseWal(pPager) ){
43173     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
43174   }
43175   return rc;
43176 }
43177
43178 /*
43179 ** Sync the database file for the pager pPager. zMaster points to the name
43180 ** of a master journal file that should be written into the individual
43181 ** journal file. zMaster may be NULL, which is interpreted as no master
43182 ** journal (a single database transaction).
43183 **
43184 ** This routine ensures that:
43185 **
43186 **   * The database file change-counter is updated,
43187 **   * the journal is synced (unless the atomic-write optimization is used),
43188 **   * all dirty pages are written to the database file, 
43189 **   * the database file is truncated (if required), and
43190 **   * the database file synced. 
43191 **
43192 ** The only thing that remains to commit the transaction is to finalize 
43193 ** (delete, truncate or zero the first part of) the journal file (or 
43194 ** delete the master journal file if specified).
43195 **
43196 ** Note that if zMaster==NULL, this does not overwrite a previous value
43197 ** passed to an sqlite3PagerCommitPhaseOne() call.
43198 **
43199 ** If the final parameter - noSync - is true, then the database file itself
43200 ** is not synced. The caller must call sqlite3PagerSync() directly to
43201 ** sync the database file before calling CommitPhaseTwo() to delete the
43202 ** journal file in this case.
43203 */
43204 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
43205   Pager *pPager,                  /* Pager object */
43206   const char *zMaster,            /* If not NULL, the master journal name */
43207   int noSync                      /* True to omit the xSync on the db file */
43208 ){
43209   int rc = SQLITE_OK;             /* Return code */
43210
43211   assert( pPager->eState==PAGER_WRITER_LOCKED
43212        || pPager->eState==PAGER_WRITER_CACHEMOD
43213        || pPager->eState==PAGER_WRITER_DBMOD
43214        || pPager->eState==PAGER_ERROR
43215   );
43216   assert( assert_pager_state(pPager) );
43217
43218   /* If a prior error occurred, report that error again. */
43219   if( NEVER(pPager->errCode) ) return pPager->errCode;
43220
43221   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
43222       pPager->zFilename, zMaster, pPager->dbSize));
43223
43224   /* If no database changes have been made, return early. */
43225   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
43226
43227   if( MEMDB ){
43228     /* If this is an in-memory db, or no pages have been written to, or this
43229     ** function has already been called, it is mostly a no-op.  However, any
43230     ** backup in progress needs to be restarted.
43231     */
43232     sqlite3BackupRestart(pPager->pBackup);
43233   }else{
43234     if( pagerUseWal(pPager) ){
43235       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
43236       PgHdr *pPageOne = 0;
43237       if( pList==0 ){
43238         /* Must have at least one page for the WAL commit flag.
43239         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
43240         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
43241         pList = pPageOne;
43242         pList->pDirty = 0;
43243       }
43244       assert( rc==SQLITE_OK );
43245       if( ALWAYS(pList) ){
43246         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
43247       }
43248       sqlite3PagerUnref(pPageOne);
43249       if( rc==SQLITE_OK ){
43250         sqlite3PcacheCleanAll(pPager->pPCache);
43251       }
43252     }else{
43253       /* The following block updates the change-counter. Exactly how it
43254       ** does this depends on whether or not the atomic-update optimization
43255       ** was enabled at compile time, and if this transaction meets the 
43256       ** runtime criteria to use the operation: 
43257       **
43258       **    * The file-system supports the atomic-write property for
43259       **      blocks of size page-size, and 
43260       **    * This commit is not part of a multi-file transaction, and
43261       **    * Exactly one page has been modified and store in the journal file.
43262       **
43263       ** If the optimization was not enabled at compile time, then the
43264       ** pager_incr_changecounter() function is called to update the change
43265       ** counter in 'indirect-mode'. If the optimization is compiled in but
43266       ** is not applicable to this transaction, call sqlite3JournalCreate()
43267       ** to make sure the journal file has actually been created, then call
43268       ** pager_incr_changecounter() to update the change-counter in indirect
43269       ** mode. 
43270       **
43271       ** Otherwise, if the optimization is both enabled and applicable,
43272       ** then call pager_incr_changecounter() to update the change-counter
43273       ** in 'direct' mode. In this case the journal file will never be
43274       ** created for this transaction.
43275       */
43276   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43277       PgHdr *pPg;
43278       assert( isOpen(pPager->jfd) 
43279            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
43280            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
43281       );
43282       if( !zMaster && isOpen(pPager->jfd) 
43283        && pPager->journalOff==jrnlBufferSize(pPager) 
43284        && pPager->dbSize>=pPager->dbOrigSize
43285        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
43286       ){
43287         /* Update the db file change counter via the direct-write method. The 
43288         ** following call will modify the in-memory representation of page 1 
43289         ** to include the updated change counter and then write page 1 
43290         ** directly to the database file. Because of the atomic-write 
43291         ** property of the host file-system, this is safe.
43292         */
43293         rc = pager_incr_changecounter(pPager, 1);
43294       }else{
43295         rc = sqlite3JournalCreate(pPager->jfd);
43296         if( rc==SQLITE_OK ){
43297           rc = pager_incr_changecounter(pPager, 0);
43298         }
43299       }
43300   #else
43301       rc = pager_incr_changecounter(pPager, 0);
43302   #endif
43303       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43304   
43305       /* Write the master journal name into the journal file. If a master 
43306       ** journal file name has already been written to the journal file, 
43307       ** or if zMaster is NULL (no master journal), then this call is a no-op.
43308       */
43309       rc = writeMasterJournal(pPager, zMaster);
43310       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43311   
43312       /* Sync the journal file and write all dirty pages to the database.
43313       ** If the atomic-update optimization is being used, this sync will not 
43314       ** create the journal file or perform any real IO.
43315       **
43316       ** Because the change-counter page was just modified, unless the
43317       ** atomic-update optimization is used it is almost certain that the
43318       ** journal requires a sync here. However, in locking_mode=exclusive
43319       ** on a system under memory pressure it is just possible that this is 
43320       ** not the case. In this case it is likely enough that the redundant
43321       ** xSync() call will be changed to a no-op by the OS anyhow. 
43322       */
43323       rc = syncJournal(pPager, 0);
43324       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43325   
43326       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
43327       if( rc!=SQLITE_OK ){
43328         assert( rc!=SQLITE_IOERR_BLOCKED );
43329         goto commit_phase_one_exit;
43330       }
43331       sqlite3PcacheCleanAll(pPager->pPCache);
43332
43333       /* If the file on disk is smaller than the database image, use 
43334       ** pager_truncate to grow the file here. This can happen if the database
43335       ** image was extended as part of the current transaction and then the
43336       ** last page in the db image moved to the free-list. In this case the
43337       ** last page is never written out to disk, leaving the database file
43338       ** undersized. Fix this now if it is the case.  */
43339       if( pPager->dbSize>pPager->dbFileSize ){
43340         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
43341         assert( pPager->eState==PAGER_WRITER_DBMOD );
43342         rc = pager_truncate(pPager, nNew);
43343         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43344       }
43345   
43346       /* Finally, sync the database file. */
43347       if( !noSync ){
43348         rc = sqlite3PagerSync(pPager);
43349       }
43350       IOTRACE(("DBSYNC %p\n", pPager))
43351     }
43352   }
43353
43354 commit_phase_one_exit:
43355   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
43356     pPager->eState = PAGER_WRITER_FINISHED;
43357   }
43358   return rc;
43359 }
43360
43361
43362 /*
43363 ** When this function is called, the database file has been completely
43364 ** updated to reflect the changes made by the current transaction and
43365 ** synced to disk. The journal file still exists in the file-system 
43366 ** though, and if a failure occurs at this point it will eventually
43367 ** be used as a hot-journal and the current transaction rolled back.
43368 **
43369 ** This function finalizes the journal file, either by deleting, 
43370 ** truncating or partially zeroing it, so that it cannot be used 
43371 ** for hot-journal rollback. Once this is done the transaction is
43372 ** irrevocably committed.
43373 **
43374 ** If an error occurs, an IO error code is returned and the pager
43375 ** moves into the error state. Otherwise, SQLITE_OK is returned.
43376 */
43377 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
43378   int rc = SQLITE_OK;                  /* Return code */
43379
43380   /* This routine should not be called if a prior error has occurred.
43381   ** But if (due to a coding error elsewhere in the system) it does get
43382   ** called, just return the same error code without doing anything. */
43383   if( NEVER(pPager->errCode) ) return pPager->errCode;
43384
43385   assert( pPager->eState==PAGER_WRITER_LOCKED
43386        || pPager->eState==PAGER_WRITER_FINISHED
43387        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
43388   );
43389   assert( assert_pager_state(pPager) );
43390
43391   /* An optimization. If the database was not actually modified during
43392   ** this transaction, the pager is running in exclusive-mode and is
43393   ** using persistent journals, then this function is a no-op.
43394   **
43395   ** The start of the journal file currently contains a single journal 
43396   ** header with the nRec field set to 0. If such a journal is used as
43397   ** a hot-journal during hot-journal rollback, 0 changes will be made
43398   ** to the database file. So there is no need to zero the journal 
43399   ** header. Since the pager is in exclusive mode, there is no need
43400   ** to drop any locks either.
43401   */
43402   if( pPager->eState==PAGER_WRITER_LOCKED 
43403    && pPager->exclusiveMode 
43404    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
43405   ){
43406     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
43407     pPager->eState = PAGER_READER;
43408     return SQLITE_OK;
43409   }
43410
43411   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
43412   rc = pager_end_transaction(pPager, pPager->setMaster, 1);
43413   return pager_error(pPager, rc);
43414 }
43415
43416 /*
43417 ** If a write transaction is open, then all changes made within the 
43418 ** transaction are reverted and the current write-transaction is closed.
43419 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
43420 ** state if an error occurs.
43421 **
43422 ** If the pager is already in PAGER_ERROR state when this function is called,
43423 ** it returns Pager.errCode immediately. No work is performed in this case.
43424 **
43425 ** Otherwise, in rollback mode, this function performs two functions:
43426 **
43427 **   1) It rolls back the journal file, restoring all database file and 
43428 **      in-memory cache pages to the state they were in when the transaction
43429 **      was opened, and
43430 **
43431 **   2) It finalizes the journal file, so that it is not used for hot
43432 **      rollback at any point in the future.
43433 **
43434 ** Finalization of the journal file (task 2) is only performed if the 
43435 ** rollback is successful.
43436 **
43437 ** In WAL mode, all cache-entries containing data modified within the
43438 ** current transaction are either expelled from the cache or reverted to
43439 ** their pre-transaction state by re-reading data from the database or
43440 ** WAL files. The WAL transaction is then closed.
43441 */
43442 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
43443   int rc = SQLITE_OK;                  /* Return code */
43444   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
43445
43446   /* PagerRollback() is a no-op if called in READER or OPEN state. If
43447   ** the pager is already in the ERROR state, the rollback is not 
43448   ** attempted here. Instead, the error code is returned to the caller.
43449   */
43450   assert( assert_pager_state(pPager) );
43451   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
43452   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
43453
43454   if( pagerUseWal(pPager) ){
43455     int rc2;
43456     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
43457     rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
43458     if( rc==SQLITE_OK ) rc = rc2;
43459   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
43460     int eState = pPager->eState;
43461     rc = pager_end_transaction(pPager, 0, 0);
43462     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
43463       /* This can happen using journal_mode=off. Move the pager to the error 
43464       ** state to indicate that the contents of the cache may not be trusted.
43465       ** Any active readers will get SQLITE_ABORT.
43466       */
43467       pPager->errCode = SQLITE_ABORT;
43468       pPager->eState = PAGER_ERROR;
43469       return rc;
43470     }
43471   }else{
43472     rc = pager_playback(pPager, 0);
43473   }
43474
43475   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
43476   assert( rc==SQLITE_OK || rc==SQLITE_FULL
43477           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
43478
43479   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
43480   ** cache. So call pager_error() on the way out to make any error persistent.
43481   */
43482   return pager_error(pPager, rc);
43483 }
43484
43485 /*
43486 ** Return TRUE if the database file is opened read-only.  Return FALSE
43487 ** if the database is (in theory) writable.
43488 */
43489 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
43490   return pPager->readOnly;
43491 }
43492
43493 /*
43494 ** Return the number of references to the pager.
43495 */
43496 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
43497   return sqlite3PcacheRefCount(pPager->pPCache);
43498 }
43499
43500 /*
43501 ** Return the approximate number of bytes of memory currently
43502 ** used by the pager and its associated cache.
43503 */
43504 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
43505   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
43506                                      + 5*sizeof(void*);
43507   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
43508            + sqlite3MallocSize(pPager)
43509            + pPager->pageSize;
43510 }
43511
43512 /*
43513 ** Return the number of references to the specified page.
43514 */
43515 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
43516   return sqlite3PcachePageRefcount(pPage);
43517 }
43518
43519 #ifdef SQLITE_TEST
43520 /*
43521 ** This routine is used for testing and analysis only.
43522 */
43523 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
43524   static int a[11];
43525   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
43526   a[1] = sqlite3PcachePagecount(pPager->pPCache);
43527   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
43528   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
43529   a[4] = pPager->eState;
43530   a[5] = pPager->errCode;
43531   a[6] = pPager->aStat[PAGER_STAT_HIT];
43532   a[7] = pPager->aStat[PAGER_STAT_MISS];
43533   a[8] = 0;  /* Used to be pPager->nOvfl */
43534   a[9] = pPager->nRead;
43535   a[10] = pPager->aStat[PAGER_STAT_WRITE];
43536   return a;
43537 }
43538 #endif
43539
43540 /*
43541 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
43542 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
43543 ** current cache hit or miss count, according to the value of eStat. If the 
43544 ** reset parameter is non-zero, the cache hit or miss count is zeroed before 
43545 ** returning.
43546 */
43547 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
43548
43549   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
43550        || eStat==SQLITE_DBSTATUS_CACHE_MISS
43551        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
43552   );
43553
43554   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
43555   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
43556   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
43557
43558   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
43559   if( reset ){
43560     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
43561   }
43562 }
43563
43564 /*
43565 ** Return true if this is an in-memory pager.
43566 */
43567 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
43568   return MEMDB;
43569 }
43570
43571 /*
43572 ** Check that there are at least nSavepoint savepoints open. If there are
43573 ** currently less than nSavepoints open, then open one or more savepoints
43574 ** to make up the difference. If the number of savepoints is already
43575 ** equal to nSavepoint, then this function is a no-op.
43576 **
43577 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
43578 ** occurs while opening the sub-journal file, then an IO error code is
43579 ** returned. Otherwise, SQLITE_OK.
43580 */
43581 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
43582   int rc = SQLITE_OK;                       /* Return code */
43583   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
43584
43585   assert( pPager->eState>=PAGER_WRITER_LOCKED );
43586   assert( assert_pager_state(pPager) );
43587
43588   if( nSavepoint>nCurrent && pPager->useJournal ){
43589     int ii;                                 /* Iterator variable */
43590     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
43591
43592     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
43593     ** if the allocation fails. Otherwise, zero the new portion in case a 
43594     ** malloc failure occurs while populating it in the for(...) loop below.
43595     */
43596     aNew = (PagerSavepoint *)sqlite3Realloc(
43597         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
43598     );
43599     if( !aNew ){
43600       return SQLITE_NOMEM;
43601     }
43602     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
43603     pPager->aSavepoint = aNew;
43604
43605     /* Populate the PagerSavepoint structures just allocated. */
43606     for(ii=nCurrent; ii<nSavepoint; ii++){
43607       aNew[ii].nOrig = pPager->dbSize;
43608       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
43609         aNew[ii].iOffset = pPager->journalOff;
43610       }else{
43611         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
43612       }
43613       aNew[ii].iSubRec = pPager->nSubRec;
43614       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
43615       if( !aNew[ii].pInSavepoint ){
43616         return SQLITE_NOMEM;
43617       }
43618       if( pagerUseWal(pPager) ){
43619         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
43620       }
43621       pPager->nSavepoint = ii+1;
43622     }
43623     assert( pPager->nSavepoint==nSavepoint );
43624     assertTruncateConstraint(pPager);
43625   }
43626
43627   return rc;
43628 }
43629
43630 /*
43631 ** This function is called to rollback or release (commit) a savepoint.
43632 ** The savepoint to release or rollback need not be the most recently 
43633 ** created savepoint.
43634 **
43635 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
43636 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
43637 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
43638 ** that have occurred since the specified savepoint was created.
43639 **
43640 ** The savepoint to rollback or release is identified by parameter 
43641 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
43642 ** (the first created). A value of (Pager.nSavepoint-1) means operate
43643 ** on the most recently created savepoint. If iSavepoint is greater than
43644 ** (Pager.nSavepoint-1), then this function is a no-op.
43645 **
43646 ** If a negative value is passed to this function, then the current
43647 ** transaction is rolled back. This is different to calling 
43648 ** sqlite3PagerRollback() because this function does not terminate
43649 ** the transaction or unlock the database, it just restores the 
43650 ** contents of the database to its original state. 
43651 **
43652 ** In any case, all savepoints with an index greater than iSavepoint 
43653 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
43654 ** then savepoint iSavepoint is also destroyed.
43655 **
43656 ** This function may return SQLITE_NOMEM if a memory allocation fails,
43657 ** or an IO error code if an IO error occurs while rolling back a 
43658 ** savepoint. If no errors occur, SQLITE_OK is returned.
43659 */ 
43660 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
43661   int rc = pPager->errCode;       /* Return code */
43662
43663   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
43664   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
43665
43666   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
43667     int ii;            /* Iterator variable */
43668     int nNew;          /* Number of remaining savepoints after this op. */
43669
43670     /* Figure out how many savepoints will still be active after this
43671     ** operation. Store this value in nNew. Then free resources associated 
43672     ** with any savepoints that are destroyed by this operation.
43673     */
43674     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
43675     for(ii=nNew; ii<pPager->nSavepoint; ii++){
43676       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
43677     }
43678     pPager->nSavepoint = nNew;
43679
43680     /* If this is a release of the outermost savepoint, truncate 
43681     ** the sub-journal to zero bytes in size. */
43682     if( op==SAVEPOINT_RELEASE ){
43683       if( nNew==0 && isOpen(pPager->sjfd) ){
43684         /* Only truncate if it is an in-memory sub-journal. */
43685         if( sqlite3IsMemJournal(pPager->sjfd) ){
43686           rc = sqlite3OsTruncate(pPager->sjfd, 0);
43687           assert( rc==SQLITE_OK );
43688         }
43689         pPager->nSubRec = 0;
43690       }
43691     }
43692     /* Else this is a rollback operation, playback the specified savepoint.
43693     ** If this is a temp-file, it is possible that the journal file has
43694     ** not yet been opened. In this case there have been no changes to
43695     ** the database file, so the playback operation can be skipped.
43696     */
43697     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
43698       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
43699       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
43700       assert(rc!=SQLITE_DONE);
43701     }
43702   }
43703
43704   return rc;
43705 }
43706
43707 /*
43708 ** Return the full pathname of the database file.
43709 **
43710 ** Except, if the pager is in-memory only, then return an empty string if
43711 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
43712 ** used to report the filename to the user, for compatibility with legacy
43713 ** behavior.  But when the Btree needs to know the filename for matching to
43714 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
43715 ** participate in shared-cache.
43716 */
43717 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
43718   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
43719 }
43720
43721 /*
43722 ** Return the VFS structure for the pager.
43723 */
43724 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
43725   return pPager->pVfs;
43726 }
43727
43728 /*
43729 ** Return the file handle for the database file associated
43730 ** with the pager.  This might return NULL if the file has
43731 ** not yet been opened.
43732 */
43733 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
43734   return pPager->fd;
43735 }
43736
43737 /*
43738 ** Return the full pathname of the journal file.
43739 */
43740 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
43741   return pPager->zJournal;
43742 }
43743
43744 /*
43745 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
43746 ** if fsync()s are executed normally.
43747 */
43748 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
43749   return pPager->noSync;
43750 }
43751
43752 #ifdef SQLITE_HAS_CODEC
43753 /*
43754 ** Set or retrieve the codec for this pager
43755 */
43756 SQLITE_PRIVATE void sqlite3PagerSetCodec(
43757   Pager *pPager,
43758   void *(*xCodec)(void*,void*,Pgno,int),
43759   void (*xCodecSizeChng)(void*,int,int),
43760   void (*xCodecFree)(void*),
43761   void *pCodec
43762 ){
43763   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43764   pPager->xCodec = pPager->memDb ? 0 : xCodec;
43765   pPager->xCodecSizeChng = xCodecSizeChng;
43766   pPager->xCodecFree = xCodecFree;
43767   pPager->pCodec = pCodec;
43768   pagerReportSize(pPager);
43769 }
43770 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
43771   return pPager->pCodec;
43772 }
43773 #endif
43774
43775 #ifndef SQLITE_OMIT_AUTOVACUUM
43776 /*
43777 ** Move the page pPg to location pgno in the file.
43778 **
43779 ** There must be no references to the page previously located at
43780 ** pgno (which we call pPgOld) though that page is allowed to be
43781 ** in cache.  If the page previously located at pgno is not already
43782 ** in the rollback journal, it is not put there by by this routine.
43783 **
43784 ** References to the page pPg remain valid. Updating any
43785 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
43786 ** allocated along with the page) is the responsibility of the caller.
43787 **
43788 ** A transaction must be active when this routine is called. It used to be
43789 ** required that a statement transaction was not active, but this restriction
43790 ** has been removed (CREATE INDEX needs to move a page when a statement
43791 ** transaction is active).
43792 **
43793 ** If the fourth argument, isCommit, is non-zero, then this page is being
43794 ** moved as part of a database reorganization just before the transaction 
43795 ** is being committed. In this case, it is guaranteed that the database page 
43796 ** pPg refers to will not be written to again within this transaction.
43797 **
43798 ** This function may return SQLITE_NOMEM or an IO error code if an error
43799 ** occurs. Otherwise, it returns SQLITE_OK.
43800 */
43801 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
43802   PgHdr *pPgOld;               /* The page being overwritten. */
43803   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
43804   int rc;                      /* Return code */
43805   Pgno origPgno;               /* The original page number */
43806
43807   assert( pPg->nRef>0 );
43808   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43809        || pPager->eState==PAGER_WRITER_DBMOD
43810   );
43811   assert( assert_pager_state(pPager) );
43812
43813   /* In order to be able to rollback, an in-memory database must journal
43814   ** the page we are moving from.
43815   */
43816   if( MEMDB ){
43817     rc = sqlite3PagerWrite(pPg);
43818     if( rc ) return rc;
43819   }
43820
43821   /* If the page being moved is dirty and has not been saved by the latest
43822   ** savepoint, then save the current contents of the page into the 
43823   ** sub-journal now. This is required to handle the following scenario:
43824   **
43825   **   BEGIN;
43826   **     <journal page X, then modify it in memory>
43827   **     SAVEPOINT one;
43828   **       <Move page X to location Y>
43829   **     ROLLBACK TO one;
43830   **
43831   ** If page X were not written to the sub-journal here, it would not
43832   ** be possible to restore its contents when the "ROLLBACK TO one"
43833   ** statement were is processed.
43834   **
43835   ** subjournalPage() may need to allocate space to store pPg->pgno into
43836   ** one or more savepoint bitvecs. This is the reason this function
43837   ** may return SQLITE_NOMEM.
43838   */
43839   if( pPg->flags&PGHDR_DIRTY
43840    && subjRequiresPage(pPg)
43841    && SQLITE_OK!=(rc = subjournalPage(pPg))
43842   ){
43843     return rc;
43844   }
43845
43846   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
43847       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
43848   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
43849
43850   /* If the journal needs to be sync()ed before page pPg->pgno can
43851   ** be written to, store pPg->pgno in local variable needSyncPgno.
43852   **
43853   ** If the isCommit flag is set, there is no need to remember that
43854   ** the journal needs to be sync()ed before database page pPg->pgno 
43855   ** can be written to. The caller has already promised not to write to it.
43856   */
43857   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
43858     needSyncPgno = pPg->pgno;
43859     assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
43860             pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
43861     assert( pPg->flags&PGHDR_DIRTY );
43862   }
43863
43864   /* If the cache contains a page with page-number pgno, remove it
43865   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
43866   ** page pgno before the 'move' operation, it needs to be retained 
43867   ** for the page moved there.
43868   */
43869   pPg->flags &= ~PGHDR_NEED_SYNC;
43870   pPgOld = pager_lookup(pPager, pgno);
43871   assert( !pPgOld || pPgOld->nRef==1 );
43872   if( pPgOld ){
43873     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
43874     if( MEMDB ){
43875       /* Do not discard pages from an in-memory database since we might
43876       ** need to rollback later.  Just move the page out of the way. */
43877       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
43878     }else{
43879       sqlite3PcacheDrop(pPgOld);
43880     }
43881   }
43882
43883   origPgno = pPg->pgno;
43884   sqlite3PcacheMove(pPg, pgno);
43885   sqlite3PcacheMakeDirty(pPg);
43886
43887   /* For an in-memory database, make sure the original page continues
43888   ** to exist, in case the transaction needs to roll back.  Use pPgOld
43889   ** as the original page since it has already been allocated.
43890   */
43891   if( MEMDB ){
43892     assert( pPgOld );
43893     sqlite3PcacheMove(pPgOld, origPgno);
43894     sqlite3PagerUnref(pPgOld);
43895   }
43896
43897   if( needSyncPgno ){
43898     /* If needSyncPgno is non-zero, then the journal file needs to be 
43899     ** sync()ed before any data is written to database file page needSyncPgno.
43900     ** Currently, no such page exists in the page-cache and the 
43901     ** "is journaled" bitvec flag has been set. This needs to be remedied by
43902     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
43903     ** flag.
43904     **
43905     ** If the attempt to load the page into the page-cache fails, (due
43906     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
43907     ** array. Otherwise, if the page is loaded and written again in
43908     ** this transaction, it may be written to the database file before
43909     ** it is synced into the journal file. This way, it may end up in
43910     ** the journal file twice, but that is not a problem.
43911     */
43912     PgHdr *pPgHdr;
43913     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
43914     if( rc!=SQLITE_OK ){
43915       if( needSyncPgno<=pPager->dbOrigSize ){
43916         assert( pPager->pTmpSpace!=0 );
43917         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
43918       }
43919       return rc;
43920     }
43921     pPgHdr->flags |= PGHDR_NEED_SYNC;
43922     sqlite3PcacheMakeDirty(pPgHdr);
43923     sqlite3PagerUnref(pPgHdr);
43924   }
43925
43926   return SQLITE_OK;
43927 }
43928 #endif
43929
43930 /*
43931 ** Return a pointer to the data for the specified page.
43932 */
43933 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
43934   assert( pPg->nRef>0 || pPg->pPager->memDb );
43935   return pPg->pData;
43936 }
43937
43938 /*
43939 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
43940 ** allocated along with the specified page.
43941 */
43942 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
43943   return pPg->pExtra;
43944 }
43945
43946 /*
43947 ** Get/set the locking-mode for this pager. Parameter eMode must be one
43948 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
43949 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
43950 ** the locking-mode is set to the value specified.
43951 **
43952 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
43953 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
43954 ** locking-mode.
43955 */
43956 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
43957   assert( eMode==PAGER_LOCKINGMODE_QUERY
43958             || eMode==PAGER_LOCKINGMODE_NORMAL
43959             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
43960   assert( PAGER_LOCKINGMODE_QUERY<0 );
43961   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
43962   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
43963   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
43964     pPager->exclusiveMode = (u8)eMode;
43965   }
43966   return (int)pPager->exclusiveMode;
43967 }
43968
43969 /*
43970 ** Set the journal-mode for this pager. Parameter eMode must be one of:
43971 **
43972 **    PAGER_JOURNALMODE_DELETE
43973 **    PAGER_JOURNALMODE_TRUNCATE
43974 **    PAGER_JOURNALMODE_PERSIST
43975 **    PAGER_JOURNALMODE_OFF
43976 **    PAGER_JOURNALMODE_MEMORY
43977 **    PAGER_JOURNALMODE_WAL
43978 **
43979 ** The journalmode is set to the value specified if the change is allowed.
43980 ** The change may be disallowed for the following reasons:
43981 **
43982 **   *  An in-memory database can only have its journal_mode set to _OFF
43983 **      or _MEMORY.
43984 **
43985 **   *  Temporary databases cannot have _WAL journalmode.
43986 **
43987 ** The returned indicate the current (possibly updated) journal-mode.
43988 */
43989 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
43990   u8 eOld = pPager->journalMode;    /* Prior journalmode */
43991
43992 #ifdef SQLITE_DEBUG
43993   /* The print_pager_state() routine is intended to be used by the debugger
43994   ** only.  We invoke it once here to suppress a compiler warning. */
43995   print_pager_state(pPager);
43996 #endif
43997
43998
43999   /* The eMode parameter is always valid */
44000   assert(      eMode==PAGER_JOURNALMODE_DELETE
44001             || eMode==PAGER_JOURNALMODE_TRUNCATE
44002             || eMode==PAGER_JOURNALMODE_PERSIST
44003             || eMode==PAGER_JOURNALMODE_OFF 
44004             || eMode==PAGER_JOURNALMODE_WAL 
44005             || eMode==PAGER_JOURNALMODE_MEMORY );
44006
44007   /* This routine is only called from the OP_JournalMode opcode, and
44008   ** the logic there will never allow a temporary file to be changed
44009   ** to WAL mode.
44010   */
44011   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
44012
44013   /* Do allow the journalmode of an in-memory database to be set to
44014   ** anything other than MEMORY or OFF
44015   */
44016   if( MEMDB ){
44017     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
44018     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
44019       eMode = eOld;
44020     }
44021   }
44022
44023   if( eMode!=eOld ){
44024
44025     /* Change the journal mode. */
44026     assert( pPager->eState!=PAGER_ERROR );
44027     pPager->journalMode = (u8)eMode;
44028
44029     /* When transistioning from TRUNCATE or PERSIST to any other journal
44030     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
44031     ** delete the journal file.
44032     */
44033     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
44034     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
44035     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
44036     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
44037     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
44038     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
44039
44040     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
44041     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
44042
44043       /* In this case we would like to delete the journal file. If it is
44044       ** not possible, then that is not a problem. Deleting the journal file
44045       ** here is an optimization only.
44046       **
44047       ** Before deleting the journal file, obtain a RESERVED lock on the
44048       ** database file. This ensures that the journal file is not deleted
44049       ** while it is in use by some other client.
44050       */
44051       sqlite3OsClose(pPager->jfd);
44052       if( pPager->eLock>=RESERVED_LOCK ){
44053         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
44054       }else{
44055         int rc = SQLITE_OK;
44056         int state = pPager->eState;
44057         assert( state==PAGER_OPEN || state==PAGER_READER );
44058         if( state==PAGER_OPEN ){
44059           rc = sqlite3PagerSharedLock(pPager);
44060         }
44061         if( pPager->eState==PAGER_READER ){
44062           assert( rc==SQLITE_OK );
44063           rc = pagerLockDb(pPager, RESERVED_LOCK);
44064         }
44065         if( rc==SQLITE_OK ){
44066           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
44067         }
44068         if( rc==SQLITE_OK && state==PAGER_READER ){
44069           pagerUnlockDb(pPager, SHARED_LOCK);
44070         }else if( state==PAGER_OPEN ){
44071           pager_unlock(pPager);
44072         }
44073         assert( state==pPager->eState );
44074       }
44075     }
44076   }
44077
44078   /* Return the new journal mode */
44079   return (int)pPager->journalMode;
44080 }
44081
44082 /*
44083 ** Return the current journal mode.
44084 */
44085 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
44086   return (int)pPager->journalMode;
44087 }
44088
44089 /*
44090 ** Return TRUE if the pager is in a state where it is OK to change the
44091 ** journalmode.  Journalmode changes can only happen when the database
44092 ** is unmodified.
44093 */
44094 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
44095   assert( assert_pager_state(pPager) );
44096   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
44097   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
44098   return 1;
44099 }
44100
44101 /*
44102 ** Get/set the size-limit used for persistent journal files.
44103 **
44104 ** Setting the size limit to -1 means no limit is enforced.
44105 ** An attempt to set a limit smaller than -1 is a no-op.
44106 */
44107 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
44108   if( iLimit>=-1 ){
44109     pPager->journalSizeLimit = iLimit;
44110     sqlite3WalLimit(pPager->pWal, iLimit);
44111   }
44112   return pPager->journalSizeLimit;
44113 }
44114
44115 /*
44116 ** Return a pointer to the pPager->pBackup variable. The backup module
44117 ** in backup.c maintains the content of this variable. This module
44118 ** uses it opaquely as an argument to sqlite3BackupRestart() and
44119 ** sqlite3BackupUpdate() only.
44120 */
44121 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
44122   return &pPager->pBackup;
44123 }
44124
44125 #ifndef SQLITE_OMIT_VACUUM
44126 /*
44127 ** Unless this is an in-memory or temporary database, clear the pager cache.
44128 */
44129 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
44130   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
44131 }
44132 #endif
44133
44134 #ifndef SQLITE_OMIT_WAL
44135 /*
44136 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
44137 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
44138 ** or wal_blocking_checkpoint() API functions.
44139 **
44140 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
44141 */
44142 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
44143   int rc = SQLITE_OK;
44144   if( pPager->pWal ){
44145     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
44146         pPager->xBusyHandler, pPager->pBusyHandlerArg,
44147         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
44148         pnLog, pnCkpt
44149     );
44150   }
44151   return rc;
44152 }
44153
44154 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
44155   return sqlite3WalCallback(pPager->pWal);
44156 }
44157
44158 /*
44159 ** Return true if the underlying VFS for the given pager supports the
44160 ** primitives necessary for write-ahead logging.
44161 */
44162 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
44163   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
44164   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
44165 }
44166
44167 /*
44168 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
44169 ** is obtained instead, immediately release it.
44170 */
44171 static int pagerExclusiveLock(Pager *pPager){
44172   int rc;                         /* Return code */
44173
44174   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
44175   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44176   if( rc!=SQLITE_OK ){
44177     /* If the attempt to grab the exclusive lock failed, release the 
44178     ** pending lock that may have been obtained instead.  */
44179     pagerUnlockDb(pPager, SHARED_LOCK);
44180   }
44181
44182   return rc;
44183 }
44184
44185 /*
44186 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
44187 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
44188 ** lock on the database file and use heap-memory to store the wal-index
44189 ** in. Otherwise, use the normal shared-memory.
44190 */
44191 static int pagerOpenWal(Pager *pPager){
44192   int rc = SQLITE_OK;
44193
44194   assert( pPager->pWal==0 && pPager->tempFile==0 );
44195   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
44196
44197   /* If the pager is already in exclusive-mode, the WAL module will use 
44198   ** heap-memory for the wal-index instead of the VFS shared-memory 
44199   ** implementation. Take the exclusive lock now, before opening the WAL
44200   ** file, to make sure this is safe.
44201   */
44202   if( pPager->exclusiveMode ){
44203     rc = pagerExclusiveLock(pPager);
44204   }
44205
44206   /* Open the connection to the log file. If this operation fails, 
44207   ** (e.g. due to malloc() failure), return an error code.
44208   */
44209   if( rc==SQLITE_OK ){
44210     rc = sqlite3WalOpen(pPager->pVfs, 
44211         pPager->fd, pPager->zWal, pPager->exclusiveMode,
44212         pPager->journalSizeLimit, &pPager->pWal
44213     );
44214   }
44215
44216   return rc;
44217 }
44218
44219
44220 /*
44221 ** The caller must be holding a SHARED lock on the database file to call
44222 ** this function.
44223 **
44224 ** If the pager passed as the first argument is open on a real database
44225 ** file (not a temp file or an in-memory database), and the WAL file
44226 ** is not already open, make an attempt to open it now. If successful,
44227 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
44228 ** not support the xShmXXX() methods, return an error code. *pbOpen is
44229 ** not modified in either case.
44230 **
44231 ** If the pager is open on a temp-file (or in-memory database), or if
44232 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
44233 ** without doing anything.
44234 */
44235 SQLITE_PRIVATE int sqlite3PagerOpenWal(
44236   Pager *pPager,                  /* Pager object */
44237   int *pbOpen                     /* OUT: Set to true if call is a no-op */
44238 ){
44239   int rc = SQLITE_OK;             /* Return code */
44240
44241   assert( assert_pager_state(pPager) );
44242   assert( pPager->eState==PAGER_OPEN   || pbOpen );
44243   assert( pPager->eState==PAGER_READER || !pbOpen );
44244   assert( pbOpen==0 || *pbOpen==0 );
44245   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
44246
44247   if( !pPager->tempFile && !pPager->pWal ){
44248     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
44249
44250     /* Close any rollback journal previously open */
44251     sqlite3OsClose(pPager->jfd);
44252
44253     rc = pagerOpenWal(pPager);
44254     if( rc==SQLITE_OK ){
44255       pPager->journalMode = PAGER_JOURNALMODE_WAL;
44256       pPager->eState = PAGER_OPEN;
44257     }
44258   }else{
44259     *pbOpen = 1;
44260   }
44261
44262   return rc;
44263 }
44264
44265 /*
44266 ** This function is called to close the connection to the log file prior
44267 ** to switching from WAL to rollback mode.
44268 **
44269 ** Before closing the log file, this function attempts to take an 
44270 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
44271 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
44272 ** If successful, the EXCLUSIVE lock is not released before returning.
44273 */
44274 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
44275   int rc = SQLITE_OK;
44276
44277   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
44278
44279   /* If the log file is not already open, but does exist in the file-system,
44280   ** it may need to be checkpointed before the connection can switch to
44281   ** rollback mode. Open it now so this can happen.
44282   */
44283   if( !pPager->pWal ){
44284     int logexists = 0;
44285     rc = pagerLockDb(pPager, SHARED_LOCK);
44286     if( rc==SQLITE_OK ){
44287       rc = sqlite3OsAccess(
44288           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
44289       );
44290     }
44291     if( rc==SQLITE_OK && logexists ){
44292       rc = pagerOpenWal(pPager);
44293     }
44294   }
44295     
44296   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
44297   ** the database file, the log and log-summary files will be deleted.
44298   */
44299   if( rc==SQLITE_OK && pPager->pWal ){
44300     rc = pagerExclusiveLock(pPager);
44301     if( rc==SQLITE_OK ){
44302       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
44303                            pPager->pageSize, (u8*)pPager->pTmpSpace);
44304       pPager->pWal = 0;
44305     }
44306   }
44307   return rc;
44308 }
44309
44310 #endif /* !SQLITE_OMIT_WAL */
44311
44312 #ifdef SQLITE_ENABLE_ZIPVFS
44313 /*
44314 ** A read-lock must be held on the pager when this function is called. If
44315 ** the pager is in WAL mode and the WAL file currently contains one or more
44316 ** frames, return the size in bytes of the page images stored within the
44317 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
44318 ** is empty, return 0.
44319 */
44320 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
44321   assert( pPager->eState==PAGER_READER );
44322   return sqlite3WalFramesize(pPager->pWal);
44323 }
44324 #endif
44325
44326 #ifdef SQLITE_HAS_CODEC
44327 /*
44328 ** This function is called by the wal module when writing page content
44329 ** into the log file.
44330 **
44331 ** This function returns a pointer to a buffer containing the encrypted
44332 ** page content. If a malloc fails, this function may return NULL.
44333 */
44334 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
44335   void *aData = 0;
44336   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
44337   return aData;
44338 }
44339 #endif /* SQLITE_HAS_CODEC */
44340
44341 #endif /* SQLITE_OMIT_DISKIO */
44342
44343 /************** End of pager.c ***********************************************/
44344 /************** Begin file wal.c *********************************************/
44345 /*
44346 ** 2010 February 1
44347 **
44348 ** The author disclaims copyright to this source code.  In place of
44349 ** a legal notice, here is a blessing:
44350 **
44351 **    May you do good and not evil.
44352 **    May you find forgiveness for yourself and forgive others.
44353 **    May you share freely, never taking more than you give.
44354 **
44355 *************************************************************************
44356 **
44357 ** This file contains the implementation of a write-ahead log (WAL) used in 
44358 ** "journal_mode=WAL" mode.
44359 **
44360 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
44361 **
44362 ** A WAL file consists of a header followed by zero or more "frames".
44363 ** Each frame records the revised content of a single page from the
44364 ** database file.  All changes to the database are recorded by writing
44365 ** frames into the WAL.  Transactions commit when a frame is written that
44366 ** contains a commit marker.  A single WAL can and usually does record 
44367 ** multiple transactions.  Periodically, the content of the WAL is
44368 ** transferred back into the database file in an operation called a
44369 ** "checkpoint".
44370 **
44371 ** A single WAL file can be used multiple times.  In other words, the
44372 ** WAL can fill up with frames and then be checkpointed and then new
44373 ** frames can overwrite the old ones.  A WAL always grows from beginning
44374 ** toward the end.  Checksums and counters attached to each frame are
44375 ** used to determine which frames within the WAL are valid and which
44376 ** are leftovers from prior checkpoints.
44377 **
44378 ** The WAL header is 32 bytes in size and consists of the following eight
44379 ** big-endian 32-bit unsigned integer values:
44380 **
44381 **     0: Magic number.  0x377f0682 or 0x377f0683
44382 **     4: File format version.  Currently 3007000
44383 **     8: Database page size.  Example: 1024
44384 **    12: Checkpoint sequence number
44385 **    16: Salt-1, random integer incremented with each checkpoint
44386 **    20: Salt-2, a different random integer changing with each ckpt
44387 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
44388 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
44389 **
44390 ** Immediately following the wal-header are zero or more frames. Each
44391 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
44392 ** of page data. The frame-header is six big-endian 32-bit unsigned 
44393 ** integer values, as follows:
44394 **
44395 **     0: Page number.
44396 **     4: For commit records, the size of the database image in pages 
44397 **        after the commit. For all other records, zero.
44398 **     8: Salt-1 (copied from the header)
44399 **    12: Salt-2 (copied from the header)
44400 **    16: Checksum-1.
44401 **    20: Checksum-2.
44402 **
44403 ** A frame is considered valid if and only if the following conditions are
44404 ** true:
44405 **
44406 **    (1) The salt-1 and salt-2 values in the frame-header match
44407 **        salt values in the wal-header
44408 **
44409 **    (2) The checksum values in the final 8 bytes of the frame-header
44410 **        exactly match the checksum computed consecutively on the
44411 **        WAL header and the first 8 bytes and the content of all frames
44412 **        up to and including the current frame.
44413 **
44414 ** The checksum is computed using 32-bit big-endian integers if the
44415 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
44416 ** is computed using little-endian if the magic number is 0x377f0682.
44417 ** The checksum values are always stored in the frame header in a
44418 ** big-endian format regardless of which byte order is used to compute
44419 ** the checksum.  The checksum is computed by interpreting the input as
44420 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
44421 ** algorithm used for the checksum is as follows:
44422 ** 
44423 **   for i from 0 to n-1 step 2:
44424 **     s0 += x[i] + s1;
44425 **     s1 += x[i+1] + s0;
44426 **   endfor
44427 **
44428 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
44429 ** in reverse order (the largest fibonacci weight occurs on the first element
44430 ** of the sequence being summed.)  The s1 value spans all 32-bit 
44431 ** terms of the sequence whereas s0 omits the final term.
44432 **
44433 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
44434 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
44435 ** The VFS.xSync operations serve as write barriers - all writes launched
44436 ** before the xSync must complete before any write that launches after the
44437 ** xSync begins.
44438 **
44439 ** After each checkpoint, the salt-1 value is incremented and the salt-2
44440 ** value is randomized.  This prevents old and new frames in the WAL from
44441 ** being considered valid at the same time and being checkpointing together
44442 ** following a crash.
44443 **
44444 ** READER ALGORITHM
44445 **
44446 ** To read a page from the database (call it page number P), a reader
44447 ** first checks the WAL to see if it contains page P.  If so, then the
44448 ** last valid instance of page P that is a followed by a commit frame
44449 ** or is a commit frame itself becomes the value read.  If the WAL
44450 ** contains no copies of page P that are valid and which are a commit
44451 ** frame or are followed by a commit frame, then page P is read from
44452 ** the database file.
44453 **
44454 ** To start a read transaction, the reader records the index of the last
44455 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
44456 ** for all subsequent read operations.  New transactions can be appended
44457 ** to the WAL, but as long as the reader uses its original mxFrame value
44458 ** and ignores the newly appended content, it will see a consistent snapshot
44459 ** of the database from a single point in time.  This technique allows
44460 ** multiple concurrent readers to view different versions of the database
44461 ** content simultaneously.
44462 **
44463 ** The reader algorithm in the previous paragraphs works correctly, but 
44464 ** because frames for page P can appear anywhere within the WAL, the
44465 ** reader has to scan the entire WAL looking for page P frames.  If the
44466 ** WAL is large (multiple megabytes is typical) that scan can be slow,
44467 ** and read performance suffers.  To overcome this problem, a separate
44468 ** data structure called the wal-index is maintained to expedite the
44469 ** search for frames of a particular page.
44470 ** 
44471 ** WAL-INDEX FORMAT
44472 **
44473 ** Conceptually, the wal-index is shared memory, though VFS implementations
44474 ** might choose to implement the wal-index using a mmapped file.  Because
44475 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
44476 ** on a network filesystem.  All users of the database must be able to
44477 ** share memory.
44478 **
44479 ** The wal-index is transient.  After a crash, the wal-index can (and should
44480 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
44481 ** to either truncate or zero the header of the wal-index when the last
44482 ** connection to it closes.  Because the wal-index is transient, it can
44483 ** use an architecture-specific format; it does not have to be cross-platform.
44484 ** Hence, unlike the database and WAL file formats which store all values
44485 ** as big endian, the wal-index can store multi-byte values in the native
44486 ** byte order of the host computer.
44487 **
44488 ** The purpose of the wal-index is to answer this question quickly:  Given
44489 ** a page number P and a maximum frame index M, return the index of the 
44490 ** last frame in the wal before frame M for page P in the WAL, or return
44491 ** NULL if there are no frames for page P in the WAL prior to M.
44492 **
44493 ** The wal-index consists of a header region, followed by an one or
44494 ** more index blocks.  
44495 **
44496 ** The wal-index header contains the total number of frames within the WAL
44497 ** in the mxFrame field.
44498 **
44499 ** Each index block except for the first contains information on 
44500 ** HASHTABLE_NPAGE frames. The first index block contains information on
44501 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
44502 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
44503 ** first index block are the same size as all other index blocks in the
44504 ** wal-index.
44505 **
44506 ** Each index block contains two sections, a page-mapping that contains the
44507 ** database page number associated with each wal frame, and a hash-table 
44508 ** that allows readers to query an index block for a specific page number.
44509 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
44510 ** for the first index block) 32-bit page numbers. The first entry in the 
44511 ** first index-block contains the database page number corresponding to the
44512 ** first frame in the WAL file. The first entry in the second index block
44513 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
44514 ** the log, and so on.
44515 **
44516 ** The last index block in a wal-index usually contains less than the full
44517 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
44518 ** depending on the contents of the WAL file. This does not change the
44519 ** allocated size of the page-mapping array - the page-mapping array merely
44520 ** contains unused entries.
44521 **
44522 ** Even without using the hash table, the last frame for page P
44523 ** can be found by scanning the page-mapping sections of each index block
44524 ** starting with the last index block and moving toward the first, and
44525 ** within each index block, starting at the end and moving toward the
44526 ** beginning.  The first entry that equals P corresponds to the frame
44527 ** holding the content for that page.
44528 **
44529 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
44530 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
44531 ** hash table for each page number in the mapping section, so the hash 
44532 ** table is never more than half full.  The expected number of collisions 
44533 ** prior to finding a match is 1.  Each entry of the hash table is an
44534 ** 1-based index of an entry in the mapping section of the same
44535 ** index block.   Let K be the 1-based index of the largest entry in
44536 ** the mapping section.  (For index blocks other than the last, K will
44537 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
44538 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
44539 ** contain a value of 0.
44540 **
44541 ** To look for page P in the hash table, first compute a hash iKey on
44542 ** P as follows:
44543 **
44544 **      iKey = (P * 383) % HASHTABLE_NSLOT
44545 **
44546 ** Then start scanning entries of the hash table, starting with iKey
44547 ** (wrapping around to the beginning when the end of the hash table is
44548 ** reached) until an unused hash slot is found. Let the first unused slot
44549 ** be at index iUnused.  (iUnused might be less than iKey if there was
44550 ** wrap-around.) Because the hash table is never more than half full,
44551 ** the search is guaranteed to eventually hit an unused entry.  Let 
44552 ** iMax be the value between iKey and iUnused, closest to iUnused,
44553 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
44554 ** no hash slot such that aHash[i]==p) then page P is not in the
44555 ** current index block.  Otherwise the iMax-th mapping entry of the
44556 ** current index block corresponds to the last entry that references 
44557 ** page P.
44558 **
44559 ** A hash search begins with the last index block and moves toward the
44560 ** first index block, looking for entries corresponding to page P.  On
44561 ** average, only two or three slots in each index block need to be
44562 ** examined in order to either find the last entry for page P, or to
44563 ** establish that no such entry exists in the block.  Each index block
44564 ** holds over 4000 entries.  So two or three index blocks are sufficient
44565 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
44566 ** comparisons (on average) suffice to either locate a frame in the
44567 ** WAL or to establish that the frame does not exist in the WAL.  This
44568 ** is much faster than scanning the entire 10MB WAL.
44569 **
44570 ** Note that entries are added in order of increasing K.  Hence, one
44571 ** reader might be using some value K0 and a second reader that started
44572 ** at a later time (after additional transactions were added to the WAL
44573 ** and to the wal-index) might be using a different value K1, where K1>K0.
44574 ** Both readers can use the same hash table and mapping section to get
44575 ** the correct result.  There may be entries in the hash table with
44576 ** K>K0 but to the first reader, those entries will appear to be unused
44577 ** slots in the hash table and so the first reader will get an answer as
44578 ** if no values greater than K0 had ever been inserted into the hash table
44579 ** in the first place - which is what reader one wants.  Meanwhile, the
44580 ** second reader using K1 will see additional values that were inserted
44581 ** later, which is exactly what reader two wants.  
44582 **
44583 ** When a rollback occurs, the value of K is decreased. Hash table entries
44584 ** that correspond to frames greater than the new K value are removed
44585 ** from the hash table at this point.
44586 */
44587 #ifndef SQLITE_OMIT_WAL
44588
44589
44590 /*
44591 ** Trace output macros
44592 */
44593 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44594 SQLITE_PRIVATE int sqlite3WalTrace = 0;
44595 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
44596 #else
44597 # define WALTRACE(X)
44598 #endif
44599
44600 /*
44601 ** The maximum (and only) versions of the wal and wal-index formats
44602 ** that may be interpreted by this version of SQLite.
44603 **
44604 ** If a client begins recovering a WAL file and finds that (a) the checksum
44605 ** values in the wal-header are correct and (b) the version field is not
44606 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
44607 **
44608 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
44609 ** checksum test is successful) and finds that the version field is not
44610 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
44611 ** returns SQLITE_CANTOPEN.
44612 */
44613 #define WAL_MAX_VERSION      3007000
44614 #define WALINDEX_MAX_VERSION 3007000
44615
44616 /*
44617 ** Indices of various locking bytes.   WAL_NREADER is the number
44618 ** of available reader locks and should be at least 3.
44619 */
44620 #define WAL_WRITE_LOCK         0
44621 #define WAL_ALL_BUT_WRITE      1
44622 #define WAL_CKPT_LOCK          1
44623 #define WAL_RECOVER_LOCK       2
44624 #define WAL_READ_LOCK(I)       (3+(I))
44625 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
44626
44627
44628 /* Object declarations */
44629 typedef struct WalIndexHdr WalIndexHdr;
44630 typedef struct WalIterator WalIterator;
44631 typedef struct WalCkptInfo WalCkptInfo;
44632
44633
44634 /*
44635 ** The following object holds a copy of the wal-index header content.
44636 **
44637 ** The actual header in the wal-index consists of two copies of this
44638 ** object.
44639 **
44640 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
44641 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
44642 ** added in 3.7.1 when support for 64K pages was added.  
44643 */
44644 struct WalIndexHdr {
44645   u32 iVersion;                   /* Wal-index version */
44646   u32 unused;                     /* Unused (padding) field */
44647   u32 iChange;                    /* Counter incremented each transaction */
44648   u8 isInit;                      /* 1 when initialized */
44649   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
44650   u16 szPage;                     /* Database page size in bytes. 1==64K */
44651   u32 mxFrame;                    /* Index of last valid frame in the WAL */
44652   u32 nPage;                      /* Size of database in pages */
44653   u32 aFrameCksum[2];             /* Checksum of last frame in log */
44654   u32 aSalt[2];                   /* Two salt values copied from WAL header */
44655   u32 aCksum[2];                  /* Checksum over all prior fields */
44656 };
44657
44658 /*
44659 ** A copy of the following object occurs in the wal-index immediately
44660 ** following the second copy of the WalIndexHdr.  This object stores
44661 ** information used by checkpoint.
44662 **
44663 ** nBackfill is the number of frames in the WAL that have been written
44664 ** back into the database. (We call the act of moving content from WAL to
44665 ** database "backfilling".)  The nBackfill number is never greater than
44666 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
44667 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
44668 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
44669 ** mxFrame back to zero when the WAL is reset.
44670 **
44671 ** There is one entry in aReadMark[] for each reader lock.  If a reader
44672 ** holds read-lock K, then the value in aReadMark[K] is no greater than
44673 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
44674 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
44675 ** a special case; its value is never used and it exists as a place-holder
44676 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
44677 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
44678 ** directly from the database.
44679 **
44680 ** The value of aReadMark[K] may only be changed by a thread that
44681 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
44682 ** aReadMark[K] cannot changed while there is a reader is using that mark
44683 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
44684 **
44685 ** The checkpointer may only transfer frames from WAL to database where
44686 ** the frame numbers are less than or equal to every aReadMark[] that is
44687 ** in use (that is, every aReadMark[j] for which there is a corresponding
44688 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
44689 ** largest value and will increase an unused aReadMark[] to mxFrame if there
44690 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
44691 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
44692 ** in the WAL has been backfilled into the database) then new readers
44693 ** will choose aReadMark[0] which has value 0 and hence such reader will
44694 ** get all their all content directly from the database file and ignore 
44695 ** the WAL.
44696 **
44697 ** Writers normally append new frames to the end of the WAL.  However,
44698 ** if nBackfill equals mxFrame (meaning that all WAL content has been
44699 ** written back into the database) and if no readers are using the WAL
44700 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
44701 ** the writer will first "reset" the WAL back to the beginning and start
44702 ** writing new content beginning at frame 1.
44703 **
44704 ** We assume that 32-bit loads are atomic and so no locks are needed in
44705 ** order to read from any aReadMark[] entries.
44706 */
44707 struct WalCkptInfo {
44708   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
44709   u32 aReadMark[WAL_NREADER];     /* Reader marks */
44710 };
44711 #define READMARK_NOT_USED  0xffffffff
44712
44713
44714 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
44715 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
44716 ** only support mandatory file-locks, we do not read or write data
44717 ** from the region of the file on which locks are applied.
44718 */
44719 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
44720 #define WALINDEX_LOCK_RESERVED 16
44721 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
44722
44723 /* Size of header before each frame in wal */
44724 #define WAL_FRAME_HDRSIZE 24
44725
44726 /* Size of write ahead log header, including checksum. */
44727 /* #define WAL_HDRSIZE 24 */
44728 #define WAL_HDRSIZE 32
44729
44730 /* WAL magic value. Either this value, or the same value with the least
44731 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
44732 ** big-endian format in the first 4 bytes of a WAL file.
44733 **
44734 ** If the LSB is set, then the checksums for each frame within the WAL
44735 ** file are calculated by treating all data as an array of 32-bit 
44736 ** big-endian words. Otherwise, they are calculated by interpreting 
44737 ** all data as 32-bit little-endian words.
44738 */
44739 #define WAL_MAGIC 0x377f0682
44740
44741 /*
44742 ** Return the offset of frame iFrame in the write-ahead log file, 
44743 ** assuming a database page size of szPage bytes. The offset returned
44744 ** is to the start of the write-ahead log frame-header.
44745 */
44746 #define walFrameOffset(iFrame, szPage) (                               \
44747   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
44748 )
44749
44750 /*
44751 ** An open write-ahead log file is represented by an instance of the
44752 ** following object.
44753 */
44754 struct Wal {
44755   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
44756   sqlite3_file *pDbFd;       /* File handle for the database file */
44757   sqlite3_file *pWalFd;      /* File handle for WAL file */
44758   u32 iCallback;             /* Value to pass to log callback (or 0) */
44759   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
44760   int nWiData;               /* Size of array apWiData */
44761   int szFirstBlock;          /* Size of first block written to WAL file */
44762   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
44763   u32 szPage;                /* Database page size */
44764   i16 readLock;              /* Which read lock is being held.  -1 for none */
44765   u8 syncFlags;              /* Flags to use to sync header writes */
44766   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
44767   u8 writeLock;              /* True if in a write transaction */
44768   u8 ckptLock;               /* True if holding a checkpoint lock */
44769   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
44770   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
44771   u8 syncHeader;             /* Fsync the WAL header if true */
44772   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
44773   WalIndexHdr hdr;           /* Wal-index header for current transaction */
44774   const char *zWalName;      /* Name of WAL file */
44775   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
44776 #ifdef SQLITE_DEBUG
44777   u8 lockError;              /* True if a locking error has occurred */
44778 #endif
44779 };
44780
44781 /*
44782 ** Candidate values for Wal.exclusiveMode.
44783 */
44784 #define WAL_NORMAL_MODE     0
44785 #define WAL_EXCLUSIVE_MODE  1     
44786 #define WAL_HEAPMEMORY_MODE 2
44787
44788 /*
44789 ** Possible values for WAL.readOnly
44790 */
44791 #define WAL_RDWR        0    /* Normal read/write connection */
44792 #define WAL_RDONLY      1    /* The WAL file is readonly */
44793 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
44794
44795 /*
44796 ** Each page of the wal-index mapping contains a hash-table made up of
44797 ** an array of HASHTABLE_NSLOT elements of the following type.
44798 */
44799 typedef u16 ht_slot;
44800
44801 /*
44802 ** This structure is used to implement an iterator that loops through
44803 ** all frames in the WAL in database page order. Where two or more frames
44804 ** correspond to the same database page, the iterator visits only the 
44805 ** frame most recently written to the WAL (in other words, the frame with
44806 ** the largest index).
44807 **
44808 ** The internals of this structure are only accessed by:
44809 **
44810 **   walIteratorInit() - Create a new iterator,
44811 **   walIteratorNext() - Step an iterator,
44812 **   walIteratorFree() - Free an iterator.
44813 **
44814 ** This functionality is used by the checkpoint code (see walCheckpoint()).
44815 */
44816 struct WalIterator {
44817   int iPrior;                     /* Last result returned from the iterator */
44818   int nSegment;                   /* Number of entries in aSegment[] */
44819   struct WalSegment {
44820     int iNext;                    /* Next slot in aIndex[] not yet returned */
44821     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
44822     u32 *aPgno;                   /* Array of page numbers. */
44823     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
44824     int iZero;                    /* Frame number associated with aPgno[0] */
44825   } aSegment[1];                  /* One for every 32KB page in the wal-index */
44826 };
44827
44828 /*
44829 ** Define the parameters of the hash tables in the wal-index file. There
44830 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
44831 ** wal-index.
44832 **
44833 ** Changing any of these constants will alter the wal-index format and
44834 ** create incompatibilities.
44835 */
44836 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
44837 #define HASHTABLE_HASH_1     383                  /* Should be prime */
44838 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
44839
44840 /* 
44841 ** The block of page numbers associated with the first hash-table in a
44842 ** wal-index is smaller than usual. This is so that there is a complete
44843 ** hash-table on each aligned 32KB page of the wal-index.
44844 */
44845 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
44846
44847 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
44848 #define WALINDEX_PGSZ   (                                         \
44849     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
44850 )
44851
44852 /*
44853 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
44854 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
44855 ** numbered from zero.
44856 **
44857 ** If this call is successful, *ppPage is set to point to the wal-index
44858 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
44859 ** then an SQLite error code is returned and *ppPage is set to 0.
44860 */
44861 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
44862   int rc = SQLITE_OK;
44863
44864   /* Enlarge the pWal->apWiData[] array if required */
44865   if( pWal->nWiData<=iPage ){
44866     int nByte = sizeof(u32*)*(iPage+1);
44867     volatile u32 **apNew;
44868     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
44869     if( !apNew ){
44870       *ppPage = 0;
44871       return SQLITE_NOMEM;
44872     }
44873     memset((void*)&apNew[pWal->nWiData], 0,
44874            sizeof(u32*)*(iPage+1-pWal->nWiData));
44875     pWal->apWiData = apNew;
44876     pWal->nWiData = iPage+1;
44877   }
44878
44879   /* Request a pointer to the required page from the VFS */
44880   if( pWal->apWiData[iPage]==0 ){
44881     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44882       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
44883       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
44884     }else{
44885       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
44886           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
44887       );
44888       if( rc==SQLITE_READONLY ){
44889         pWal->readOnly |= WAL_SHM_RDONLY;
44890         rc = SQLITE_OK;
44891       }
44892     }
44893   }
44894
44895   *ppPage = pWal->apWiData[iPage];
44896   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
44897   return rc;
44898 }
44899
44900 /*
44901 ** Return a pointer to the WalCkptInfo structure in the wal-index.
44902 */
44903 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
44904   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44905   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
44906 }
44907
44908 /*
44909 ** Return a pointer to the WalIndexHdr structure in the wal-index.
44910 */
44911 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
44912   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44913   return (volatile WalIndexHdr*)pWal->apWiData[0];
44914 }
44915
44916 /*
44917 ** The argument to this macro must be of type u32. On a little-endian
44918 ** architecture, it returns the u32 value that results from interpreting
44919 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
44920 ** returns the value that would be produced by intepreting the 4 bytes
44921 ** of the input value as a little-endian integer.
44922 */
44923 #define BYTESWAP32(x) ( \
44924     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
44925   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
44926 )
44927
44928 /*
44929 ** Generate or extend an 8 byte checksum based on the data in 
44930 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
44931 ** initial values of 0 and 0 if aIn==NULL).
44932 **
44933 ** The checksum is written back into aOut[] before returning.
44934 **
44935 ** nByte must be a positive multiple of 8.
44936 */
44937 static void walChecksumBytes(
44938   int nativeCksum, /* True for native byte-order, false for non-native */
44939   u8 *a,           /* Content to be checksummed */
44940   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
44941   const u32 *aIn,  /* Initial checksum value input */
44942   u32 *aOut        /* OUT: Final checksum value output */
44943 ){
44944   u32 s1, s2;
44945   u32 *aData = (u32 *)a;
44946   u32 *aEnd = (u32 *)&a[nByte];
44947
44948   if( aIn ){
44949     s1 = aIn[0];
44950     s2 = aIn[1];
44951   }else{
44952     s1 = s2 = 0;
44953   }
44954
44955   assert( nByte>=8 );
44956   assert( (nByte&0x00000007)==0 );
44957
44958   if( nativeCksum ){
44959     do {
44960       s1 += *aData++ + s2;
44961       s2 += *aData++ + s1;
44962     }while( aData<aEnd );
44963   }else{
44964     do {
44965       s1 += BYTESWAP32(aData[0]) + s2;
44966       s2 += BYTESWAP32(aData[1]) + s1;
44967       aData += 2;
44968     }while( aData<aEnd );
44969   }
44970
44971   aOut[0] = s1;
44972   aOut[1] = s2;
44973 }
44974
44975 static void walShmBarrier(Wal *pWal){
44976   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
44977     sqlite3OsShmBarrier(pWal->pDbFd);
44978   }
44979 }
44980
44981 /*
44982 ** Write the header information in pWal->hdr into the wal-index.
44983 **
44984 ** The checksum on pWal->hdr is updated before it is written.
44985 */
44986 static void walIndexWriteHdr(Wal *pWal){
44987   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
44988   const int nCksum = offsetof(WalIndexHdr, aCksum);
44989
44990   assert( pWal->writeLock );
44991   pWal->hdr.isInit = 1;
44992   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
44993   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
44994   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44995   walShmBarrier(pWal);
44996   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44997 }
44998
44999 /*
45000 ** This function encodes a single frame header and writes it to a buffer
45001 ** supplied by the caller. A frame-header is made up of a series of 
45002 ** 4-byte big-endian integers, as follows:
45003 **
45004 **     0: Page number.
45005 **     4: For commit records, the size of the database image in pages 
45006 **        after the commit. For all other records, zero.
45007 **     8: Salt-1 (copied from the wal-header)
45008 **    12: Salt-2 (copied from the wal-header)
45009 **    16: Checksum-1.
45010 **    20: Checksum-2.
45011 */
45012 static void walEncodeFrame(
45013   Wal *pWal,                      /* The write-ahead log */
45014   u32 iPage,                      /* Database page number for frame */
45015   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
45016   u8 *aData,                      /* Pointer to page data */
45017   u8 *aFrame                      /* OUT: Write encoded frame here */
45018 ){
45019   int nativeCksum;                /* True for native byte-order checksums */
45020   u32 *aCksum = pWal->hdr.aFrameCksum;
45021   assert( WAL_FRAME_HDRSIZE==24 );
45022   sqlite3Put4byte(&aFrame[0], iPage);
45023   sqlite3Put4byte(&aFrame[4], nTruncate);
45024   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
45025
45026   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
45027   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
45028   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
45029
45030   sqlite3Put4byte(&aFrame[16], aCksum[0]);
45031   sqlite3Put4byte(&aFrame[20], aCksum[1]);
45032 }
45033
45034 /*
45035 ** Check to see if the frame with header in aFrame[] and content
45036 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
45037 ** *pnTruncate and return true.  Return if the frame is not valid.
45038 */
45039 static int walDecodeFrame(
45040   Wal *pWal,                      /* The write-ahead log */
45041   u32 *piPage,                    /* OUT: Database page number for frame */
45042   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
45043   u8 *aData,                      /* Pointer to page data (for checksum) */
45044   u8 *aFrame                      /* Frame data */
45045 ){
45046   int nativeCksum;                /* True for native byte-order checksums */
45047   u32 *aCksum = pWal->hdr.aFrameCksum;
45048   u32 pgno;                       /* Page number of the frame */
45049   assert( WAL_FRAME_HDRSIZE==24 );
45050
45051   /* A frame is only valid if the salt values in the frame-header
45052   ** match the salt values in the wal-header. 
45053   */
45054   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
45055     return 0;
45056   }
45057
45058   /* A frame is only valid if the page number is creater than zero.
45059   */
45060   pgno = sqlite3Get4byte(&aFrame[0]);
45061   if( pgno==0 ){
45062     return 0;
45063   }
45064
45065   /* A frame is only valid if a checksum of the WAL header,
45066   ** all prior frams, the first 16 bytes of this frame-header, 
45067   ** and the frame-data matches the checksum in the last 8 
45068   ** bytes of this frame-header.
45069   */
45070   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
45071   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
45072   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
45073   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
45074    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
45075   ){
45076     /* Checksum failed. */
45077     return 0;
45078   }
45079
45080   /* If we reach this point, the frame is valid.  Return the page number
45081   ** and the new database size.
45082   */
45083   *piPage = pgno;
45084   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
45085   return 1;
45086 }
45087
45088
45089 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45090 /*
45091 ** Names of locks.  This routine is used to provide debugging output and is not
45092 ** a part of an ordinary build.
45093 */
45094 static const char *walLockName(int lockIdx){
45095   if( lockIdx==WAL_WRITE_LOCK ){
45096     return "WRITE-LOCK";
45097   }else if( lockIdx==WAL_CKPT_LOCK ){
45098     return "CKPT-LOCK";
45099   }else if( lockIdx==WAL_RECOVER_LOCK ){
45100     return "RECOVER-LOCK";
45101   }else{
45102     static char zName[15];
45103     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
45104                      lockIdx-WAL_READ_LOCK(0));
45105     return zName;
45106   }
45107 }
45108 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
45109     
45110
45111 /*
45112 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
45113 ** A lock cannot be moved directly between shared and exclusive - it must go
45114 ** through the unlocked state first.
45115 **
45116 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
45117 */
45118 static int walLockShared(Wal *pWal, int lockIdx){
45119   int rc;
45120   if( pWal->exclusiveMode ) return SQLITE_OK;
45121   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
45122                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
45123   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
45124             walLockName(lockIdx), rc ? "failed" : "ok"));
45125   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
45126   return rc;
45127 }
45128 static void walUnlockShared(Wal *pWal, int lockIdx){
45129   if( pWal->exclusiveMode ) return;
45130   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
45131                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
45132   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
45133 }
45134 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
45135   int rc;
45136   if( pWal->exclusiveMode ) return SQLITE_OK;
45137   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
45138                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
45139   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
45140             walLockName(lockIdx), n, rc ? "failed" : "ok"));
45141   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
45142   return rc;
45143 }
45144 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
45145   if( pWal->exclusiveMode ) return;
45146   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
45147                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
45148   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
45149              walLockName(lockIdx), n));
45150 }
45151
45152 /*
45153 ** Compute a hash on a page number.  The resulting hash value must land
45154 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
45155 ** the hash to the next value in the event of a collision.
45156 */
45157 static int walHash(u32 iPage){
45158   assert( iPage>0 );
45159   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
45160   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
45161 }
45162 static int walNextHash(int iPriorHash){
45163   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
45164 }
45165
45166 /* 
45167 ** Return pointers to the hash table and page number array stored on
45168 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
45169 ** numbered starting from 0.
45170 **
45171 ** Set output variable *paHash to point to the start of the hash table
45172 ** in the wal-index file. Set *piZero to one less than the frame 
45173 ** number of the first frame indexed by this hash table. If a
45174 ** slot in the hash table is set to N, it refers to frame number 
45175 ** (*piZero+N) in the log.
45176 **
45177 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
45178 ** first frame indexed by the hash table, frame (*piZero+1).
45179 */
45180 static int walHashGet(
45181   Wal *pWal,                      /* WAL handle */
45182   int iHash,                      /* Find the iHash'th table */
45183   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
45184   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
45185   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
45186 ){
45187   int rc;                         /* Return code */
45188   volatile u32 *aPgno;
45189
45190   rc = walIndexPage(pWal, iHash, &aPgno);
45191   assert( rc==SQLITE_OK || iHash>0 );
45192
45193   if( rc==SQLITE_OK ){
45194     u32 iZero;
45195     volatile ht_slot *aHash;
45196
45197     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
45198     if( iHash==0 ){
45199       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
45200       iZero = 0;
45201     }else{
45202       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
45203     }
45204   
45205     *paPgno = &aPgno[-1];
45206     *paHash = aHash;
45207     *piZero = iZero;
45208   }
45209   return rc;
45210 }
45211
45212 /*
45213 ** Return the number of the wal-index page that contains the hash-table
45214 ** and page-number array that contain entries corresponding to WAL frame
45215 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
45216 ** are numbered starting from 0.
45217 */
45218 static int walFramePage(u32 iFrame){
45219   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
45220   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
45221        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
45222        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
45223        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
45224        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
45225   );
45226   return iHash;
45227 }
45228
45229 /*
45230 ** Return the page number associated with frame iFrame in this WAL.
45231 */
45232 static u32 walFramePgno(Wal *pWal, u32 iFrame){
45233   int iHash = walFramePage(iFrame);
45234   if( iHash==0 ){
45235     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
45236   }
45237   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
45238 }
45239
45240 /*
45241 ** Remove entries from the hash table that point to WAL slots greater
45242 ** than pWal->hdr.mxFrame.
45243 **
45244 ** This function is called whenever pWal->hdr.mxFrame is decreased due
45245 ** to a rollback or savepoint.
45246 **
45247 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
45248 ** updated.  Any later hash tables will be automatically cleared when
45249 ** pWal->hdr.mxFrame advances to the point where those hash tables are
45250 ** actually needed.
45251 */
45252 static void walCleanupHash(Wal *pWal){
45253   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
45254   volatile u32 *aPgno = 0;        /* Page number array for hash table */
45255   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
45256   int iLimit = 0;                 /* Zero values greater than this */
45257   int nByte;                      /* Number of bytes to zero in aPgno[] */
45258   int i;                          /* Used to iterate through aHash[] */
45259
45260   assert( pWal->writeLock );
45261   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
45262   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
45263   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
45264
45265   if( pWal->hdr.mxFrame==0 ) return;
45266
45267   /* Obtain pointers to the hash-table and page-number array containing 
45268   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
45269   ** that the page said hash-table and array reside on is already mapped.
45270   */
45271   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
45272   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
45273   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
45274
45275   /* Zero all hash-table entries that correspond to frame numbers greater
45276   ** than pWal->hdr.mxFrame.
45277   */
45278   iLimit = pWal->hdr.mxFrame - iZero;
45279   assert( iLimit>0 );
45280   for(i=0; i<HASHTABLE_NSLOT; i++){
45281     if( aHash[i]>iLimit ){
45282       aHash[i] = 0;
45283     }
45284   }
45285   
45286   /* Zero the entries in the aPgno array that correspond to frames with
45287   ** frame numbers greater than pWal->hdr.mxFrame. 
45288   */
45289   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
45290   memset((void *)&aPgno[iLimit+1], 0, nByte);
45291
45292 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45293   /* Verify that the every entry in the mapping region is still reachable
45294   ** via the hash table even after the cleanup.
45295   */
45296   if( iLimit ){
45297     int i;           /* Loop counter */
45298     int iKey;        /* Hash key */
45299     for(i=1; i<=iLimit; i++){
45300       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
45301         if( aHash[iKey]==i ) break;
45302       }
45303       assert( aHash[iKey]==i );
45304     }
45305   }
45306 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
45307 }
45308
45309
45310 /*
45311 ** Set an entry in the wal-index that will map database page number
45312 ** pPage into WAL frame iFrame.
45313 */
45314 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
45315   int rc;                         /* Return code */
45316   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
45317   volatile u32 *aPgno = 0;        /* Page number array */
45318   volatile ht_slot *aHash = 0;    /* Hash table */
45319
45320   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
45321
45322   /* Assuming the wal-index file was successfully mapped, populate the
45323   ** page number array and hash table entry.
45324   */
45325   if( rc==SQLITE_OK ){
45326     int iKey;                     /* Hash table key */
45327     int idx;                      /* Value to write to hash-table slot */
45328     int nCollide;                 /* Number of hash collisions */
45329
45330     idx = iFrame - iZero;
45331     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
45332     
45333     /* If this is the first entry to be added to this hash-table, zero the
45334     ** entire hash table and aPgno[] array before proceding. 
45335     */
45336     if( idx==1 ){
45337       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
45338       memset((void*)&aPgno[1], 0, nByte);
45339     }
45340
45341     /* If the entry in aPgno[] is already set, then the previous writer
45342     ** must have exited unexpectedly in the middle of a transaction (after
45343     ** writing one or more dirty pages to the WAL to free up memory). 
45344     ** Remove the remnants of that writers uncommitted transaction from 
45345     ** the hash-table before writing any new entries.
45346     */
45347     if( aPgno[idx] ){
45348       walCleanupHash(pWal);
45349       assert( !aPgno[idx] );
45350     }
45351
45352     /* Write the aPgno[] array entry and the hash-table slot. */
45353     nCollide = idx;
45354     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
45355       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
45356     }
45357     aPgno[idx] = iPage;
45358     aHash[iKey] = (ht_slot)idx;
45359
45360 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45361     /* Verify that the number of entries in the hash table exactly equals
45362     ** the number of entries in the mapping region.
45363     */
45364     {
45365       int i;           /* Loop counter */
45366       int nEntry = 0;  /* Number of entries in the hash table */
45367       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
45368       assert( nEntry==idx );
45369     }
45370
45371     /* Verify that the every entry in the mapping region is reachable
45372     ** via the hash table.  This turns out to be a really, really expensive
45373     ** thing to check, so only do this occasionally - not on every
45374     ** iteration.
45375     */
45376     if( (idx&0x3ff)==0 ){
45377       int i;           /* Loop counter */
45378       for(i=1; i<=idx; i++){
45379         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
45380           if( aHash[iKey]==i ) break;
45381         }
45382         assert( aHash[iKey]==i );
45383       }
45384     }
45385 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
45386   }
45387
45388
45389   return rc;
45390 }
45391
45392
45393 /*
45394 ** Recover the wal-index by reading the write-ahead log file. 
45395 **
45396 ** This routine first tries to establish an exclusive lock on the
45397 ** wal-index to prevent other threads/processes from doing anything
45398 ** with the WAL or wal-index while recovery is running.  The
45399 ** WAL_RECOVER_LOCK is also held so that other threads will know
45400 ** that this thread is running recovery.  If unable to establish
45401 ** the necessary locks, this routine returns SQLITE_BUSY.
45402 */
45403 static int walIndexRecover(Wal *pWal){
45404   int rc;                         /* Return Code */
45405   i64 nSize;                      /* Size of log file */
45406   u32 aFrameCksum[2] = {0, 0};
45407   int iLock;                      /* Lock offset to lock for checkpoint */
45408   int nLock;                      /* Number of locks to hold */
45409
45410   /* Obtain an exclusive lock on all byte in the locking range not already
45411   ** locked by the caller. The caller is guaranteed to have locked the
45412   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
45413   ** If successful, the same bytes that are locked here are unlocked before
45414   ** this function returns.
45415   */
45416   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
45417   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
45418   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
45419   assert( pWal->writeLock );
45420   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
45421   nLock = SQLITE_SHM_NLOCK - iLock;
45422   rc = walLockExclusive(pWal, iLock, nLock);
45423   if( rc ){
45424     return rc;
45425   }
45426   WALTRACE(("WAL%p: recovery begin...\n", pWal));
45427
45428   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
45429
45430   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
45431   if( rc!=SQLITE_OK ){
45432     goto recovery_error;
45433   }
45434
45435   if( nSize>WAL_HDRSIZE ){
45436     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
45437     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
45438     int szFrame;                  /* Number of bytes in buffer aFrame[] */
45439     u8 *aData;                    /* Pointer to data part of aFrame buffer */
45440     int iFrame;                   /* Index of last frame read */
45441     i64 iOffset;                  /* Next offset to read from log file */
45442     int szPage;                   /* Page size according to the log */
45443     u32 magic;                    /* Magic value read from WAL header */
45444     u32 version;                  /* Magic value read from WAL header */
45445     int isValid;                  /* True if this frame is valid */
45446
45447     /* Read in the WAL header. */
45448     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
45449     if( rc!=SQLITE_OK ){
45450       goto recovery_error;
45451     }
45452
45453     /* If the database page size is not a power of two, or is greater than
45454     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
45455     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
45456     ** WAL file.
45457     */
45458     magic = sqlite3Get4byte(&aBuf[0]);
45459     szPage = sqlite3Get4byte(&aBuf[8]);
45460     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
45461      || szPage&(szPage-1) 
45462      || szPage>SQLITE_MAX_PAGE_SIZE 
45463      || szPage<512 
45464     ){
45465       goto finished;
45466     }
45467     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
45468     pWal->szPage = szPage;
45469     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
45470     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
45471
45472     /* Verify that the WAL header checksum is correct */
45473     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
45474         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
45475     );
45476     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
45477      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
45478     ){
45479       goto finished;
45480     }
45481
45482     /* Verify that the version number on the WAL format is one that
45483     ** are able to understand */
45484     version = sqlite3Get4byte(&aBuf[4]);
45485     if( version!=WAL_MAX_VERSION ){
45486       rc = SQLITE_CANTOPEN_BKPT;
45487       goto finished;
45488     }
45489
45490     /* Malloc a buffer to read frames into. */
45491     szFrame = szPage + WAL_FRAME_HDRSIZE;
45492     aFrame = (u8 *)sqlite3_malloc(szFrame);
45493     if( !aFrame ){
45494       rc = SQLITE_NOMEM;
45495       goto recovery_error;
45496     }
45497     aData = &aFrame[WAL_FRAME_HDRSIZE];
45498
45499     /* Read all frames from the log file. */
45500     iFrame = 0;
45501     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
45502       u32 pgno;                   /* Database page number for frame */
45503       u32 nTruncate;              /* dbsize field from frame header */
45504
45505       /* Read and decode the next log frame. */
45506       iFrame++;
45507       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
45508       if( rc!=SQLITE_OK ) break;
45509       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
45510       if( !isValid ) break;
45511       rc = walIndexAppend(pWal, iFrame, pgno);
45512       if( rc!=SQLITE_OK ) break;
45513
45514       /* If nTruncate is non-zero, this is a commit record. */
45515       if( nTruncate ){
45516         pWal->hdr.mxFrame = iFrame;
45517         pWal->hdr.nPage = nTruncate;
45518         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
45519         testcase( szPage<=32768 );
45520         testcase( szPage>=65536 );
45521         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
45522         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
45523       }
45524     }
45525
45526     sqlite3_free(aFrame);
45527   }
45528
45529 finished:
45530   if( rc==SQLITE_OK ){
45531     volatile WalCkptInfo *pInfo;
45532     int i;
45533     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
45534     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
45535     walIndexWriteHdr(pWal);
45536
45537     /* Reset the checkpoint-header. This is safe because this thread is 
45538     ** currently holding locks that exclude all other readers, writers and
45539     ** checkpointers.
45540     */
45541     pInfo = walCkptInfo(pWal);
45542     pInfo->nBackfill = 0;
45543     pInfo->aReadMark[0] = 0;
45544     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
45545     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
45546
45547     /* If more than one frame was recovered from the log file, report an
45548     ** event via sqlite3_log(). This is to help with identifying performance
45549     ** problems caused by applications routinely shutting down without
45550     ** checkpointing the log file.
45551     */
45552     if( pWal->hdr.nPage ){
45553       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
45554           pWal->hdr.nPage, pWal->zWalName
45555       );
45556     }
45557   }
45558
45559 recovery_error:
45560   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
45561   walUnlockExclusive(pWal, iLock, nLock);
45562   return rc;
45563 }
45564
45565 /*
45566 ** Close an open wal-index.
45567 */
45568 static void walIndexClose(Wal *pWal, int isDelete){
45569   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
45570     int i;
45571     for(i=0; i<pWal->nWiData; i++){
45572       sqlite3_free((void *)pWal->apWiData[i]);
45573       pWal->apWiData[i] = 0;
45574     }
45575   }else{
45576     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
45577   }
45578 }
45579
45580 /* 
45581 ** Open a connection to the WAL file zWalName. The database file must 
45582 ** already be opened on connection pDbFd. The buffer that zWalName points
45583 ** to must remain valid for the lifetime of the returned Wal* handle.
45584 **
45585 ** A SHARED lock should be held on the database file when this function
45586 ** is called. The purpose of this SHARED lock is to prevent any other
45587 ** client from unlinking the WAL or wal-index file. If another process
45588 ** were to do this just after this client opened one of these files, the
45589 ** system would be badly broken.
45590 **
45591 ** If the log file is successfully opened, SQLITE_OK is returned and 
45592 ** *ppWal is set to point to a new WAL handle. If an error occurs,
45593 ** an SQLite error code is returned and *ppWal is left unmodified.
45594 */
45595 SQLITE_PRIVATE int sqlite3WalOpen(
45596   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
45597   sqlite3_file *pDbFd,            /* The open database file */
45598   const char *zWalName,           /* Name of the WAL file */
45599   int bNoShm,                     /* True to run in heap-memory mode */
45600   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
45601   Wal **ppWal                     /* OUT: Allocated Wal handle */
45602 ){
45603   int rc;                         /* Return Code */
45604   Wal *pRet;                      /* Object to allocate and return */
45605   int flags;                      /* Flags passed to OsOpen() */
45606
45607   assert( zWalName && zWalName[0] );
45608   assert( pDbFd );
45609
45610   /* In the amalgamation, the os_unix.c and os_win.c source files come before
45611   ** this source file.  Verify that the #defines of the locking byte offsets
45612   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
45613   */
45614 #ifdef WIN_SHM_BASE
45615   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
45616 #endif
45617 #ifdef UNIX_SHM_BASE
45618   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
45619 #endif
45620
45621
45622   /* Allocate an instance of struct Wal to return. */
45623   *ppWal = 0;
45624   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
45625   if( !pRet ){
45626     return SQLITE_NOMEM;
45627   }
45628
45629   pRet->pVfs = pVfs;
45630   pRet->pWalFd = (sqlite3_file *)&pRet[1];
45631   pRet->pDbFd = pDbFd;
45632   pRet->readLock = -1;
45633   pRet->mxWalSize = mxWalSize;
45634   pRet->zWalName = zWalName;
45635   pRet->syncHeader = 1;
45636   pRet->padToSectorBoundary = 1;
45637   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
45638
45639   /* Open file handle on the write-ahead log file. */
45640   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
45641   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
45642   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
45643     pRet->readOnly = WAL_RDONLY;
45644   }
45645
45646   if( rc!=SQLITE_OK ){
45647     walIndexClose(pRet, 0);
45648     sqlite3OsClose(pRet->pWalFd);
45649     sqlite3_free(pRet);
45650   }else{
45651     int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
45652     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
45653     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
45654       pRet->padToSectorBoundary = 0;
45655     }
45656     *ppWal = pRet;
45657     WALTRACE(("WAL%d: opened\n", pRet));
45658   }
45659   return rc;
45660 }
45661
45662 /*
45663 ** Change the size to which the WAL file is trucated on each reset.
45664 */
45665 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
45666   if( pWal ) pWal->mxWalSize = iLimit;
45667 }
45668
45669 /*
45670 ** Find the smallest page number out of all pages held in the WAL that
45671 ** has not been returned by any prior invocation of this method on the
45672 ** same WalIterator object.   Write into *piFrame the frame index where
45673 ** that page was last written into the WAL.  Write into *piPage the page
45674 ** number.
45675 **
45676 ** Return 0 on success.  If there are no pages in the WAL with a page
45677 ** number larger than *piPage, then return 1.
45678 */
45679 static int walIteratorNext(
45680   WalIterator *p,               /* Iterator */
45681   u32 *piPage,                  /* OUT: The page number of the next page */
45682   u32 *piFrame                  /* OUT: Wal frame index of next page */
45683 ){
45684   u32 iMin;                     /* Result pgno must be greater than iMin */
45685   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
45686   int i;                        /* For looping through segments */
45687
45688   iMin = p->iPrior;
45689   assert( iMin<0xffffffff );
45690   for(i=p->nSegment-1; i>=0; i--){
45691     struct WalSegment *pSegment = &p->aSegment[i];
45692     while( pSegment->iNext<pSegment->nEntry ){
45693       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
45694       if( iPg>iMin ){
45695         if( iPg<iRet ){
45696           iRet = iPg;
45697           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
45698         }
45699         break;
45700       }
45701       pSegment->iNext++;
45702     }
45703   }
45704
45705   *piPage = p->iPrior = iRet;
45706   return (iRet==0xFFFFFFFF);
45707 }
45708
45709 /*
45710 ** This function merges two sorted lists into a single sorted list.
45711 **
45712 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
45713 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
45714 ** is guaranteed for all J<K:
45715 **
45716 **        aContent[aLeft[J]] < aContent[aLeft[K]]
45717 **        aContent[aRight[J]] < aContent[aRight[K]]
45718 **
45719 ** This routine overwrites aRight[] with a new (probably longer) sequence
45720 ** of indices such that the aRight[] contains every index that appears in
45721 ** either aLeft[] or the old aRight[] and such that the second condition
45722 ** above is still met.
45723 **
45724 ** The aContent[aLeft[X]] values will be unique for all X.  And the
45725 ** aContent[aRight[X]] values will be unique too.  But there might be
45726 ** one or more combinations of X and Y such that
45727 **
45728 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
45729 **
45730 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
45731 */
45732 static void walMerge(
45733   const u32 *aContent,            /* Pages in wal - keys for the sort */
45734   ht_slot *aLeft,                 /* IN: Left hand input list */
45735   int nLeft,                      /* IN: Elements in array *paLeft */
45736   ht_slot **paRight,              /* IN/OUT: Right hand input list */
45737   int *pnRight,                   /* IN/OUT: Elements in *paRight */
45738   ht_slot *aTmp                   /* Temporary buffer */
45739 ){
45740   int iLeft = 0;                  /* Current index in aLeft */
45741   int iRight = 0;                 /* Current index in aRight */
45742   int iOut = 0;                   /* Current index in output buffer */
45743   int nRight = *pnRight;
45744   ht_slot *aRight = *paRight;
45745
45746   assert( nLeft>0 && nRight>0 );
45747   while( iRight<nRight || iLeft<nLeft ){
45748     ht_slot logpage;
45749     Pgno dbpage;
45750
45751     if( (iLeft<nLeft) 
45752      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
45753     ){
45754       logpage = aLeft[iLeft++];
45755     }else{
45756       logpage = aRight[iRight++];
45757     }
45758     dbpage = aContent[logpage];
45759
45760     aTmp[iOut++] = logpage;
45761     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
45762
45763     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
45764     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
45765   }
45766
45767   *paRight = aLeft;
45768   *pnRight = iOut;
45769   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
45770 }
45771
45772 /*
45773 ** Sort the elements in list aList using aContent[] as the sort key.
45774 ** Remove elements with duplicate keys, preferring to keep the
45775 ** larger aList[] values.
45776 **
45777 ** The aList[] entries are indices into aContent[].  The values in
45778 ** aList[] are to be sorted so that for all J<K:
45779 **
45780 **      aContent[aList[J]] < aContent[aList[K]]
45781 **
45782 ** For any X and Y such that
45783 **
45784 **      aContent[aList[X]] == aContent[aList[Y]]
45785 **
45786 ** Keep the larger of the two values aList[X] and aList[Y] and discard
45787 ** the smaller.
45788 */
45789 static void walMergesort(
45790   const u32 *aContent,            /* Pages in wal */
45791   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
45792   ht_slot *aList,                 /* IN/OUT: List to sort */
45793   int *pnList                     /* IN/OUT: Number of elements in aList[] */
45794 ){
45795   struct Sublist {
45796     int nList;                    /* Number of elements in aList */
45797     ht_slot *aList;               /* Pointer to sub-list content */
45798   };
45799
45800   const int nList = *pnList;      /* Size of input list */
45801   int nMerge = 0;                 /* Number of elements in list aMerge */
45802   ht_slot *aMerge = 0;            /* List to be merged */
45803   int iList;                      /* Index into input list */
45804   int iSub = 0;                   /* Index into aSub array */
45805   struct Sublist aSub[13];        /* Array of sub-lists */
45806
45807   memset(aSub, 0, sizeof(aSub));
45808   assert( nList<=HASHTABLE_NPAGE && nList>0 );
45809   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
45810
45811   for(iList=0; iList<nList; iList++){
45812     nMerge = 1;
45813     aMerge = &aList[iList];
45814     for(iSub=0; iList & (1<<iSub); iSub++){
45815       struct Sublist *p = &aSub[iSub];
45816       assert( p->aList && p->nList<=(1<<iSub) );
45817       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
45818       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45819     }
45820     aSub[iSub].aList = aMerge;
45821     aSub[iSub].nList = nMerge;
45822   }
45823
45824   for(iSub++; iSub<ArraySize(aSub); iSub++){
45825     if( nList & (1<<iSub) ){
45826       struct Sublist *p = &aSub[iSub];
45827       assert( p->nList<=(1<<iSub) );
45828       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
45829       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45830     }
45831   }
45832   assert( aMerge==aList );
45833   *pnList = nMerge;
45834
45835 #ifdef SQLITE_DEBUG
45836   {
45837     int i;
45838     for(i=1; i<*pnList; i++){
45839       assert( aContent[aList[i]] > aContent[aList[i-1]] );
45840     }
45841   }
45842 #endif
45843 }
45844
45845 /* 
45846 ** Free an iterator allocated by walIteratorInit().
45847 */
45848 static void walIteratorFree(WalIterator *p){
45849   sqlite3ScratchFree(p);
45850 }
45851
45852 /*
45853 ** Construct a WalInterator object that can be used to loop over all 
45854 ** pages in the WAL in ascending order. The caller must hold the checkpoint
45855 ** lock.
45856 **
45857 ** On success, make *pp point to the newly allocated WalInterator object
45858 ** return SQLITE_OK. Otherwise, return an error code. If this routine
45859 ** returns an error, the value of *pp is undefined.
45860 **
45861 ** The calling routine should invoke walIteratorFree() to destroy the
45862 ** WalIterator object when it has finished with it.
45863 */
45864 static int walIteratorInit(Wal *pWal, WalIterator **pp){
45865   WalIterator *p;                 /* Return value */
45866   int nSegment;                   /* Number of segments to merge */
45867   u32 iLast;                      /* Last frame in log */
45868   int nByte;                      /* Number of bytes to allocate */
45869   int i;                          /* Iterator variable */
45870   ht_slot *aTmp;                  /* Temp space used by merge-sort */
45871   int rc = SQLITE_OK;             /* Return Code */
45872
45873   /* This routine only runs while holding the checkpoint lock. And
45874   ** it only runs if there is actually content in the log (mxFrame>0).
45875   */
45876   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
45877   iLast = pWal->hdr.mxFrame;
45878
45879   /* Allocate space for the WalIterator object. */
45880   nSegment = walFramePage(iLast) + 1;
45881   nByte = sizeof(WalIterator) 
45882         + (nSegment-1)*sizeof(struct WalSegment)
45883         + iLast*sizeof(ht_slot);
45884   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
45885   if( !p ){
45886     return SQLITE_NOMEM;
45887   }
45888   memset(p, 0, nByte);
45889   p->nSegment = nSegment;
45890
45891   /* Allocate temporary space used by the merge-sort routine. This block
45892   ** of memory will be freed before this function returns.
45893   */
45894   aTmp = (ht_slot *)sqlite3ScratchMalloc(
45895       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
45896   );
45897   if( !aTmp ){
45898     rc = SQLITE_NOMEM;
45899   }
45900
45901   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
45902     volatile ht_slot *aHash;
45903     u32 iZero;
45904     volatile u32 *aPgno;
45905
45906     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
45907     if( rc==SQLITE_OK ){
45908       int j;                      /* Counter variable */
45909       int nEntry;                 /* Number of entries in this segment */
45910       ht_slot *aIndex;            /* Sorted index for this segment */
45911
45912       aPgno++;
45913       if( (i+1)==nSegment ){
45914         nEntry = (int)(iLast - iZero);
45915       }else{
45916         nEntry = (int)((u32*)aHash - (u32*)aPgno);
45917       }
45918       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
45919       iZero++;
45920   
45921       for(j=0; j<nEntry; j++){
45922         aIndex[j] = (ht_slot)j;
45923       }
45924       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
45925       p->aSegment[i].iZero = iZero;
45926       p->aSegment[i].nEntry = nEntry;
45927       p->aSegment[i].aIndex = aIndex;
45928       p->aSegment[i].aPgno = (u32 *)aPgno;
45929     }
45930   }
45931   sqlite3ScratchFree(aTmp);
45932
45933   if( rc!=SQLITE_OK ){
45934     walIteratorFree(p);
45935   }
45936   *pp = p;
45937   return rc;
45938 }
45939
45940 /*
45941 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
45942 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
45943 ** busy-handler function. Invoke it and retry the lock until either the
45944 ** lock is successfully obtained or the busy-handler returns 0.
45945 */
45946 static int walBusyLock(
45947   Wal *pWal,                      /* WAL connection */
45948   int (*xBusy)(void*),            /* Function to call when busy */
45949   void *pBusyArg,                 /* Context argument for xBusyHandler */
45950   int lockIdx,                    /* Offset of first byte to lock */
45951   int n                           /* Number of bytes to lock */
45952 ){
45953   int rc;
45954   do {
45955     rc = walLockExclusive(pWal, lockIdx, n);
45956   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
45957   return rc;
45958 }
45959
45960 /*
45961 ** The cache of the wal-index header must be valid to call this function.
45962 ** Return the page-size in bytes used by the database.
45963 */
45964 static int walPagesize(Wal *pWal){
45965   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45966 }
45967
45968 /*
45969 ** Copy as much content as we can from the WAL back into the database file
45970 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
45971 **
45972 ** The amount of information copies from WAL to database might be limited
45973 ** by active readers.  This routine will never overwrite a database page
45974 ** that a concurrent reader might be using.
45975 **
45976 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
45977 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
45978 ** checkpoints are always run by a background thread or background 
45979 ** process, foreground threads will never block on a lengthy fsync call.
45980 **
45981 ** Fsync is called on the WAL before writing content out of the WAL and
45982 ** into the database.  This ensures that if the new content is persistent
45983 ** in the WAL and can be recovered following a power-loss or hard reset.
45984 **
45985 ** Fsync is also called on the database file if (and only if) the entire
45986 ** WAL content is copied into the database file.  This second fsync makes
45987 ** it safe to delete the WAL since the new content will persist in the
45988 ** database file.
45989 **
45990 ** This routine uses and updates the nBackfill field of the wal-index header.
45991 ** This is the only routine tha will increase the value of nBackfill.  
45992 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
45993 ** its value.)
45994 **
45995 ** The caller must be holding sufficient locks to ensure that no other
45996 ** checkpoint is running (in any other thread or process) at the same
45997 ** time.
45998 */
45999 static int walCheckpoint(
46000   Wal *pWal,                      /* Wal connection */
46001   int eMode,                      /* One of PASSIVE, FULL or RESTART */
46002   int (*xBusyCall)(void*),        /* Function to call when busy */
46003   void *pBusyArg,                 /* Context argument for xBusyHandler */
46004   int sync_flags,                 /* Flags for OsSync() (or 0) */
46005   u8 *zBuf                        /* Temporary buffer to use */
46006 ){
46007   int rc;                         /* Return code */
46008   int szPage;                     /* Database page-size */
46009   WalIterator *pIter = 0;         /* Wal iterator context */
46010   u32 iDbpage = 0;                /* Next database page to write */
46011   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
46012   u32 mxSafeFrame;                /* Max frame that can be backfilled */
46013   u32 mxPage;                     /* Max database page to write */
46014   int i;                          /* Loop counter */
46015   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
46016   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
46017
46018   szPage = walPagesize(pWal);
46019   testcase( szPage<=32768 );
46020   testcase( szPage>=65536 );
46021   pInfo = walCkptInfo(pWal);
46022   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
46023
46024   /* Allocate the iterator */
46025   rc = walIteratorInit(pWal, &pIter);
46026   if( rc!=SQLITE_OK ){
46027     return rc;
46028   }
46029   assert( pIter );
46030
46031   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
46032
46033   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
46034   ** safe to write into the database.  Frames beyond mxSafeFrame might
46035   ** overwrite database pages that are in use by active readers and thus
46036   ** cannot be backfilled from the WAL.
46037   */
46038   mxSafeFrame = pWal->hdr.mxFrame;
46039   mxPage = pWal->hdr.nPage;
46040   for(i=1; i<WAL_NREADER; i++){
46041     u32 y = pInfo->aReadMark[i];
46042     if( mxSafeFrame>y ){
46043       assert( y<=pWal->hdr.mxFrame );
46044       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
46045       if( rc==SQLITE_OK ){
46046         pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
46047         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
46048       }else if( rc==SQLITE_BUSY ){
46049         mxSafeFrame = y;
46050         xBusy = 0;
46051       }else{
46052         goto walcheckpoint_out;
46053       }
46054     }
46055   }
46056
46057   if( pInfo->nBackfill<mxSafeFrame
46058    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
46059   ){
46060     i64 nSize;                    /* Current size of database file */
46061     u32 nBackfill = pInfo->nBackfill;
46062
46063     /* Sync the WAL to disk */
46064     if( sync_flags ){
46065       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
46066     }
46067
46068     /* If the database file may grow as a result of this checkpoint, hint
46069     ** about the eventual size of the db file to the VFS layer. 
46070     */
46071     if( rc==SQLITE_OK ){
46072       i64 nReq = ((i64)mxPage * szPage);
46073       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
46074       if( rc==SQLITE_OK && nSize<nReq ){
46075         sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
46076       }
46077     }
46078
46079     /* Iterate through the contents of the WAL, copying data to the db file. */
46080     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
46081       i64 iOffset;
46082       assert( walFramePgno(pWal, iFrame)==iDbpage );
46083       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
46084       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
46085       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
46086       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
46087       if( rc!=SQLITE_OK ) break;
46088       iOffset = (iDbpage-1)*(i64)szPage;
46089       testcase( IS_BIG_INT(iOffset) );
46090       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
46091       if( rc!=SQLITE_OK ) break;
46092     }
46093
46094     /* If work was actually accomplished... */
46095     if( rc==SQLITE_OK ){
46096       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
46097         i64 szDb = pWal->hdr.nPage*(i64)szPage;
46098         testcase( IS_BIG_INT(szDb) );
46099         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
46100         if( rc==SQLITE_OK && sync_flags ){
46101           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
46102         }
46103       }
46104       if( rc==SQLITE_OK ){
46105         pInfo->nBackfill = mxSafeFrame;
46106       }
46107     }
46108
46109     /* Release the reader lock held while backfilling */
46110     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
46111   }
46112
46113   if( rc==SQLITE_BUSY ){
46114     /* Reset the return code so as not to report a checkpoint failure
46115     ** just because there are active readers.  */
46116     rc = SQLITE_OK;
46117   }
46118
46119   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
46120   ** file has been copied into the database file, then block until all
46121   ** readers have finished using the wal file. This ensures that the next
46122   ** process to write to the database restarts the wal file.
46123   */
46124   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
46125     assert( pWal->writeLock );
46126     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
46127       rc = SQLITE_BUSY;
46128     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
46129       assert( mxSafeFrame==pWal->hdr.mxFrame );
46130       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
46131       if( rc==SQLITE_OK ){
46132         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46133       }
46134     }
46135   }
46136
46137  walcheckpoint_out:
46138   walIteratorFree(pIter);
46139   return rc;
46140 }
46141
46142 /*
46143 ** If the WAL file is currently larger than nMax bytes in size, truncate
46144 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
46145 */
46146 static void walLimitSize(Wal *pWal, i64 nMax){
46147   i64 sz;
46148   int rx;
46149   sqlite3BeginBenignMalloc();
46150   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
46151   if( rx==SQLITE_OK && (sz > nMax ) ){
46152     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
46153   }
46154   sqlite3EndBenignMalloc();
46155   if( rx ){
46156     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
46157   }
46158 }
46159
46160 /*
46161 ** Close a connection to a log file.
46162 */
46163 SQLITE_PRIVATE int sqlite3WalClose(
46164   Wal *pWal,                      /* Wal to close */
46165   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
46166   int nBuf,
46167   u8 *zBuf                        /* Buffer of at least nBuf bytes */
46168 ){
46169   int rc = SQLITE_OK;
46170   if( pWal ){
46171     int isDelete = 0;             /* True to unlink wal and wal-index files */
46172
46173     /* If an EXCLUSIVE lock can be obtained on the database file (using the
46174     ** ordinary, rollback-mode locking methods, this guarantees that the
46175     ** connection associated with this log file is the only connection to
46176     ** the database. In this case checkpoint the database and unlink both
46177     ** the wal and wal-index files.
46178     **
46179     ** The EXCLUSIVE lock is not released before returning.
46180     */
46181     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
46182     if( rc==SQLITE_OK ){
46183       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
46184         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
46185       }
46186       rc = sqlite3WalCheckpoint(
46187           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
46188       );
46189       if( rc==SQLITE_OK ){
46190         int bPersist = -1;
46191         sqlite3OsFileControlHint(
46192             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
46193         );
46194         if( bPersist!=1 ){
46195           /* Try to delete the WAL file if the checkpoint completed and
46196           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
46197           ** mode (!bPersist) */
46198           isDelete = 1;
46199         }else if( pWal->mxWalSize>=0 ){
46200           /* Try to truncate the WAL file to zero bytes if the checkpoint
46201           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
46202           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
46203           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
46204           ** to zero bytes as truncating to the journal_size_limit might
46205           ** leave a corrupt WAL file on disk. */
46206           walLimitSize(pWal, 0);
46207         }
46208       }
46209     }
46210
46211     walIndexClose(pWal, isDelete);
46212     sqlite3OsClose(pWal->pWalFd);
46213     if( isDelete ){
46214       sqlite3BeginBenignMalloc();
46215       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
46216       sqlite3EndBenignMalloc();
46217     }
46218     WALTRACE(("WAL%p: closed\n", pWal));
46219     sqlite3_free((void *)pWal->apWiData);
46220     sqlite3_free(pWal);
46221   }
46222   return rc;
46223 }
46224
46225 /*
46226 ** Try to read the wal-index header.  Return 0 on success and 1 if
46227 ** there is a problem.
46228 **
46229 ** The wal-index is in shared memory.  Another thread or process might
46230 ** be writing the header at the same time this procedure is trying to
46231 ** read it, which might result in inconsistency.  A dirty read is detected
46232 ** by verifying that both copies of the header are the same and also by
46233 ** a checksum on the header.
46234 **
46235 ** If and only if the read is consistent and the header is different from
46236 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
46237 ** and *pChanged is set to 1.
46238 **
46239 ** If the checksum cannot be verified return non-zero. If the header
46240 ** is read successfully and the checksum verified, return zero.
46241 */
46242 static int walIndexTryHdr(Wal *pWal, int *pChanged){
46243   u32 aCksum[2];                  /* Checksum on the header content */
46244   WalIndexHdr h1, h2;             /* Two copies of the header content */
46245   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
46246
46247   /* The first page of the wal-index must be mapped at this point. */
46248   assert( pWal->nWiData>0 && pWal->apWiData[0] );
46249
46250   /* Read the header. This might happen concurrently with a write to the
46251   ** same area of shared memory on a different CPU in a SMP,
46252   ** meaning it is possible that an inconsistent snapshot is read
46253   ** from the file. If this happens, return non-zero.
46254   **
46255   ** There are two copies of the header at the beginning of the wal-index.
46256   ** When reading, read [0] first then [1].  Writes are in the reverse order.
46257   ** Memory barriers are used to prevent the compiler or the hardware from
46258   ** reordering the reads and writes.
46259   */
46260   aHdr = walIndexHdr(pWal);
46261   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
46262   walShmBarrier(pWal);
46263   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
46264
46265   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
46266     return 1;   /* Dirty read */
46267   }  
46268   if( h1.isInit==0 ){
46269     return 1;   /* Malformed header - probably all zeros */
46270   }
46271   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
46272   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
46273     return 1;   /* Checksum does not match */
46274   }
46275
46276   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
46277     *pChanged = 1;
46278     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
46279     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
46280     testcase( pWal->szPage<=32768 );
46281     testcase( pWal->szPage>=65536 );
46282   }
46283
46284   /* The header was successfully read. Return zero. */
46285   return 0;
46286 }
46287
46288 /*
46289 ** Read the wal-index header from the wal-index and into pWal->hdr.
46290 ** If the wal-header appears to be corrupt, try to reconstruct the
46291 ** wal-index from the WAL before returning.
46292 **
46293 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
46294 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
46295 ** to 0.
46296 **
46297 ** If the wal-index header is successfully read, return SQLITE_OK. 
46298 ** Otherwise an SQLite error code.
46299 */
46300 static int walIndexReadHdr(Wal *pWal, int *pChanged){
46301   int rc;                         /* Return code */
46302   int badHdr;                     /* True if a header read failed */
46303   volatile u32 *page0;            /* Chunk of wal-index containing header */
46304
46305   /* Ensure that page 0 of the wal-index (the page that contains the 
46306   ** wal-index header) is mapped. Return early if an error occurs here.
46307   */
46308   assert( pChanged );
46309   rc = walIndexPage(pWal, 0, &page0);
46310   if( rc!=SQLITE_OK ){
46311     return rc;
46312   };
46313   assert( page0 || pWal->writeLock==0 );
46314
46315   /* If the first page of the wal-index has been mapped, try to read the
46316   ** wal-index header immediately, without holding any lock. This usually
46317   ** works, but may fail if the wal-index header is corrupt or currently 
46318   ** being modified by another thread or process.
46319   */
46320   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
46321
46322   /* If the first attempt failed, it might have been due to a race
46323   ** with a writer.  So get a WRITE lock and try again.
46324   */
46325   assert( badHdr==0 || pWal->writeLock==0 );
46326   if( badHdr ){
46327     if( pWal->readOnly & WAL_SHM_RDONLY ){
46328       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
46329         walUnlockShared(pWal, WAL_WRITE_LOCK);
46330         rc = SQLITE_READONLY_RECOVERY;
46331       }
46332     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
46333       pWal->writeLock = 1;
46334       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
46335         badHdr = walIndexTryHdr(pWal, pChanged);
46336         if( badHdr ){
46337           /* If the wal-index header is still malformed even while holding
46338           ** a WRITE lock, it can only mean that the header is corrupted and
46339           ** needs to be reconstructed.  So run recovery to do exactly that.
46340           */
46341           rc = walIndexRecover(pWal);
46342           *pChanged = 1;
46343         }
46344       }
46345       pWal->writeLock = 0;
46346       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46347     }
46348   }
46349
46350   /* If the header is read successfully, check the version number to make
46351   ** sure the wal-index was not constructed with some future format that
46352   ** this version of SQLite cannot understand.
46353   */
46354   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
46355     rc = SQLITE_CANTOPEN_BKPT;
46356   }
46357
46358   return rc;
46359 }
46360
46361 /*
46362 ** This is the value that walTryBeginRead returns when it needs to
46363 ** be retried.
46364 */
46365 #define WAL_RETRY  (-1)
46366
46367 /*
46368 ** Attempt to start a read transaction.  This might fail due to a race or
46369 ** other transient condition.  When that happens, it returns WAL_RETRY to
46370 ** indicate to the caller that it is safe to retry immediately.
46371 **
46372 ** On success return SQLITE_OK.  On a permanent failure (such an
46373 ** I/O error or an SQLITE_BUSY because another process is running
46374 ** recovery) return a positive error code.
46375 **
46376 ** The useWal parameter is true to force the use of the WAL and disable
46377 ** the case where the WAL is bypassed because it has been completely
46378 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
46379 ** to make a copy of the wal-index header into pWal->hdr.  If the 
46380 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
46381 ** to the caller that the local paget cache is obsolete and needs to be 
46382 ** flushed.)  When useWal==1, the wal-index header is assumed to already
46383 ** be loaded and the pChanged parameter is unused.
46384 **
46385 ** The caller must set the cnt parameter to the number of prior calls to
46386 ** this routine during the current read attempt that returned WAL_RETRY.
46387 ** This routine will start taking more aggressive measures to clear the
46388 ** race conditions after multiple WAL_RETRY returns, and after an excessive
46389 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
46390 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
46391 ** and is not honoring the locking protocol.  There is a vanishingly small
46392 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
46393 ** bad luck when there is lots of contention for the wal-index, but that
46394 ** possibility is so small that it can be safely neglected, we believe.
46395 **
46396 ** On success, this routine obtains a read lock on 
46397 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
46398 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
46399 ** that means the Wal does not hold any read lock.  The reader must not
46400 ** access any database page that is modified by a WAL frame up to and
46401 ** including frame number aReadMark[pWal->readLock].  The reader will
46402 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
46403 ** Or if pWal->readLock==0, then the reader will ignore the WAL
46404 ** completely and get all content directly from the database file.
46405 ** If the useWal parameter is 1 then the WAL will never be ignored and
46406 ** this routine will always set pWal->readLock>0 on success.
46407 ** When the read transaction is completed, the caller must release the
46408 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
46409 **
46410 ** This routine uses the nBackfill and aReadMark[] fields of the header
46411 ** to select a particular WAL_READ_LOCK() that strives to let the
46412 ** checkpoint process do as much work as possible.  This routine might
46413 ** update values of the aReadMark[] array in the header, but if it does
46414 ** so it takes care to hold an exclusive lock on the corresponding
46415 ** WAL_READ_LOCK() while changing values.
46416 */
46417 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
46418   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
46419   u32 mxReadMark;                 /* Largest aReadMark[] value */
46420   int mxI;                        /* Index of largest aReadMark[] value */
46421   int i;                          /* Loop counter */
46422   int rc = SQLITE_OK;             /* Return code  */
46423
46424   assert( pWal->readLock<0 );     /* Not currently locked */
46425
46426   /* Take steps to avoid spinning forever if there is a protocol error.
46427   **
46428   ** Circumstances that cause a RETRY should only last for the briefest
46429   ** instances of time.  No I/O or other system calls are done while the
46430   ** locks are held, so the locks should not be held for very long. But 
46431   ** if we are unlucky, another process that is holding a lock might get
46432   ** paged out or take a page-fault that is time-consuming to resolve, 
46433   ** during the few nanoseconds that it is holding the lock.  In that case,
46434   ** it might take longer than normal for the lock to free.
46435   **
46436   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
46437   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
46438   ** is more of a scheduler yield than an actual delay.  But on the 10th
46439   ** an subsequent retries, the delays start becoming longer and longer, 
46440   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
46441   ** The total delay time before giving up is less than 1 second.
46442   */
46443   if( cnt>5 ){
46444     int nDelay = 1;                      /* Pause time in microseconds */
46445     if( cnt>100 ){
46446       VVA_ONLY( pWal->lockError = 1; )
46447       return SQLITE_PROTOCOL;
46448     }
46449     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
46450     sqlite3OsSleep(pWal->pVfs, nDelay);
46451   }
46452
46453   if( !useWal ){
46454     rc = walIndexReadHdr(pWal, pChanged);
46455     if( rc==SQLITE_BUSY ){
46456       /* If there is not a recovery running in another thread or process
46457       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
46458       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
46459       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
46460       ** would be technically correct.  But the race is benign since with
46461       ** WAL_RETRY this routine will be called again and will probably be
46462       ** right on the second iteration.
46463       */
46464       if( pWal->apWiData[0]==0 ){
46465         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
46466         ** We assume this is a transient condition, so return WAL_RETRY. The
46467         ** xShmMap() implementation used by the default unix and win32 VFS 
46468         ** modules may return SQLITE_BUSY due to a race condition in the 
46469         ** code that determines whether or not the shared-memory region 
46470         ** must be zeroed before the requested page is returned.
46471         */
46472         rc = WAL_RETRY;
46473       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
46474         walUnlockShared(pWal, WAL_RECOVER_LOCK);
46475         rc = WAL_RETRY;
46476       }else if( rc==SQLITE_BUSY ){
46477         rc = SQLITE_BUSY_RECOVERY;
46478       }
46479     }
46480     if( rc!=SQLITE_OK ){
46481       return rc;
46482     }
46483   }
46484
46485   pInfo = walCkptInfo(pWal);
46486   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
46487     /* The WAL has been completely backfilled (or it is empty).
46488     ** and can be safely ignored.
46489     */
46490     rc = walLockShared(pWal, WAL_READ_LOCK(0));
46491     walShmBarrier(pWal);
46492     if( rc==SQLITE_OK ){
46493       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
46494         /* It is not safe to allow the reader to continue here if frames
46495         ** may have been appended to the log before READ_LOCK(0) was obtained.
46496         ** When holding READ_LOCK(0), the reader ignores the entire log file,
46497         ** which implies that the database file contains a trustworthy
46498         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
46499         ** happening, this is usually correct.
46500         **
46501         ** However, if frames have been appended to the log (or if the log 
46502         ** is wrapped and written for that matter) before the READ_LOCK(0)
46503         ** is obtained, that is not necessarily true. A checkpointer may
46504         ** have started to backfill the appended frames but crashed before
46505         ** it finished. Leaving a corrupt image in the database file.
46506         */
46507         walUnlockShared(pWal, WAL_READ_LOCK(0));
46508         return WAL_RETRY;
46509       }
46510       pWal->readLock = 0;
46511       return SQLITE_OK;
46512     }else if( rc!=SQLITE_BUSY ){
46513       return rc;
46514     }
46515   }
46516
46517   /* If we get this far, it means that the reader will want to use
46518   ** the WAL to get at content from recent commits.  The job now is
46519   ** to select one of the aReadMark[] entries that is closest to
46520   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
46521   */
46522   mxReadMark = 0;
46523   mxI = 0;
46524   for(i=1; i<WAL_NREADER; i++){
46525     u32 thisMark = pInfo->aReadMark[i];
46526     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
46527       assert( thisMark!=READMARK_NOT_USED );
46528       mxReadMark = thisMark;
46529       mxI = i;
46530     }
46531   }
46532   /* There was once an "if" here. The extra "{" is to preserve indentation. */
46533   {
46534     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
46535      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
46536     ){
46537       for(i=1; i<WAL_NREADER; i++){
46538         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
46539         if( rc==SQLITE_OK ){
46540           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
46541           mxI = i;
46542           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
46543           break;
46544         }else if( rc!=SQLITE_BUSY ){
46545           return rc;
46546         }
46547       }
46548     }
46549     if( mxI==0 ){
46550       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
46551       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
46552     }
46553
46554     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
46555     if( rc ){
46556       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
46557     }
46558     /* Now that the read-lock has been obtained, check that neither the
46559     ** value in the aReadMark[] array or the contents of the wal-index
46560     ** header have changed.
46561     **
46562     ** It is necessary to check that the wal-index header did not change
46563     ** between the time it was read and when the shared-lock was obtained
46564     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
46565     ** that the log file may have been wrapped by a writer, or that frames
46566     ** that occur later in the log than pWal->hdr.mxFrame may have been
46567     ** copied into the database by a checkpointer. If either of these things
46568     ** happened, then reading the database with the current value of
46569     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
46570     ** instead.
46571     **
46572     ** This does not guarantee that the copy of the wal-index header is up to
46573     ** date before proceeding. That would not be possible without somehow
46574     ** blocking writers. It only guarantees that a dangerous checkpoint or 
46575     ** log-wrap (either of which would require an exclusive lock on
46576     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
46577     */
46578     walShmBarrier(pWal);
46579     if( pInfo->aReadMark[mxI]!=mxReadMark
46580      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
46581     ){
46582       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
46583       return WAL_RETRY;
46584     }else{
46585       assert( mxReadMark<=pWal->hdr.mxFrame );
46586       pWal->readLock = (i16)mxI;
46587     }
46588   }
46589   return rc;
46590 }
46591
46592 /*
46593 ** Begin a read transaction on the database.
46594 **
46595 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
46596 ** it takes a snapshot of the state of the WAL and wal-index for the current
46597 ** instant in time.  The current thread will continue to use this snapshot.
46598 ** Other threads might append new content to the WAL and wal-index but
46599 ** that extra content is ignored by the current thread.
46600 **
46601 ** If the database contents have changes since the previous read
46602 ** transaction, then *pChanged is set to 1 before returning.  The
46603 ** Pager layer will use this to know that is cache is stale and
46604 ** needs to be flushed.
46605 */
46606 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
46607   int rc;                         /* Return code */
46608   int cnt = 0;                    /* Number of TryBeginRead attempts */
46609
46610   do{
46611     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
46612   }while( rc==WAL_RETRY );
46613   testcase( (rc&0xff)==SQLITE_BUSY );
46614   testcase( (rc&0xff)==SQLITE_IOERR );
46615   testcase( rc==SQLITE_PROTOCOL );
46616   testcase( rc==SQLITE_OK );
46617   return rc;
46618 }
46619
46620 /*
46621 ** Finish with a read transaction.  All this does is release the
46622 ** read-lock.
46623 */
46624 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
46625   sqlite3WalEndWriteTransaction(pWal);
46626   if( pWal->readLock>=0 ){
46627     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46628     pWal->readLock = -1;
46629   }
46630 }
46631
46632 /*
46633 ** Read a page from the WAL, if it is present in the WAL and if the 
46634 ** current read transaction is configured to use the WAL.  
46635 **
46636 ** The *pInWal is set to 1 if the requested page is in the WAL and
46637 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
46638 ** the WAL and needs to be read out of the database.
46639 */
46640 SQLITE_PRIVATE int sqlite3WalRead(
46641   Wal *pWal,                      /* WAL handle */
46642   Pgno pgno,                      /* Database page number to read data for */
46643   int *pInWal,                    /* OUT: True if data is read from WAL */
46644   int nOut,                       /* Size of buffer pOut in bytes */
46645   u8 *pOut                        /* Buffer to write page data to */
46646 ){
46647   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
46648   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
46649   int iHash;                      /* Used to loop through N hash tables */
46650
46651   /* This routine is only be called from within a read transaction. */
46652   assert( pWal->readLock>=0 || pWal->lockError );
46653
46654   /* If the "last page" field of the wal-index header snapshot is 0, then
46655   ** no data will be read from the wal under any circumstances. Return early
46656   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
46657   ** then the WAL is ignored by the reader so return early, as if the 
46658   ** WAL were empty.
46659   */
46660   if( iLast==0 || pWal->readLock==0 ){
46661     *pInWal = 0;
46662     return SQLITE_OK;
46663   }
46664
46665   /* Search the hash table or tables for an entry matching page number
46666   ** pgno. Each iteration of the following for() loop searches one
46667   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
46668   **
46669   ** This code might run concurrently to the code in walIndexAppend()
46670   ** that adds entries to the wal-index (and possibly to this hash 
46671   ** table). This means the value just read from the hash 
46672   ** slot (aHash[iKey]) may have been added before or after the 
46673   ** current read transaction was opened. Values added after the
46674   ** read transaction was opened may have been written incorrectly -
46675   ** i.e. these slots may contain garbage data. However, we assume
46676   ** that any slots written before the current read transaction was
46677   ** opened remain unmodified.
46678   **
46679   ** For the reasons above, the if(...) condition featured in the inner
46680   ** loop of the following block is more stringent that would be required 
46681   ** if we had exclusive access to the hash-table:
46682   **
46683   **   (aPgno[iFrame]==pgno): 
46684   **     This condition filters out normal hash-table collisions.
46685   **
46686   **   (iFrame<=iLast): 
46687   **     This condition filters out entries that were added to the hash
46688   **     table after the current read-transaction had started.
46689   */
46690   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
46691     volatile ht_slot *aHash;      /* Pointer to hash table */
46692     volatile u32 *aPgno;          /* Pointer to array of page numbers */
46693     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
46694     int iKey;                     /* Hash slot index */
46695     int nCollide;                 /* Number of hash collisions remaining */
46696     int rc;                       /* Error code */
46697
46698     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
46699     if( rc!=SQLITE_OK ){
46700       return rc;
46701     }
46702     nCollide = HASHTABLE_NSLOT;
46703     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
46704       u32 iFrame = aHash[iKey] + iZero;
46705       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
46706         /* assert( iFrame>iRead ); -- not true if there is corruption */
46707         iRead = iFrame;
46708       }
46709       if( (nCollide--)==0 ){
46710         return SQLITE_CORRUPT_BKPT;
46711       }
46712     }
46713   }
46714
46715 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46716   /* If expensive assert() statements are available, do a linear search
46717   ** of the wal-index file content. Make sure the results agree with the
46718   ** result obtained using the hash indexes above.  */
46719   {
46720     u32 iRead2 = 0;
46721     u32 iTest;
46722     for(iTest=iLast; iTest>0; iTest--){
46723       if( walFramePgno(pWal, iTest)==pgno ){
46724         iRead2 = iTest;
46725         break;
46726       }
46727     }
46728     assert( iRead==iRead2 );
46729   }
46730 #endif
46731
46732   /* If iRead is non-zero, then it is the log frame number that contains the
46733   ** required page. Read and return data from the log file.
46734   */
46735   if( iRead ){
46736     int sz;
46737     i64 iOffset;
46738     sz = pWal->hdr.szPage;
46739     sz = (sz&0xfe00) + ((sz&0x0001)<<16);
46740     testcase( sz<=32768 );
46741     testcase( sz>=65536 );
46742     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
46743     *pInWal = 1;
46744     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46745     return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
46746   }
46747
46748   *pInWal = 0;
46749   return SQLITE_OK;
46750 }
46751
46752
46753 /* 
46754 ** Return the size of the database in pages (or zero, if unknown).
46755 */
46756 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
46757   if( pWal && ALWAYS(pWal->readLock>=0) ){
46758     return pWal->hdr.nPage;
46759   }
46760   return 0;
46761 }
46762
46763
46764 /* 
46765 ** This function starts a write transaction on the WAL.
46766 **
46767 ** A read transaction must have already been started by a prior call
46768 ** to sqlite3WalBeginReadTransaction().
46769 **
46770 ** If another thread or process has written into the database since
46771 ** the read transaction was started, then it is not possible for this
46772 ** thread to write as doing so would cause a fork.  So this routine
46773 ** returns SQLITE_BUSY in that case and no write transaction is started.
46774 **
46775 ** There can only be a single writer active at a time.
46776 */
46777 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
46778   int rc;
46779
46780   /* Cannot start a write transaction without first holding a read
46781   ** transaction. */
46782   assert( pWal->readLock>=0 );
46783
46784   if( pWal->readOnly ){
46785     return SQLITE_READONLY;
46786   }
46787
46788   /* Only one writer allowed at a time.  Get the write lock.  Return
46789   ** SQLITE_BUSY if unable.
46790   */
46791   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
46792   if( rc ){
46793     return rc;
46794   }
46795   pWal->writeLock = 1;
46796
46797   /* If another connection has written to the database file since the
46798   ** time the read transaction on this connection was started, then
46799   ** the write is disallowed.
46800   */
46801   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
46802     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46803     pWal->writeLock = 0;
46804     rc = SQLITE_BUSY;
46805   }
46806
46807   return rc;
46808 }
46809
46810 /*
46811 ** End a write transaction.  The commit has already been done.  This
46812 ** routine merely releases the lock.
46813 */
46814 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
46815   if( pWal->writeLock ){
46816     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46817     pWal->writeLock = 0;
46818     pWal->truncateOnCommit = 0;
46819   }
46820   return SQLITE_OK;
46821 }
46822
46823 /*
46824 ** If any data has been written (but not committed) to the log file, this
46825 ** function moves the write-pointer back to the start of the transaction.
46826 **
46827 ** Additionally, the callback function is invoked for each frame written
46828 ** to the WAL since the start of the transaction. If the callback returns
46829 ** other than SQLITE_OK, it is not invoked again and the error code is
46830 ** returned to the caller.
46831 **
46832 ** Otherwise, if the callback function does not return an error, this
46833 ** function returns SQLITE_OK.
46834 */
46835 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
46836   int rc = SQLITE_OK;
46837   if( ALWAYS(pWal->writeLock) ){
46838     Pgno iMax = pWal->hdr.mxFrame;
46839     Pgno iFrame;
46840   
46841     /* Restore the clients cache of the wal-index header to the state it
46842     ** was in before the client began writing to the database. 
46843     */
46844     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
46845
46846     for(iFrame=pWal->hdr.mxFrame+1; 
46847         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
46848         iFrame++
46849     ){
46850       /* This call cannot fail. Unless the page for which the page number
46851       ** is passed as the second argument is (a) in the cache and 
46852       ** (b) has an outstanding reference, then xUndo is either a no-op
46853       ** (if (a) is false) or simply expels the page from the cache (if (b)
46854       ** is false).
46855       **
46856       ** If the upper layer is doing a rollback, it is guaranteed that there
46857       ** are no outstanding references to any page other than page 1. And
46858       ** page 1 is never written to the log until the transaction is
46859       ** committed. As a result, the call to xUndo may not fail.
46860       */
46861       assert( walFramePgno(pWal, iFrame)!=1 );
46862       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
46863     }
46864     if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
46865   }
46866   assert( rc==SQLITE_OK );
46867   return rc;
46868 }
46869
46870 /* 
46871 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
46872 ** values. This function populates the array with values required to 
46873 ** "rollback" the write position of the WAL handle back to the current 
46874 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
46875 */
46876 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
46877   assert( pWal->writeLock );
46878   aWalData[0] = pWal->hdr.mxFrame;
46879   aWalData[1] = pWal->hdr.aFrameCksum[0];
46880   aWalData[2] = pWal->hdr.aFrameCksum[1];
46881   aWalData[3] = pWal->nCkpt;
46882 }
46883
46884 /* 
46885 ** Move the write position of the WAL back to the point identified by
46886 ** the values in the aWalData[] array. aWalData must point to an array
46887 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
46888 ** by a call to WalSavepoint().
46889 */
46890 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
46891   int rc = SQLITE_OK;
46892
46893   assert( pWal->writeLock );
46894   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
46895
46896   if( aWalData[3]!=pWal->nCkpt ){
46897     /* This savepoint was opened immediately after the write-transaction
46898     ** was started. Right after that, the writer decided to wrap around
46899     ** to the start of the log. Update the savepoint values to match.
46900     */
46901     aWalData[0] = 0;
46902     aWalData[3] = pWal->nCkpt;
46903   }
46904
46905   if( aWalData[0]<pWal->hdr.mxFrame ){
46906     pWal->hdr.mxFrame = aWalData[0];
46907     pWal->hdr.aFrameCksum[0] = aWalData[1];
46908     pWal->hdr.aFrameCksum[1] = aWalData[2];
46909     walCleanupHash(pWal);
46910   }
46911
46912   return rc;
46913 }
46914
46915
46916 /*
46917 ** This function is called just before writing a set of frames to the log
46918 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
46919 ** to the current log file, it is possible to overwrite the start of the
46920 ** existing log file with the new frames (i.e. "reset" the log). If so,
46921 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
46922 ** unchanged.
46923 **
46924 ** SQLITE_OK is returned if no error is encountered (regardless of whether
46925 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
46926 ** if an error occurs.
46927 */
46928 static int walRestartLog(Wal *pWal){
46929   int rc = SQLITE_OK;
46930   int cnt;
46931
46932   if( pWal->readLock==0 ){
46933     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
46934     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
46935     if( pInfo->nBackfill>0 ){
46936       u32 salt1;
46937       sqlite3_randomness(4, &salt1);
46938       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46939       if( rc==SQLITE_OK ){
46940         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
46941         ** readers are currently using the WAL), then the transactions
46942         ** frames will overwrite the start of the existing log. Update the
46943         ** wal-index header to reflect this.
46944         **
46945         ** In theory it would be Ok to update the cache of the header only
46946         ** at this point. But updating the actual wal-index header is also
46947         ** safe and means there is no special case for sqlite3WalUndo()
46948         ** to handle if this transaction is rolled back.
46949         */
46950         int i;                    /* Loop counter */
46951         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
46952
46953         pWal->nCkpt++;
46954         pWal->hdr.mxFrame = 0;
46955         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
46956         aSalt[1] = salt1;
46957         walIndexWriteHdr(pWal);
46958         pInfo->nBackfill = 0;
46959         pInfo->aReadMark[1] = 0;
46960         for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
46961         assert( pInfo->aReadMark[0]==0 );
46962         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46963       }else if( rc!=SQLITE_BUSY ){
46964         return rc;
46965       }
46966     }
46967     walUnlockShared(pWal, WAL_READ_LOCK(0));
46968     pWal->readLock = -1;
46969     cnt = 0;
46970     do{
46971       int notUsed;
46972       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
46973     }while( rc==WAL_RETRY );
46974     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
46975     testcase( (rc&0xff)==SQLITE_IOERR );
46976     testcase( rc==SQLITE_PROTOCOL );
46977     testcase( rc==SQLITE_OK );
46978   }
46979   return rc;
46980 }
46981
46982 /*
46983 ** Information about the current state of the WAL file and where
46984 ** the next fsync should occur - passed from sqlite3WalFrames() into
46985 ** walWriteToLog().
46986 */
46987 typedef struct WalWriter {
46988   Wal *pWal;                   /* The complete WAL information */
46989   sqlite3_file *pFd;           /* The WAL file to which we write */
46990   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
46991   int syncFlags;               /* Flags for the fsync */
46992   int szPage;                  /* Size of one page */
46993 } WalWriter;
46994
46995 /*
46996 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
46997 ** Do a sync when crossing the p->iSyncPoint boundary.
46998 **
46999 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
47000 ** first write the part before iSyncPoint, then sync, then write the
47001 ** rest.
47002 */
47003 static int walWriteToLog(
47004   WalWriter *p,              /* WAL to write to */
47005   void *pContent,            /* Content to be written */
47006   int iAmt,                  /* Number of bytes to write */
47007   sqlite3_int64 iOffset      /* Start writing at this offset */
47008 ){
47009   int rc;
47010   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
47011     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
47012     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
47013     if( rc ) return rc;
47014     iOffset += iFirstAmt;
47015     iAmt -= iFirstAmt;
47016     pContent = (void*)(iFirstAmt + (char*)pContent);
47017     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
47018     rc = sqlite3OsSync(p->pFd, p->syncFlags);
47019     if( iAmt==0 || rc ) return rc;
47020   }
47021   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
47022   return rc;
47023 }
47024
47025 /*
47026 ** Write out a single frame of the WAL
47027 */
47028 static int walWriteOneFrame(
47029   WalWriter *p,               /* Where to write the frame */
47030   PgHdr *pPage,               /* The page of the frame to be written */
47031   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
47032   sqlite3_int64 iOffset       /* Byte offset at which to write */
47033 ){
47034   int rc;                         /* Result code from subfunctions */
47035   void *pData;                    /* Data actually written */
47036   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
47037 #if defined(SQLITE_HAS_CODEC)
47038   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
47039 #else
47040   pData = pPage->pData;
47041 #endif
47042   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
47043   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
47044   if( rc ) return rc;
47045   /* Write the page data */
47046   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
47047   return rc;
47048 }
47049
47050 /* 
47051 ** Write a set of frames to the log. The caller must hold the write-lock
47052 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
47053 */
47054 SQLITE_PRIVATE int sqlite3WalFrames(
47055   Wal *pWal,                      /* Wal handle to write to */
47056   int szPage,                     /* Database page-size in bytes */
47057   PgHdr *pList,                   /* List of dirty pages to write */
47058   Pgno nTruncate,                 /* Database size after this commit */
47059   int isCommit,                   /* True if this is a commit */
47060   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
47061 ){
47062   int rc;                         /* Used to catch return codes */
47063   u32 iFrame;                     /* Next frame address */
47064   PgHdr *p;                       /* Iterator to run through pList with. */
47065   PgHdr *pLast = 0;               /* Last frame in list */
47066   int nExtra = 0;                 /* Number of extra copies of last page */
47067   int szFrame;                    /* The size of a single frame */
47068   i64 iOffset;                    /* Next byte to write in WAL file */
47069   WalWriter w;                    /* The writer */
47070
47071   assert( pList );
47072   assert( pWal->writeLock );
47073
47074   /* If this frame set completes a transaction, then nTruncate>0.  If
47075   ** nTruncate==0 then this frame set does not complete the transaction. */
47076   assert( (isCommit!=0)==(nTruncate!=0) );
47077
47078 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
47079   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
47080     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
47081               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
47082   }
47083 #endif
47084
47085   /* See if it is possible to write these frames into the start of the
47086   ** log file, instead of appending to it at pWal->hdr.mxFrame.
47087   */
47088   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
47089     return rc;
47090   }
47091
47092   /* If this is the first frame written into the log, write the WAL
47093   ** header to the start of the WAL file. See comments at the top of
47094   ** this source file for a description of the WAL header format.
47095   */
47096   iFrame = pWal->hdr.mxFrame;
47097   if( iFrame==0 ){
47098     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
47099     u32 aCksum[2];                /* Checksum for wal-header */
47100
47101     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
47102     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
47103     sqlite3Put4byte(&aWalHdr[8], szPage);
47104     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
47105     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
47106     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
47107     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
47108     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
47109     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
47110     
47111     pWal->szPage = szPage;
47112     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
47113     pWal->hdr.aFrameCksum[0] = aCksum[0];
47114     pWal->hdr.aFrameCksum[1] = aCksum[1];
47115     pWal->truncateOnCommit = 1;
47116
47117     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
47118     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
47119     if( rc!=SQLITE_OK ){
47120       return rc;
47121     }
47122
47123     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
47124     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
47125     ** an out-of-order write following a WAL restart could result in
47126     ** database corruption.  See the ticket:
47127     **
47128     **     http://localhost:591/sqlite/info/ff5be73dee
47129     */
47130     if( pWal->syncHeader && sync_flags ){
47131       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
47132       if( rc ) return rc;
47133     }
47134   }
47135   assert( (int)pWal->szPage==szPage );
47136
47137   /* Setup information needed to write frames into the WAL */
47138   w.pWal = pWal;
47139   w.pFd = pWal->pWalFd;
47140   w.iSyncPoint = 0;
47141   w.syncFlags = sync_flags;
47142   w.szPage = szPage;
47143   iOffset = walFrameOffset(iFrame+1, szPage);
47144   szFrame = szPage + WAL_FRAME_HDRSIZE;
47145
47146   /* Write all frames into the log file exactly once */
47147   for(p=pList; p; p=p->pDirty){
47148     int nDbSize;   /* 0 normally.  Positive == commit flag */
47149     iFrame++;
47150     assert( iOffset==walFrameOffset(iFrame, szPage) );
47151     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
47152     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
47153     if( rc ) return rc;
47154     pLast = p;
47155     iOffset += szFrame;
47156   }
47157
47158   /* If this is the end of a transaction, then we might need to pad
47159   ** the transaction and/or sync the WAL file.
47160   **
47161   ** Padding and syncing only occur if this set of frames complete a
47162   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
47163   ** or synchonous==OFF, then no padding or syncing are needed.
47164   **
47165   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
47166   ** needed and only the sync is done.  If padding is needed, then the
47167   ** final frame is repeated (with its commit mark) until the next sector
47168   ** boundary is crossed.  Only the part of the WAL prior to the last
47169   ** sector boundary is synced; the part of the last frame that extends
47170   ** past the sector boundary is written after the sync.
47171   */
47172   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
47173     if( pWal->padToSectorBoundary ){
47174       int sectorSize = sqlite3SectorSize(pWal->pWalFd);
47175       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
47176       while( iOffset<w.iSyncPoint ){
47177         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
47178         if( rc ) return rc;
47179         iOffset += szFrame;
47180         nExtra++;
47181       }
47182     }else{
47183       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
47184     }
47185   }
47186
47187   /* If this frame set completes the first transaction in the WAL and
47188   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
47189   ** journal size limit, if possible.
47190   */
47191   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
47192     i64 sz = pWal->mxWalSize;
47193     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
47194       sz = walFrameOffset(iFrame+nExtra+1, szPage);
47195     }
47196     walLimitSize(pWal, sz);
47197     pWal->truncateOnCommit = 0;
47198   }
47199
47200   /* Append data to the wal-index. It is not necessary to lock the 
47201   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
47202   ** guarantees that there are no other writers, and no data that may
47203   ** be in use by existing readers is being overwritten.
47204   */
47205   iFrame = pWal->hdr.mxFrame;
47206   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
47207     iFrame++;
47208     rc = walIndexAppend(pWal, iFrame, p->pgno);
47209   }
47210   while( rc==SQLITE_OK && nExtra>0 ){
47211     iFrame++;
47212     nExtra--;
47213     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
47214   }
47215
47216   if( rc==SQLITE_OK ){
47217     /* Update the private copy of the header. */
47218     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
47219     testcase( szPage<=32768 );
47220     testcase( szPage>=65536 );
47221     pWal->hdr.mxFrame = iFrame;
47222     if( isCommit ){
47223       pWal->hdr.iChange++;
47224       pWal->hdr.nPage = nTruncate;
47225     }
47226     /* If this is a commit, update the wal-index header too. */
47227     if( isCommit ){
47228       walIndexWriteHdr(pWal);
47229       pWal->iCallback = iFrame;
47230     }
47231   }
47232
47233   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
47234   return rc;
47235 }
47236
47237 /* 
47238 ** This routine is called to implement sqlite3_wal_checkpoint() and
47239 ** related interfaces.
47240 **
47241 ** Obtain a CHECKPOINT lock and then backfill as much information as
47242 ** we can from WAL into the database.
47243 **
47244 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
47245 ** callback. In this case this function runs a blocking checkpoint.
47246 */
47247 SQLITE_PRIVATE int sqlite3WalCheckpoint(
47248   Wal *pWal,                      /* Wal connection */
47249   int eMode,                      /* PASSIVE, FULL or RESTART */
47250   int (*xBusy)(void*),            /* Function to call when busy */
47251   void *pBusyArg,                 /* Context argument for xBusyHandler */
47252   int sync_flags,                 /* Flags to sync db file with (or 0) */
47253   int nBuf,                       /* Size of temporary buffer */
47254   u8 *zBuf,                       /* Temporary buffer to use */
47255   int *pnLog,                     /* OUT: Number of frames in WAL */
47256   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
47257 ){
47258   int rc;                         /* Return code */
47259   int isChanged = 0;              /* True if a new wal-index header is loaded */
47260   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
47261
47262   assert( pWal->ckptLock==0 );
47263   assert( pWal->writeLock==0 );
47264
47265   if( pWal->readOnly ) return SQLITE_READONLY;
47266   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
47267   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
47268   if( rc ){
47269     /* Usually this is SQLITE_BUSY meaning that another thread or process
47270     ** is already running a checkpoint, or maybe a recovery.  But it might
47271     ** also be SQLITE_IOERR. */
47272     return rc;
47273   }
47274   pWal->ckptLock = 1;
47275
47276   /* If this is a blocking-checkpoint, then obtain the write-lock as well
47277   ** to prevent any writers from running while the checkpoint is underway.
47278   ** This has to be done before the call to walIndexReadHdr() below.
47279   **
47280   ** If the writer lock cannot be obtained, then a passive checkpoint is
47281   ** run instead. Since the checkpointer is not holding the writer lock,
47282   ** there is no point in blocking waiting for any readers. Assuming no 
47283   ** other error occurs, this function will return SQLITE_BUSY to the caller.
47284   */
47285   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
47286     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
47287     if( rc==SQLITE_OK ){
47288       pWal->writeLock = 1;
47289     }else if( rc==SQLITE_BUSY ){
47290       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
47291       rc = SQLITE_OK;
47292     }
47293   }
47294
47295   /* Read the wal-index header. */
47296   if( rc==SQLITE_OK ){
47297     rc = walIndexReadHdr(pWal, &isChanged);
47298   }
47299
47300   /* Copy data from the log to the database file. */
47301   if( rc==SQLITE_OK ){
47302     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
47303       rc = SQLITE_CORRUPT_BKPT;
47304     }else{
47305       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
47306     }
47307
47308     /* If no error occurred, set the output variables. */
47309     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
47310       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
47311       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
47312     }
47313   }
47314
47315   if( isChanged ){
47316     /* If a new wal-index header was loaded before the checkpoint was 
47317     ** performed, then the pager-cache associated with pWal is now
47318     ** out of date. So zero the cached wal-index header to ensure that
47319     ** next time the pager opens a snapshot on this database it knows that
47320     ** the cache needs to be reset.
47321     */
47322     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
47323   }
47324
47325   /* Release the locks. */
47326   sqlite3WalEndWriteTransaction(pWal);
47327   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
47328   pWal->ckptLock = 0;
47329   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
47330   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
47331 }
47332
47333 /* Return the value to pass to a sqlite3_wal_hook callback, the
47334 ** number of frames in the WAL at the point of the last commit since
47335 ** sqlite3WalCallback() was called.  If no commits have occurred since
47336 ** the last call, then return 0.
47337 */
47338 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
47339   u32 ret = 0;
47340   if( pWal ){
47341     ret = pWal->iCallback;
47342     pWal->iCallback = 0;
47343   }
47344   return (int)ret;
47345 }
47346
47347 /*
47348 ** This function is called to change the WAL subsystem into or out
47349 ** of locking_mode=EXCLUSIVE.
47350 **
47351 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
47352 ** into locking_mode=NORMAL.  This means that we must acquire a lock
47353 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
47354 ** or if the acquisition of the lock fails, then return 0.  If the
47355 ** transition out of exclusive-mode is successful, return 1.  This
47356 ** operation must occur while the pager is still holding the exclusive
47357 ** lock on the main database file.
47358 **
47359 ** If op is one, then change from locking_mode=NORMAL into 
47360 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
47361 ** be released.  Return 1 if the transition is made and 0 if the
47362 ** WAL is already in exclusive-locking mode - meaning that this
47363 ** routine is a no-op.  The pager must already hold the exclusive lock
47364 ** on the main database file before invoking this operation.
47365 **
47366 ** If op is negative, then do a dry-run of the op==1 case but do
47367 ** not actually change anything. The pager uses this to see if it
47368 ** should acquire the database exclusive lock prior to invoking
47369 ** the op==1 case.
47370 */
47371 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
47372   int rc;
47373   assert( pWal->writeLock==0 );
47374   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
47375
47376   /* pWal->readLock is usually set, but might be -1 if there was a 
47377   ** prior error while attempting to acquire are read-lock. This cannot 
47378   ** happen if the connection is actually in exclusive mode (as no xShmLock
47379   ** locks are taken in this case). Nor should the pager attempt to
47380   ** upgrade to exclusive-mode following such an error.
47381   */
47382   assert( pWal->readLock>=0 || pWal->lockError );
47383   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
47384
47385   if( op==0 ){
47386     if( pWal->exclusiveMode ){
47387       pWal->exclusiveMode = 0;
47388       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
47389         pWal->exclusiveMode = 1;
47390       }
47391       rc = pWal->exclusiveMode==0;
47392     }else{
47393       /* Already in locking_mode=NORMAL */
47394       rc = 0;
47395     }
47396   }else if( op>0 ){
47397     assert( pWal->exclusiveMode==0 );
47398     assert( pWal->readLock>=0 );
47399     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
47400     pWal->exclusiveMode = 1;
47401     rc = 1;
47402   }else{
47403     rc = pWal->exclusiveMode==0;
47404   }
47405   return rc;
47406 }
47407
47408 /* 
47409 ** Return true if the argument is non-NULL and the WAL module is using
47410 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
47411 ** WAL module is using shared-memory, return false. 
47412 */
47413 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
47414   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
47415 }
47416
47417 #ifdef SQLITE_ENABLE_ZIPVFS
47418 /*
47419 ** If the argument is not NULL, it points to a Wal object that holds a
47420 ** read-lock. This function returns the database page-size if it is known,
47421 ** or zero if it is not (or if pWal is NULL).
47422 */
47423 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
47424   assert( pWal==0 || pWal->readLock>=0 );
47425   return (pWal ? pWal->szPage : 0);
47426 }
47427 #endif
47428
47429 #endif /* #ifndef SQLITE_OMIT_WAL */
47430
47431 /************** End of wal.c *************************************************/
47432 /************** Begin file btmutex.c *****************************************/
47433 /*
47434 ** 2007 August 27
47435 **
47436 ** The author disclaims copyright to this source code.  In place of
47437 ** a legal notice, here is a blessing:
47438 **
47439 **    May you do good and not evil.
47440 **    May you find forgiveness for yourself and forgive others.
47441 **    May you share freely, never taking more than you give.
47442 **
47443 *************************************************************************
47444 **
47445 ** This file contains code used to implement mutexes on Btree objects.
47446 ** This code really belongs in btree.c.  But btree.c is getting too
47447 ** big and we want to break it down some.  This packaged seemed like
47448 ** a good breakout.
47449 */
47450 /************** Include btreeInt.h in the middle of btmutex.c ****************/
47451 /************** Begin file btreeInt.h ****************************************/
47452 /*
47453 ** 2004 April 6
47454 **
47455 ** The author disclaims copyright to this source code.  In place of
47456 ** a legal notice, here is a blessing:
47457 **
47458 **    May you do good and not evil.
47459 **    May you find forgiveness for yourself and forgive others.
47460 **    May you share freely, never taking more than you give.
47461 **
47462 *************************************************************************
47463 ** This file implements a external (disk-based) database using BTrees.
47464 ** For a detailed discussion of BTrees, refer to
47465 **
47466 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
47467 **     "Sorting And Searching", pages 473-480. Addison-Wesley
47468 **     Publishing Company, Reading, Massachusetts.
47469 **
47470 ** The basic idea is that each page of the file contains N database
47471 ** entries and N+1 pointers to subpages.
47472 **
47473 **   ----------------------------------------------------------------
47474 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
47475 **   ----------------------------------------------------------------
47476 **
47477 ** All of the keys on the page that Ptr(0) points to have values less
47478 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
47479 ** values greater than Key(0) and less than Key(1).  All of the keys
47480 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
47481 ** so forth.
47482 **
47483 ** Finding a particular key requires reading O(log(M)) pages from the 
47484 ** disk where M is the number of entries in the tree.
47485 **
47486 ** In this implementation, a single file can hold one or more separate 
47487 ** BTrees.  Each BTree is identified by the index of its root page.  The
47488 ** key and data for any entry are combined to form the "payload".  A
47489 ** fixed amount of payload can be carried directly on the database
47490 ** page.  If the payload is larger than the preset amount then surplus
47491 ** bytes are stored on overflow pages.  The payload for an entry
47492 ** and the preceding pointer are combined to form a "Cell".  Each 
47493 ** page has a small header which contains the Ptr(N) pointer and other
47494 ** information such as the size of key and data.
47495 **
47496 ** FORMAT DETAILS
47497 **
47498 ** The file is divided into pages.  The first page is called page 1,
47499 ** the second is page 2, and so forth.  A page number of zero indicates
47500 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
47501 ** Each page can be either a btree page, a freelist page, an overflow
47502 ** page, or a pointer-map page.
47503 **
47504 ** The first page is always a btree page.  The first 100 bytes of the first
47505 ** page contain a special header (the "file header") that describes the file.
47506 ** The format of the file header is as follows:
47507 **
47508 **   OFFSET   SIZE    DESCRIPTION
47509 **      0      16     Header string: "SQLite format 3\000"
47510 **     16       2     Page size in bytes.  
47511 **     18       1     File format write version
47512 **     19       1     File format read version
47513 **     20       1     Bytes of unused space at the end of each page
47514 **     21       1     Max embedded payload fraction
47515 **     22       1     Min embedded payload fraction
47516 **     23       1     Min leaf payload fraction
47517 **     24       4     File change counter
47518 **     28       4     Reserved for future use
47519 **     32       4     First freelist page
47520 **     36       4     Number of freelist pages in the file
47521 **     40      60     15 4-byte meta values passed to higher layers
47522 **
47523 **     40       4     Schema cookie
47524 **     44       4     File format of schema layer
47525 **     48       4     Size of page cache
47526 **     52       4     Largest root-page (auto/incr_vacuum)
47527 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
47528 **     60       4     User version
47529 **     64       4     Incremental vacuum mode
47530 **     68       4     unused
47531 **     72       4     unused
47532 **     76       4     unused
47533 **
47534 ** All of the integer values are big-endian (most significant byte first).
47535 **
47536 ** The file change counter is incremented when the database is changed
47537 ** This counter allows other processes to know when the file has changed
47538 ** and thus when they need to flush their cache.
47539 **
47540 ** The max embedded payload fraction is the amount of the total usable
47541 ** space in a page that can be consumed by a single cell for standard
47542 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
47543 ** is to limit the maximum cell size so that at least 4 cells will fit
47544 ** on one page.  Thus the default max embedded payload fraction is 64.
47545 **
47546 ** If the payload for a cell is larger than the max payload, then extra
47547 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
47548 ** as many bytes as possible are moved into the overflow pages without letting
47549 ** the cell size drop below the min embedded payload fraction.
47550 **
47551 ** The min leaf payload fraction is like the min embedded payload fraction
47552 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
47553 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
47554 ** not specified in the header.
47555 **
47556 ** Each btree pages is divided into three sections:  The header, the
47557 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
47558 ** file header that occurs before the page header.
47559 **
47560 **      |----------------|
47561 **      | file header    |   100 bytes.  Page 1 only.
47562 **      |----------------|
47563 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
47564 **      |----------------|
47565 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
47566 **      | array          |   |  Grows downward
47567 **      |                |   v
47568 **      |----------------|
47569 **      | unallocated    |
47570 **      | space          |
47571 **      |----------------|   ^  Grows upwards
47572 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
47573 **      | area           |   |  and free space fragments.
47574 **      |----------------|
47575 **
47576 ** The page headers looks like this:
47577 **
47578 **   OFFSET   SIZE     DESCRIPTION
47579 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
47580 **      1       2      byte offset to the first freeblock
47581 **      3       2      number of cells on this page
47582 **      5       2      first byte of the cell content area
47583 **      7       1      number of fragmented free bytes
47584 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
47585 **
47586 ** The flags define the format of this btree page.  The leaf flag means that
47587 ** this page has no children.  The zerodata flag means that this page carries
47588 ** only keys and no data.  The intkey flag means that the key is a integer
47589 ** which is stored in the key size entry of the cell header rather than in
47590 ** the payload area.
47591 **
47592 ** The cell pointer array begins on the first byte after the page header.
47593 ** The cell pointer array contains zero or more 2-byte numbers which are
47594 ** offsets from the beginning of the page to the cell content in the cell
47595 ** content area.  The cell pointers occur in sorted order.  The system strives
47596 ** to keep free space after the last cell pointer so that new cells can
47597 ** be easily added without having to defragment the page.
47598 **
47599 ** Cell content is stored at the very end of the page and grows toward the
47600 ** beginning of the page.
47601 **
47602 ** Unused space within the cell content area is collected into a linked list of
47603 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
47604 ** to the first freeblock is given in the header.  Freeblocks occur in
47605 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
47606 ** any group of 3 or fewer unused bytes in the cell content area cannot
47607 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
47608 ** a fragment.  The total number of bytes in all fragments is recorded.
47609 ** in the page header at offset 7.
47610 **
47611 **    SIZE    DESCRIPTION
47612 **      2     Byte offset of the next freeblock
47613 **      2     Bytes in this freeblock
47614 **
47615 ** Cells are of variable length.  Cells are stored in the cell content area at
47616 ** the end of the page.  Pointers to the cells are in the cell pointer array
47617 ** that immediately follows the page header.  Cells is not necessarily
47618 ** contiguous or in order, but cell pointers are contiguous and in order.
47619 **
47620 ** Cell content makes use of variable length integers.  A variable
47621 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
47622 ** byte are used.  The integer consists of all bytes that have bit 8 set and
47623 ** the first byte with bit 8 clear.  The most significant byte of the integer
47624 ** appears first.  A variable-length integer may not be more than 9 bytes long.
47625 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
47626 ** allows a 64-bit integer to be encoded in 9 bytes.
47627 **
47628 **    0x00                      becomes  0x00000000
47629 **    0x7f                      becomes  0x0000007f
47630 **    0x81 0x00                 becomes  0x00000080
47631 **    0x82 0x00                 becomes  0x00000100
47632 **    0x80 0x7f                 becomes  0x0000007f
47633 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
47634 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
47635 **
47636 ** Variable length integers are used for rowids and to hold the number of
47637 ** bytes of key and data in a btree cell.
47638 **
47639 ** The content of a cell looks like this:
47640 **
47641 **    SIZE    DESCRIPTION
47642 **      4     Page number of the left child. Omitted if leaf flag is set.
47643 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
47644 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
47645 **      *     Payload
47646 **      4     First page of the overflow chain.  Omitted if no overflow
47647 **
47648 ** Overflow pages form a linked list.  Each page except the last is completely
47649 ** filled with data (pagesize - 4 bytes).  The last page can have as little
47650 ** as 1 byte of data.
47651 **
47652 **    SIZE    DESCRIPTION
47653 **      4     Page number of next overflow page
47654 **      *     Data
47655 **
47656 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
47657 ** file header points to the first in a linked list of trunk page.  Each trunk
47658 ** page points to multiple leaf pages.  The content of a leaf page is
47659 ** unspecified.  A trunk page looks like this:
47660 **
47661 **    SIZE    DESCRIPTION
47662 **      4     Page number of next trunk page
47663 **      4     Number of leaf pointers on this page
47664 **      *     zero or more pages numbers of leaves
47665 */
47666
47667
47668 /* The following value is the maximum cell size assuming a maximum page
47669 ** size give above.
47670 */
47671 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
47672
47673 /* The maximum number of cells on a single page of the database.  This
47674 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
47675 ** plus 2 bytes for the index to the cell in the page header).  Such
47676 ** small cells will be rare, but they are possible.
47677 */
47678 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
47679
47680 /* Forward declarations */
47681 typedef struct MemPage MemPage;
47682 typedef struct BtLock BtLock;
47683
47684 /*
47685 ** This is a magic string that appears at the beginning of every
47686 ** SQLite database in order to identify the file as a real database.
47687 **
47688 ** You can change this value at compile-time by specifying a
47689 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
47690 ** header must be exactly 16 bytes including the zero-terminator so
47691 ** the string itself should be 15 characters long.  If you change
47692 ** the header, then your custom library will not be able to read 
47693 ** databases generated by the standard tools and the standard tools
47694 ** will not be able to read databases created by your custom library.
47695 */
47696 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
47697 #  define SQLITE_FILE_HEADER "SQLite format 3"
47698 #endif
47699
47700 /*
47701 ** Page type flags.  An ORed combination of these flags appear as the
47702 ** first byte of on-disk image of every BTree page.
47703 */
47704 #define PTF_INTKEY    0x01
47705 #define PTF_ZERODATA  0x02
47706 #define PTF_LEAFDATA  0x04
47707 #define PTF_LEAF      0x08
47708
47709 /*
47710 ** As each page of the file is loaded into memory, an instance of the following
47711 ** structure is appended and initialized to zero.  This structure stores
47712 ** information about the page that is decoded from the raw file page.
47713 **
47714 ** The pParent field points back to the parent page.  This allows us to
47715 ** walk up the BTree from any leaf to the root.  Care must be taken to
47716 ** unref() the parent page pointer when this page is no longer referenced.
47717 ** The pageDestructor() routine handles that chore.
47718 **
47719 ** Access to all fields of this structure is controlled by the mutex
47720 ** stored in MemPage.pBt->mutex.
47721 */
47722 struct MemPage {
47723   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
47724   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
47725   u8 intKey;           /* True if intkey flag is set */
47726   u8 leaf;             /* True if leaf flag is set */
47727   u8 hasData;          /* True if this page stores data */
47728   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
47729   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
47730   u8 max1bytePayload;  /* min(maxLocal,127) */
47731   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
47732   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
47733   u16 cellOffset;      /* Index in aData of first cell pointer */
47734   u16 nFree;           /* Number of free bytes on the page */
47735   u16 nCell;           /* Number of cells on this page, local and ovfl */
47736   u16 maskPage;        /* Mask for page offset */
47737   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
47738                        ** non-overflow cell */
47739   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
47740   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
47741   u8 *aData;           /* Pointer to disk image of the page data */
47742   u8 *aDataEnd;        /* One byte past the end of usable data */
47743   u8 *aCellIdx;        /* The cell index area */
47744   DbPage *pDbPage;     /* Pager page handle */
47745   Pgno pgno;           /* Page number for this page */
47746 };
47747
47748 /*
47749 ** The in-memory image of a disk page has the auxiliary information appended
47750 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
47751 ** that extra information.
47752 */
47753 #define EXTRA_SIZE sizeof(MemPage)
47754
47755 /*
47756 ** A linked list of the following structures is stored at BtShared.pLock.
47757 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
47758 ** is opened on the table with root page BtShared.iTable. Locks are removed
47759 ** from this list when a transaction is committed or rolled back, or when
47760 ** a btree handle is closed.
47761 */
47762 struct BtLock {
47763   Btree *pBtree;        /* Btree handle holding this lock */
47764   Pgno iTable;          /* Root page of table */
47765   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
47766   BtLock *pNext;        /* Next in BtShared.pLock list */
47767 };
47768
47769 /* Candidate values for BtLock.eLock */
47770 #define READ_LOCK     1
47771 #define WRITE_LOCK    2
47772
47773 /* A Btree handle
47774 **
47775 ** A database connection contains a pointer to an instance of
47776 ** this object for every database file that it has open.  This structure
47777 ** is opaque to the database connection.  The database connection cannot
47778 ** see the internals of this structure and only deals with pointers to
47779 ** this structure.
47780 **
47781 ** For some database files, the same underlying database cache might be 
47782 ** shared between multiple connections.  In that case, each connection
47783 ** has it own instance of this object.  But each instance of this object
47784 ** points to the same BtShared object.  The database cache and the
47785 ** schema associated with the database file are all contained within
47786 ** the BtShared object.
47787 **
47788 ** All fields in this structure are accessed under sqlite3.mutex.
47789 ** The pBt pointer itself may not be changed while there exists cursors 
47790 ** in the referenced BtShared that point back to this Btree since those
47791 ** cursors have to go through this Btree to find their BtShared and
47792 ** they often do so without holding sqlite3.mutex.
47793 */
47794 struct Btree {
47795   sqlite3 *db;       /* The database connection holding this btree */
47796   BtShared *pBt;     /* Sharable content of this btree */
47797   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
47798   u8 sharable;       /* True if we can share pBt with another db */
47799   u8 locked;         /* True if db currently has pBt locked */
47800   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
47801   int nBackup;       /* Number of backup operations reading this btree */
47802   Btree *pNext;      /* List of other sharable Btrees from the same db */
47803   Btree *pPrev;      /* Back pointer of the same list */
47804 #ifndef SQLITE_OMIT_SHARED_CACHE
47805   BtLock lock;       /* Object used to lock page 1 */
47806 #endif
47807 };
47808
47809 /*
47810 ** Btree.inTrans may take one of the following values.
47811 **
47812 ** If the shared-data extension is enabled, there may be multiple users
47813 ** of the Btree structure. At most one of these may open a write transaction,
47814 ** but any number may have active read transactions.
47815 */
47816 #define TRANS_NONE  0
47817 #define TRANS_READ  1
47818 #define TRANS_WRITE 2
47819
47820 /*
47821 ** An instance of this object represents a single database file.
47822 ** 
47823 ** A single database file can be in use at the same time by two
47824 ** or more database connections.  When two or more connections are
47825 ** sharing the same database file, each connection has it own
47826 ** private Btree object for the file and each of those Btrees points
47827 ** to this one BtShared object.  BtShared.nRef is the number of
47828 ** connections currently sharing this database file.
47829 **
47830 ** Fields in this structure are accessed under the BtShared.mutex
47831 ** mutex, except for nRef and pNext which are accessed under the
47832 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
47833 ** may not be modified once it is initially set as long as nRef>0.
47834 ** The pSchema field may be set once under BtShared.mutex and
47835 ** thereafter is unchanged as long as nRef>0.
47836 **
47837 ** isPending:
47838 **
47839 **   If a BtShared client fails to obtain a write-lock on a database
47840 **   table (because there exists one or more read-locks on the table),
47841 **   the shared-cache enters 'pending-lock' state and isPending is
47842 **   set to true.
47843 **
47844 **   The shared-cache leaves the 'pending lock' state when either of
47845 **   the following occur:
47846 **
47847 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
47848 **     2) The number of locks held by other connections drops to zero.
47849 **
47850 **   while in the 'pending-lock' state, no connection may start a new
47851 **   transaction.
47852 **
47853 **   This feature is included to help prevent writer-starvation.
47854 */
47855 struct BtShared {
47856   Pager *pPager;        /* The page cache */
47857   sqlite3 *db;          /* Database connection currently using this Btree */
47858   BtCursor *pCursor;    /* A list of all open cursors */
47859   MemPage *pPage1;      /* First page of the database */
47860   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
47861 #ifndef SQLITE_OMIT_AUTOVACUUM
47862   u8 autoVacuum;        /* True if auto-vacuum is enabled */
47863   u8 incrVacuum;        /* True if incr-vacuum is enabled */
47864   u8 bDoTruncate;       /* True to truncate db on commit */
47865 #endif
47866   u8 inTransaction;     /* Transaction state */
47867   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
47868   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
47869   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
47870   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
47871   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
47872   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
47873   u32 pageSize;         /* Total number of bytes on a page */
47874   u32 usableSize;       /* Number of usable bytes on each page */
47875   int nTransaction;     /* Number of open transactions (read + write) */
47876   u32 nPage;            /* Number of pages in the database */
47877   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
47878   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
47879   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
47880   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
47881 #ifndef SQLITE_OMIT_SHARED_CACHE
47882   int nRef;             /* Number of references to this structure */
47883   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
47884   BtLock *pLock;        /* List of locks held on this shared-btree struct */
47885   Btree *pWriter;       /* Btree with currently open write transaction */
47886 #endif
47887   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
47888 };
47889
47890 /*
47891 ** Allowed values for BtShared.btsFlags
47892 */
47893 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
47894 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
47895 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
47896 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
47897 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
47898 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
47899 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
47900
47901 /*
47902 ** An instance of the following structure is used to hold information
47903 ** about a cell.  The parseCellPtr() function fills in this structure
47904 ** based on information extract from the raw disk page.
47905 */
47906 typedef struct CellInfo CellInfo;
47907 struct CellInfo {
47908   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
47909   u8 *pCell;     /* Pointer to the start of cell content */
47910   u32 nData;     /* Number of bytes of data */
47911   u32 nPayload;  /* Total amount of payload */
47912   u16 nHeader;   /* Size of the cell content header in bytes */
47913   u16 nLocal;    /* Amount of payload held locally */
47914   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
47915   u16 nSize;     /* Size of the cell content on the main b-tree page */
47916 };
47917
47918 /*
47919 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
47920 ** this will be declared corrupt. This value is calculated based on a
47921 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
47922 ** root-node and 3 for all other internal nodes.
47923 **
47924 ** If a tree that appears to be taller than this is encountered, it is
47925 ** assumed that the database is corrupt.
47926 */
47927 #define BTCURSOR_MAX_DEPTH 20
47928
47929 /*
47930 ** A cursor is a pointer to a particular entry within a particular
47931 ** b-tree within a database file.
47932 **
47933 ** The entry is identified by its MemPage and the index in
47934 ** MemPage.aCell[] of the entry.
47935 **
47936 ** A single database file can be shared by two more database connections,
47937 ** but cursors cannot be shared.  Each cursor is associated with a
47938 ** particular database connection identified BtCursor.pBtree.db.
47939 **
47940 ** Fields in this structure are accessed under the BtShared.mutex
47941 ** found at self->pBt->mutex. 
47942 */
47943 struct BtCursor {
47944   Btree *pBtree;            /* The Btree to which this cursor belongs */
47945   BtShared *pBt;            /* The BtShared this cursor points to */
47946   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
47947   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
47948 #ifndef SQLITE_OMIT_INCRBLOB
47949   Pgno *aOverflow;          /* Cache of overflow page locations */
47950 #endif
47951   Pgno pgnoRoot;            /* The root page of this tree */
47952   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
47953   CellInfo info;            /* A parse of the cell we are pointing at */
47954   i64 nKey;        /* Size of pKey, or last integer key */
47955   void *pKey;      /* Saved key that was cursor's last known position */
47956   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
47957   u8 wrFlag;                /* True if writable */
47958   u8 atLast;                /* Cursor pointing to the last entry */
47959   u8 validNKey;             /* True if info.nKey is valid */
47960   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
47961 #ifndef SQLITE_OMIT_INCRBLOB
47962   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
47963 #endif
47964   u8 hints;                             /* As configured by CursorSetHints() */
47965   i16 iPage;                            /* Index of current page in apPage */
47966   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
47967   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
47968 };
47969
47970 /*
47971 ** Potential values for BtCursor.eState.
47972 **
47973 ** CURSOR_VALID:
47974 **   Cursor points to a valid entry. getPayload() etc. may be called.
47975 **
47976 ** CURSOR_INVALID:
47977 **   Cursor does not point to a valid entry. This can happen (for example) 
47978 **   because the table is empty or because BtreeCursorFirst() has not been
47979 **   called.
47980 **
47981 ** CURSOR_REQUIRESEEK:
47982 **   The table that this cursor was opened on still exists, but has been 
47983 **   modified since the cursor was last used. The cursor position is saved
47984 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
47985 **   this state, restoreCursorPosition() can be called to attempt to
47986 **   seek the cursor to the saved position.
47987 **
47988 ** CURSOR_FAULT:
47989 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
47990 **   on a different connection that shares the BtShared cache with this
47991 **   cursor.  The error has left the cache in an inconsistent state.
47992 **   Do nothing else with this cursor.  Any attempt to use the cursor
47993 **   should return the error code stored in BtCursor.skip
47994 */
47995 #define CURSOR_INVALID           0
47996 #define CURSOR_VALID             1
47997 #define CURSOR_REQUIRESEEK       2
47998 #define CURSOR_FAULT             3
47999
48000 /* 
48001 ** The database page the PENDING_BYTE occupies. This page is never used.
48002 */
48003 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
48004
48005 /*
48006 ** These macros define the location of the pointer-map entry for a 
48007 ** database page. The first argument to each is the number of usable
48008 ** bytes on each page of the database (often 1024). The second is the
48009 ** page number to look up in the pointer map.
48010 **
48011 ** PTRMAP_PAGENO returns the database page number of the pointer-map
48012 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
48013 ** the offset of the requested map entry.
48014 **
48015 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
48016 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
48017 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
48018 ** this test.
48019 */
48020 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
48021 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
48022 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
48023
48024 /*
48025 ** The pointer map is a lookup table that identifies the parent page for
48026 ** each child page in the database file.  The parent page is the page that
48027 ** contains a pointer to the child.  Every page in the database contains
48028 ** 0 or 1 parent pages.  (In this context 'database page' refers
48029 ** to any page that is not part of the pointer map itself.)  Each pointer map
48030 ** entry consists of a single byte 'type' and a 4 byte parent page number.
48031 ** The PTRMAP_XXX identifiers below are the valid types.
48032 **
48033 ** The purpose of the pointer map is to facility moving pages from one
48034 ** position in the file to another as part of autovacuum.  When a page
48035 ** is moved, the pointer in its parent must be updated to point to the
48036 ** new location.  The pointer map is used to locate the parent page quickly.
48037 **
48038 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
48039 **                  used in this case.
48040 **
48041 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
48042 **                  is not used in this case.
48043 **
48044 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
48045 **                   overflow pages. The page number identifies the page that
48046 **                   contains the cell with a pointer to this overflow page.
48047 **
48048 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
48049 **                   overflow pages. The page-number identifies the previous
48050 **                   page in the overflow page list.
48051 **
48052 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
48053 **               identifies the parent page in the btree.
48054 */
48055 #define PTRMAP_ROOTPAGE 1
48056 #define PTRMAP_FREEPAGE 2
48057 #define PTRMAP_OVERFLOW1 3
48058 #define PTRMAP_OVERFLOW2 4
48059 #define PTRMAP_BTREE 5
48060
48061 /* A bunch of assert() statements to check the transaction state variables
48062 ** of handle p (type Btree*) are internally consistent.
48063 */
48064 #define btreeIntegrity(p) \
48065   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
48066   assert( p->pBt->inTransaction>=p->inTrans ); 
48067
48068
48069 /*
48070 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
48071 ** if the database supports auto-vacuum or not. Because it is used
48072 ** within an expression that is an argument to another macro 
48073 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
48074 ** So, this macro is defined instead.
48075 */
48076 #ifndef SQLITE_OMIT_AUTOVACUUM
48077 #define ISAUTOVACUUM (pBt->autoVacuum)
48078 #else
48079 #define ISAUTOVACUUM 0
48080 #endif
48081
48082
48083 /*
48084 ** This structure is passed around through all the sanity checking routines
48085 ** in order to keep track of some global state information.
48086 **
48087 ** The aRef[] array is allocated so that there is 1 bit for each page in
48088 ** the database. As the integrity-check proceeds, for each page used in
48089 ** the database the corresponding bit is set. This allows integrity-check to 
48090 ** detect pages that are used twice and orphaned pages (both of which 
48091 ** indicate corruption).
48092 */
48093 typedef struct IntegrityCk IntegrityCk;
48094 struct IntegrityCk {
48095   BtShared *pBt;    /* The tree being checked out */
48096   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
48097   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
48098   Pgno nPage;       /* Number of pages in the database */
48099   int mxErr;        /* Stop accumulating errors when this reaches zero */
48100   int nErr;         /* Number of messages written to zErrMsg so far */
48101   int mallocFailed; /* A memory allocation error has occurred */
48102   StrAccum errMsg;  /* Accumulate the error message text here */
48103 };
48104
48105 /*
48106 ** Routines to read or write a two- and four-byte big-endian integer values.
48107 */
48108 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
48109 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
48110 #define get4byte sqlite3Get4byte
48111 #define put4byte sqlite3Put4byte
48112
48113 /************** End of btreeInt.h ********************************************/
48114 /************** Continuing where we left off in btmutex.c ********************/
48115 #ifndef SQLITE_OMIT_SHARED_CACHE
48116 #if SQLITE_THREADSAFE
48117
48118 /*
48119 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
48120 ** set BtShared.db to the database handle associated with p and the
48121 ** p->locked boolean to true.
48122 */
48123 static void lockBtreeMutex(Btree *p){
48124   assert( p->locked==0 );
48125   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
48126   assert( sqlite3_mutex_held(p->db->mutex) );
48127
48128   sqlite3_mutex_enter(p->pBt->mutex);
48129   p->pBt->db = p->db;
48130   p->locked = 1;
48131 }
48132
48133 /*
48134 ** Release the BtShared mutex associated with B-Tree handle p and
48135 ** clear the p->locked boolean.
48136 */
48137 static void unlockBtreeMutex(Btree *p){
48138   BtShared *pBt = p->pBt;
48139   assert( p->locked==1 );
48140   assert( sqlite3_mutex_held(pBt->mutex) );
48141   assert( sqlite3_mutex_held(p->db->mutex) );
48142   assert( p->db==pBt->db );
48143
48144   sqlite3_mutex_leave(pBt->mutex);
48145   p->locked = 0;
48146 }
48147
48148 /*
48149 ** Enter a mutex on the given BTree object.
48150 **
48151 ** If the object is not sharable, then no mutex is ever required
48152 ** and this routine is a no-op.  The underlying mutex is non-recursive.
48153 ** But we keep a reference count in Btree.wantToLock so the behavior
48154 ** of this interface is recursive.
48155 **
48156 ** To avoid deadlocks, multiple Btrees are locked in the same order
48157 ** by all database connections.  The p->pNext is a list of other
48158 ** Btrees belonging to the same database connection as the p Btree
48159 ** which need to be locked after p.  If we cannot get a lock on
48160 ** p, then first unlock all of the others on p->pNext, then wait
48161 ** for the lock to become available on p, then relock all of the
48162 ** subsequent Btrees that desire a lock.
48163 */
48164 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
48165   Btree *pLater;
48166
48167   /* Some basic sanity checking on the Btree.  The list of Btrees
48168   ** connected by pNext and pPrev should be in sorted order by
48169   ** Btree.pBt value. All elements of the list should belong to
48170   ** the same connection. Only shared Btrees are on the list. */
48171   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
48172   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
48173   assert( p->pNext==0 || p->pNext->db==p->db );
48174   assert( p->pPrev==0 || p->pPrev->db==p->db );
48175   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
48176
48177   /* Check for locking consistency */
48178   assert( !p->locked || p->wantToLock>0 );
48179   assert( p->sharable || p->wantToLock==0 );
48180
48181   /* We should already hold a lock on the database connection */
48182   assert( sqlite3_mutex_held(p->db->mutex) );
48183
48184   /* Unless the database is sharable and unlocked, then BtShared.db
48185   ** should already be set correctly. */
48186   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
48187
48188   if( !p->sharable ) return;
48189   p->wantToLock++;
48190   if( p->locked ) return;
48191
48192   /* In most cases, we should be able to acquire the lock we
48193   ** want without having to go throught the ascending lock
48194   ** procedure that follows.  Just be sure not to block.
48195   */
48196   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
48197     p->pBt->db = p->db;
48198     p->locked = 1;
48199     return;
48200   }
48201
48202   /* To avoid deadlock, first release all locks with a larger
48203   ** BtShared address.  Then acquire our lock.  Then reacquire
48204   ** the other BtShared locks that we used to hold in ascending
48205   ** order.
48206   */
48207   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
48208     assert( pLater->sharable );
48209     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
48210     assert( !pLater->locked || pLater->wantToLock>0 );
48211     if( pLater->locked ){
48212       unlockBtreeMutex(pLater);
48213     }
48214   }
48215   lockBtreeMutex(p);
48216   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
48217     if( pLater->wantToLock ){
48218       lockBtreeMutex(pLater);
48219     }
48220   }
48221 }
48222
48223 /*
48224 ** Exit the recursive mutex on a Btree.
48225 */
48226 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
48227   if( p->sharable ){
48228     assert( p->wantToLock>0 );
48229     p->wantToLock--;
48230     if( p->wantToLock==0 ){
48231       unlockBtreeMutex(p);
48232     }
48233   }
48234 }
48235
48236 #ifndef NDEBUG
48237 /*
48238 ** Return true if the BtShared mutex is held on the btree, or if the
48239 ** B-Tree is not marked as sharable.
48240 **
48241 ** This routine is used only from within assert() statements.
48242 */
48243 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
48244   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
48245   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
48246   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
48247   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
48248
48249   return (p->sharable==0 || p->locked);
48250 }
48251 #endif
48252
48253
48254 #ifndef SQLITE_OMIT_INCRBLOB
48255 /*
48256 ** Enter and leave a mutex on a Btree given a cursor owned by that
48257 ** Btree.  These entry points are used by incremental I/O and can be
48258 ** omitted if that module is not used.
48259 */
48260 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
48261   sqlite3BtreeEnter(pCur->pBtree);
48262 }
48263 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
48264   sqlite3BtreeLeave(pCur->pBtree);
48265 }
48266 #endif /* SQLITE_OMIT_INCRBLOB */
48267
48268
48269 /*
48270 ** Enter the mutex on every Btree associated with a database
48271 ** connection.  This is needed (for example) prior to parsing
48272 ** a statement since we will be comparing table and column names
48273 ** against all schemas and we do not want those schemas being
48274 ** reset out from under us.
48275 **
48276 ** There is a corresponding leave-all procedures.
48277 **
48278 ** Enter the mutexes in accending order by BtShared pointer address
48279 ** to avoid the possibility of deadlock when two threads with
48280 ** two or more btrees in common both try to lock all their btrees
48281 ** at the same instant.
48282 */
48283 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
48284   int i;
48285   Btree *p;
48286   assert( sqlite3_mutex_held(db->mutex) );
48287   for(i=0; i<db->nDb; i++){
48288     p = db->aDb[i].pBt;
48289     if( p ) sqlite3BtreeEnter(p);
48290   }
48291 }
48292 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
48293   int i;
48294   Btree *p;
48295   assert( sqlite3_mutex_held(db->mutex) );
48296   for(i=0; i<db->nDb; i++){
48297     p = db->aDb[i].pBt;
48298     if( p ) sqlite3BtreeLeave(p);
48299   }
48300 }
48301
48302 /*
48303 ** Return true if a particular Btree requires a lock.  Return FALSE if
48304 ** no lock is ever required since it is not sharable.
48305 */
48306 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
48307   return p->sharable;
48308 }
48309
48310 #ifndef NDEBUG
48311 /*
48312 ** Return true if the current thread holds the database connection
48313 ** mutex and all required BtShared mutexes.
48314 **
48315 ** This routine is used inside assert() statements only.
48316 */
48317 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
48318   int i;
48319   if( !sqlite3_mutex_held(db->mutex) ){
48320     return 0;
48321   }
48322   for(i=0; i<db->nDb; i++){
48323     Btree *p;
48324     p = db->aDb[i].pBt;
48325     if( p && p->sharable &&
48326          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
48327       return 0;
48328     }
48329   }
48330   return 1;
48331 }
48332 #endif /* NDEBUG */
48333
48334 #ifndef NDEBUG
48335 /*
48336 ** Return true if the correct mutexes are held for accessing the
48337 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
48338 ** access are:
48339 **
48340 **   (1) The mutex on db
48341 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
48342 **
48343 ** If pSchema is not NULL, then iDb is computed from pSchema and
48344 ** db using sqlite3SchemaToIndex().
48345 */
48346 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
48347   Btree *p;
48348   assert( db!=0 );
48349   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
48350   assert( iDb>=0 && iDb<db->nDb );
48351   if( !sqlite3_mutex_held(db->mutex) ) return 0;
48352   if( iDb==1 ) return 1;
48353   p = db->aDb[iDb].pBt;
48354   assert( p!=0 );
48355   return p->sharable==0 || p->locked==1;
48356 }
48357 #endif /* NDEBUG */
48358
48359 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
48360 /*
48361 ** The following are special cases for mutex enter routines for use
48362 ** in single threaded applications that use shared cache.  Except for
48363 ** these two routines, all mutex operations are no-ops in that case and
48364 ** are null #defines in btree.h.
48365 **
48366 ** If shared cache is disabled, then all btree mutex routines, including
48367 ** the ones below, are no-ops and are null #defines in btree.h.
48368 */
48369
48370 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
48371   p->pBt->db = p->db;
48372 }
48373 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
48374   int i;
48375   for(i=0; i<db->nDb; i++){
48376     Btree *p = db->aDb[i].pBt;
48377     if( p ){
48378       p->pBt->db = p->db;
48379     }
48380   }
48381 }
48382 #endif /* if SQLITE_THREADSAFE */
48383 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
48384
48385 /************** End of btmutex.c *********************************************/
48386 /************** Begin file btree.c *******************************************/
48387 /*
48388 ** 2004 April 6
48389 **
48390 ** The author disclaims copyright to this source code.  In place of
48391 ** a legal notice, here is a blessing:
48392 **
48393 **    May you do good and not evil.
48394 **    May you find forgiveness for yourself and forgive others.
48395 **    May you share freely, never taking more than you give.
48396 **
48397 *************************************************************************
48398 ** This file implements a external (disk-based) database using BTrees.
48399 ** See the header comment on "btreeInt.h" for additional information.
48400 ** Including a description of file format and an overview of operation.
48401 */
48402
48403 /*
48404 ** The header string that appears at the beginning of every
48405 ** SQLite database.
48406 */
48407 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
48408
48409 /*
48410 ** Set this global variable to 1 to enable tracing using the TRACE
48411 ** macro.
48412 */
48413 #if 0
48414 int sqlite3BtreeTrace=1;  /* True to enable tracing */
48415 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
48416 #else
48417 # define TRACE(X)
48418 #endif
48419
48420 /*
48421 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
48422 ** But if the value is zero, make it 65536.
48423 **
48424 ** This routine is used to extract the "offset to cell content area" value
48425 ** from the header of a btree page.  If the page size is 65536 and the page
48426 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
48427 ** This routine makes the necessary adjustment to 65536.
48428 */
48429 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
48430
48431 /*
48432 ** Values passed as the 5th argument to allocateBtreePage()
48433 */
48434 #define BTALLOC_ANY   0           /* Allocate any page */
48435 #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
48436 #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
48437
48438 /*
48439 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not 
48440 ** defined, or 0 if it is. For example:
48441 **
48442 **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
48443 */
48444 #ifndef SQLITE_OMIT_AUTOVACUUM
48445 #define IfNotOmitAV(expr) (expr)
48446 #else
48447 #define IfNotOmitAV(expr) 0
48448 #endif
48449
48450 #ifndef SQLITE_OMIT_SHARED_CACHE
48451 /*
48452 ** A list of BtShared objects that are eligible for participation
48453 ** in shared cache.  This variable has file scope during normal builds,
48454 ** but the test harness needs to access it so we make it global for 
48455 ** test builds.
48456 **
48457 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
48458 */
48459 #ifdef SQLITE_TEST
48460 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
48461 #else
48462 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
48463 #endif
48464 #endif /* SQLITE_OMIT_SHARED_CACHE */
48465
48466 #ifndef SQLITE_OMIT_SHARED_CACHE
48467 /*
48468 ** Enable or disable the shared pager and schema features.
48469 **
48470 ** This routine has no effect on existing database connections.
48471 ** The shared cache setting effects only future calls to
48472 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
48473 */
48474 SQLITE_API int sqlite3_enable_shared_cache(int enable){
48475   sqlite3GlobalConfig.sharedCacheEnabled = enable;
48476   return SQLITE_OK;
48477 }
48478 #endif
48479
48480
48481
48482 #ifdef SQLITE_OMIT_SHARED_CACHE
48483   /*
48484   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
48485   ** and clearAllSharedCacheTableLocks()
48486   ** manipulate entries in the BtShared.pLock linked list used to store
48487   ** shared-cache table level locks. If the library is compiled with the
48488   ** shared-cache feature disabled, then there is only ever one user
48489   ** of each BtShared structure and so this locking is not necessary. 
48490   ** So define the lock related functions as no-ops.
48491   */
48492   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
48493   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
48494   #define clearAllSharedCacheTableLocks(a)
48495   #define downgradeAllSharedCacheTableLocks(a)
48496   #define hasSharedCacheTableLock(a,b,c,d) 1
48497   #define hasReadConflicts(a, b) 0
48498 #endif
48499
48500 #ifndef SQLITE_OMIT_SHARED_CACHE
48501
48502 #ifdef SQLITE_DEBUG
48503 /*
48504 **** This function is only used as part of an assert() statement. ***
48505 **
48506 ** Check to see if pBtree holds the required locks to read or write to the 
48507 ** table with root page iRoot.   Return 1 if it does and 0 if not.
48508 **
48509 ** For example, when writing to a table with root-page iRoot via 
48510 ** Btree connection pBtree:
48511 **
48512 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
48513 **
48514 ** When writing to an index that resides in a sharable database, the 
48515 ** caller should have first obtained a lock specifying the root page of
48516 ** the corresponding table. This makes things a bit more complicated,
48517 ** as this module treats each table as a separate structure. To determine
48518 ** the table corresponding to the index being written, this
48519 ** function has to search through the database schema.
48520 **
48521 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
48522 ** hold a write-lock on the schema table (root page 1). This is also
48523 ** acceptable.
48524 */
48525 static int hasSharedCacheTableLock(
48526   Btree *pBtree,         /* Handle that must hold lock */
48527   Pgno iRoot,            /* Root page of b-tree */
48528   int isIndex,           /* True if iRoot is the root of an index b-tree */
48529   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
48530 ){
48531   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
48532   Pgno iTab = 0;
48533   BtLock *pLock;
48534
48535   /* If this database is not shareable, or if the client is reading
48536   ** and has the read-uncommitted flag set, then no lock is required. 
48537   ** Return true immediately.
48538   */
48539   if( (pBtree->sharable==0)
48540    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
48541   ){
48542     return 1;
48543   }
48544
48545   /* If the client is reading  or writing an index and the schema is
48546   ** not loaded, then it is too difficult to actually check to see if
48547   ** the correct locks are held.  So do not bother - just return true.
48548   ** This case does not come up very often anyhow.
48549   */
48550   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
48551     return 1;
48552   }
48553
48554   /* Figure out the root-page that the lock should be held on. For table
48555   ** b-trees, this is just the root page of the b-tree being read or
48556   ** written. For index b-trees, it is the root page of the associated
48557   ** table.  */
48558   if( isIndex ){
48559     HashElem *p;
48560     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
48561       Index *pIdx = (Index *)sqliteHashData(p);
48562       if( pIdx->tnum==(int)iRoot ){
48563         iTab = pIdx->pTable->tnum;
48564       }
48565     }
48566   }else{
48567     iTab = iRoot;
48568   }
48569
48570   /* Search for the required lock. Either a write-lock on root-page iTab, a 
48571   ** write-lock on the schema table, or (if the client is reading) a
48572   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
48573   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
48574     if( pLock->pBtree==pBtree 
48575      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
48576      && pLock->eLock>=eLockType 
48577     ){
48578       return 1;
48579     }
48580   }
48581
48582   /* Failed to find the required lock. */
48583   return 0;
48584 }
48585 #endif /* SQLITE_DEBUG */
48586
48587 #ifdef SQLITE_DEBUG
48588 /*
48589 **** This function may be used as part of assert() statements only. ****
48590 **
48591 ** Return true if it would be illegal for pBtree to write into the
48592 ** table or index rooted at iRoot because other shared connections are
48593 ** simultaneously reading that same table or index.
48594 **
48595 ** It is illegal for pBtree to write if some other Btree object that
48596 ** shares the same BtShared object is currently reading or writing
48597 ** the iRoot table.  Except, if the other Btree object has the
48598 ** read-uncommitted flag set, then it is OK for the other object to
48599 ** have a read cursor.
48600 **
48601 ** For example, before writing to any part of the table or index
48602 ** rooted at page iRoot, one should call:
48603 **
48604 **    assert( !hasReadConflicts(pBtree, iRoot) );
48605 */
48606 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
48607   BtCursor *p;
48608   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
48609     if( p->pgnoRoot==iRoot 
48610      && p->pBtree!=pBtree
48611      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
48612     ){
48613       return 1;
48614     }
48615   }
48616   return 0;
48617 }
48618 #endif    /* #ifdef SQLITE_DEBUG */
48619
48620 /*
48621 ** Query to see if Btree handle p may obtain a lock of type eLock 
48622 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
48623 ** SQLITE_OK if the lock may be obtained (by calling
48624 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
48625 */
48626 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
48627   BtShared *pBt = p->pBt;
48628   BtLock *pIter;
48629
48630   assert( sqlite3BtreeHoldsMutex(p) );
48631   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
48632   assert( p->db!=0 );
48633   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
48634   
48635   /* If requesting a write-lock, then the Btree must have an open write
48636   ** transaction on this file. And, obviously, for this to be so there 
48637   ** must be an open write transaction on the file itself.
48638   */
48639   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
48640   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
48641   
48642   /* This routine is a no-op if the shared-cache is not enabled */
48643   if( !p->sharable ){
48644     return SQLITE_OK;
48645   }
48646
48647   /* If some other connection is holding an exclusive lock, the
48648   ** requested lock may not be obtained.
48649   */
48650   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
48651     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
48652     return SQLITE_LOCKED_SHAREDCACHE;
48653   }
48654
48655   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48656     /* The condition (pIter->eLock!=eLock) in the following if(...) 
48657     ** statement is a simplification of:
48658     **
48659     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
48660     **
48661     ** since we know that if eLock==WRITE_LOCK, then no other connection
48662     ** may hold a WRITE_LOCK on any table in this file (since there can
48663     ** only be a single writer).
48664     */
48665     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
48666     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
48667     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
48668       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
48669       if( eLock==WRITE_LOCK ){
48670         assert( p==pBt->pWriter );
48671         pBt->btsFlags |= BTS_PENDING;
48672       }
48673       return SQLITE_LOCKED_SHAREDCACHE;
48674     }
48675   }
48676   return SQLITE_OK;
48677 }
48678 #endif /* !SQLITE_OMIT_SHARED_CACHE */
48679
48680 #ifndef SQLITE_OMIT_SHARED_CACHE
48681 /*
48682 ** Add a lock on the table with root-page iTable to the shared-btree used
48683 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
48684 ** WRITE_LOCK.
48685 **
48686 ** This function assumes the following:
48687 **
48688 **   (a) The specified Btree object p is connected to a sharable
48689 **       database (one with the BtShared.sharable flag set), and
48690 **
48691 **   (b) No other Btree objects hold a lock that conflicts
48692 **       with the requested lock (i.e. querySharedCacheTableLock() has
48693 **       already been called and returned SQLITE_OK).
48694 **
48695 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
48696 ** is returned if a malloc attempt fails.
48697 */
48698 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
48699   BtShared *pBt = p->pBt;
48700   BtLock *pLock = 0;
48701   BtLock *pIter;
48702
48703   assert( sqlite3BtreeHoldsMutex(p) );
48704   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
48705   assert( p->db!=0 );
48706
48707   /* A connection with the read-uncommitted flag set will never try to
48708   ** obtain a read-lock using this function. The only read-lock obtained
48709   ** by a connection in read-uncommitted mode is on the sqlite_master 
48710   ** table, and that lock is obtained in BtreeBeginTrans().  */
48711   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
48712
48713   /* This function should only be called on a sharable b-tree after it 
48714   ** has been determined that no other b-tree holds a conflicting lock.  */
48715   assert( p->sharable );
48716   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
48717
48718   /* First search the list for an existing lock on this table. */
48719   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48720     if( pIter->iTable==iTable && pIter->pBtree==p ){
48721       pLock = pIter;
48722       break;
48723     }
48724   }
48725
48726   /* If the above search did not find a BtLock struct associating Btree p
48727   ** with table iTable, allocate one and link it into the list.
48728   */
48729   if( !pLock ){
48730     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
48731     if( !pLock ){
48732       return SQLITE_NOMEM;
48733     }
48734     pLock->iTable = iTable;
48735     pLock->pBtree = p;
48736     pLock->pNext = pBt->pLock;
48737     pBt->pLock = pLock;
48738   }
48739
48740   /* Set the BtLock.eLock variable to the maximum of the current lock
48741   ** and the requested lock. This means if a write-lock was already held
48742   ** and a read-lock requested, we don't incorrectly downgrade the lock.
48743   */
48744   assert( WRITE_LOCK>READ_LOCK );
48745   if( eLock>pLock->eLock ){
48746     pLock->eLock = eLock;
48747   }
48748
48749   return SQLITE_OK;
48750 }
48751 #endif /* !SQLITE_OMIT_SHARED_CACHE */
48752
48753 #ifndef SQLITE_OMIT_SHARED_CACHE
48754 /*
48755 ** Release all the table locks (locks obtained via calls to
48756 ** the setSharedCacheTableLock() procedure) held by Btree object p.
48757 **
48758 ** This function assumes that Btree p has an open read or write 
48759 ** transaction. If it does not, then the BTS_PENDING flag
48760 ** may be incorrectly cleared.
48761 */
48762 static void clearAllSharedCacheTableLocks(Btree *p){
48763   BtShared *pBt = p->pBt;
48764   BtLock **ppIter = &pBt->pLock;
48765
48766   assert( sqlite3BtreeHoldsMutex(p) );
48767   assert( p->sharable || 0==*ppIter );
48768   assert( p->inTrans>0 );
48769
48770   while( *ppIter ){
48771     BtLock *pLock = *ppIter;
48772     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
48773     assert( pLock->pBtree->inTrans>=pLock->eLock );
48774     if( pLock->pBtree==p ){
48775       *ppIter = pLock->pNext;
48776       assert( pLock->iTable!=1 || pLock==&p->lock );
48777       if( pLock->iTable!=1 ){
48778         sqlite3_free(pLock);
48779       }
48780     }else{
48781       ppIter = &pLock->pNext;
48782     }
48783   }
48784
48785   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
48786   if( pBt->pWriter==p ){
48787     pBt->pWriter = 0;
48788     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
48789   }else if( pBt->nTransaction==2 ){
48790     /* This function is called when Btree p is concluding its 
48791     ** transaction. If there currently exists a writer, and p is not
48792     ** that writer, then the number of locks held by connections other
48793     ** than the writer must be about to drop to zero. In this case
48794     ** set the BTS_PENDING flag to 0.
48795     **
48796     ** If there is not currently a writer, then BTS_PENDING must
48797     ** be zero already. So this next line is harmless in that case.
48798     */
48799     pBt->btsFlags &= ~BTS_PENDING;
48800   }
48801 }
48802
48803 /*
48804 ** This function changes all write-locks held by Btree p into read-locks.
48805 */
48806 static void downgradeAllSharedCacheTableLocks(Btree *p){
48807   BtShared *pBt = p->pBt;
48808   if( pBt->pWriter==p ){
48809     BtLock *pLock;
48810     pBt->pWriter = 0;
48811     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
48812     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
48813       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
48814       pLock->eLock = READ_LOCK;
48815     }
48816   }
48817 }
48818
48819 #endif /* SQLITE_OMIT_SHARED_CACHE */
48820
48821 static void releasePage(MemPage *pPage);  /* Forward reference */
48822
48823 /*
48824 ***** This routine is used inside of assert() only ****
48825 **
48826 ** Verify that the cursor holds the mutex on its BtShared
48827 */
48828 #ifdef SQLITE_DEBUG
48829 static int cursorHoldsMutex(BtCursor *p){
48830   return sqlite3_mutex_held(p->pBt->mutex);
48831 }
48832 #endif
48833
48834
48835 #ifndef SQLITE_OMIT_INCRBLOB
48836 /*
48837 ** Invalidate the overflow page-list cache for cursor pCur, if any.
48838 */
48839 static void invalidateOverflowCache(BtCursor *pCur){
48840   assert( cursorHoldsMutex(pCur) );
48841   sqlite3_free(pCur->aOverflow);
48842   pCur->aOverflow = 0;
48843 }
48844
48845 /*
48846 ** Invalidate the overflow page-list cache for all cursors opened
48847 ** on the shared btree structure pBt.
48848 */
48849 static void invalidateAllOverflowCache(BtShared *pBt){
48850   BtCursor *p;
48851   assert( sqlite3_mutex_held(pBt->mutex) );
48852   for(p=pBt->pCursor; p; p=p->pNext){
48853     invalidateOverflowCache(p);
48854   }
48855 }
48856
48857 /*
48858 ** This function is called before modifying the contents of a table
48859 ** to invalidate any incrblob cursors that are open on the
48860 ** row or one of the rows being modified.
48861 **
48862 ** If argument isClearTable is true, then the entire contents of the
48863 ** table is about to be deleted. In this case invalidate all incrblob
48864 ** cursors open on any row within the table with root-page pgnoRoot.
48865 **
48866 ** Otherwise, if argument isClearTable is false, then the row with
48867 ** rowid iRow is being replaced or deleted. In this case invalidate
48868 ** only those incrblob cursors open on that specific row.
48869 */
48870 static void invalidateIncrblobCursors(
48871   Btree *pBtree,          /* The database file to check */
48872   i64 iRow,               /* The rowid that might be changing */
48873   int isClearTable        /* True if all rows are being deleted */
48874 ){
48875   BtCursor *p;
48876   BtShared *pBt = pBtree->pBt;
48877   assert( sqlite3BtreeHoldsMutex(pBtree) );
48878   for(p=pBt->pCursor; p; p=p->pNext){
48879     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
48880       p->eState = CURSOR_INVALID;
48881     }
48882   }
48883 }
48884
48885 #else
48886   /* Stub functions when INCRBLOB is omitted */
48887   #define invalidateOverflowCache(x)
48888   #define invalidateAllOverflowCache(x)
48889   #define invalidateIncrblobCursors(x,y,z)
48890 #endif /* SQLITE_OMIT_INCRBLOB */
48891
48892 /*
48893 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
48894 ** when a page that previously contained data becomes a free-list leaf 
48895 ** page.
48896 **
48897 ** The BtShared.pHasContent bitvec exists to work around an obscure
48898 ** bug caused by the interaction of two useful IO optimizations surrounding
48899 ** free-list leaf pages:
48900 **
48901 **   1) When all data is deleted from a page and the page becomes
48902 **      a free-list leaf page, the page is not written to the database
48903 **      (as free-list leaf pages contain no meaningful data). Sometimes
48904 **      such a page is not even journalled (as it will not be modified,
48905 **      why bother journalling it?).
48906 **
48907 **   2) When a free-list leaf page is reused, its content is not read
48908 **      from the database or written to the journal file (why should it
48909 **      be, if it is not at all meaningful?).
48910 **
48911 ** By themselves, these optimizations work fine and provide a handy
48912 ** performance boost to bulk delete or insert operations. However, if
48913 ** a page is moved to the free-list and then reused within the same
48914 ** transaction, a problem comes up. If the page is not journalled when
48915 ** it is moved to the free-list and it is also not journalled when it
48916 ** is extracted from the free-list and reused, then the original data
48917 ** may be lost. In the event of a rollback, it may not be possible
48918 ** to restore the database to its original configuration.
48919 **
48920 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
48921 ** moved to become a free-list leaf page, the corresponding bit is
48922 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
48923 ** optimization 2 above is omitted if the corresponding bit is already
48924 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
48925 ** at the end of every transaction.
48926 */
48927 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
48928   int rc = SQLITE_OK;
48929   if( !pBt->pHasContent ){
48930     assert( pgno<=pBt->nPage );
48931     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
48932     if( !pBt->pHasContent ){
48933       rc = SQLITE_NOMEM;
48934     }
48935   }
48936   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
48937     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
48938   }
48939   return rc;
48940 }
48941
48942 /*
48943 ** Query the BtShared.pHasContent vector.
48944 **
48945 ** This function is called when a free-list leaf page is removed from the
48946 ** free-list for reuse. It returns false if it is safe to retrieve the
48947 ** page from the pager layer with the 'no-content' flag set. True otherwise.
48948 */
48949 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
48950   Bitvec *p = pBt->pHasContent;
48951   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
48952 }
48953
48954 /*
48955 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
48956 ** invoked at the conclusion of each write-transaction.
48957 */
48958 static void btreeClearHasContent(BtShared *pBt){
48959   sqlite3BitvecDestroy(pBt->pHasContent);
48960   pBt->pHasContent = 0;
48961 }
48962
48963 /*
48964 ** Release all of the apPage[] pages for a cursor.
48965 */
48966 static void btreeReleaseAllCursorPages(BtCursor *pCur){
48967   int i;
48968   for(i=0; i<=pCur->iPage; i++){
48969     releasePage(pCur->apPage[i]);
48970     pCur->apPage[i] = 0;
48971   }
48972   pCur->iPage = -1;
48973 }
48974
48975
48976 /*
48977 ** Save the current cursor position in the variables BtCursor.nKey 
48978 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
48979 **
48980 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
48981 ** prior to calling this routine.  
48982 */
48983 static int saveCursorPosition(BtCursor *pCur){
48984   int rc;
48985
48986   assert( CURSOR_VALID==pCur->eState );
48987   assert( 0==pCur->pKey );
48988   assert( cursorHoldsMutex(pCur) );
48989
48990   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
48991   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
48992
48993   /* If this is an intKey table, then the above call to BtreeKeySize()
48994   ** stores the integer key in pCur->nKey. In this case this value is
48995   ** all that is required. Otherwise, if pCur is not open on an intKey
48996   ** table, then malloc space for and store the pCur->nKey bytes of key 
48997   ** data.
48998   */
48999   if( 0==pCur->apPage[0]->intKey ){
49000     void *pKey = sqlite3Malloc( (int)pCur->nKey );
49001     if( pKey ){
49002       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
49003       if( rc==SQLITE_OK ){
49004         pCur->pKey = pKey;
49005       }else{
49006         sqlite3_free(pKey);
49007       }
49008     }else{
49009       rc = SQLITE_NOMEM;
49010     }
49011   }
49012   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
49013
49014   if( rc==SQLITE_OK ){
49015     btreeReleaseAllCursorPages(pCur);
49016     pCur->eState = CURSOR_REQUIRESEEK;
49017   }
49018
49019   invalidateOverflowCache(pCur);
49020   return rc;
49021 }
49022
49023 /*
49024 ** Save the positions of all cursors (except pExcept) that are open on
49025 ** the table  with root-page iRoot. Usually, this is called just before cursor
49026 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
49027 */
49028 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
49029   BtCursor *p;
49030   assert( sqlite3_mutex_held(pBt->mutex) );
49031   assert( pExcept==0 || pExcept->pBt==pBt );
49032   for(p=pBt->pCursor; p; p=p->pNext){
49033     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
49034       if( p->eState==CURSOR_VALID ){
49035         int rc = saveCursorPosition(p);
49036         if( SQLITE_OK!=rc ){
49037           return rc;
49038         }
49039       }else{
49040         testcase( p->iPage>0 );
49041         btreeReleaseAllCursorPages(p);
49042       }
49043     }
49044   }
49045   return SQLITE_OK;
49046 }
49047
49048 /*
49049 ** Clear the current cursor position.
49050 */
49051 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
49052   assert( cursorHoldsMutex(pCur) );
49053   sqlite3_free(pCur->pKey);
49054   pCur->pKey = 0;
49055   pCur->eState = CURSOR_INVALID;
49056 }
49057
49058 /*
49059 ** In this version of BtreeMoveto, pKey is a packed index record
49060 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
49061 ** record and then call BtreeMovetoUnpacked() to do the work.
49062 */
49063 static int btreeMoveto(
49064   BtCursor *pCur,     /* Cursor open on the btree to be searched */
49065   const void *pKey,   /* Packed key if the btree is an index */
49066   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
49067   int bias,           /* Bias search to the high end */
49068   int *pRes           /* Write search results here */
49069 ){
49070   int rc;                    /* Status code */
49071   UnpackedRecord *pIdxKey;   /* Unpacked index key */
49072   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
49073   char *pFree = 0;
49074
49075   if( pKey ){
49076     assert( nKey==(i64)(int)nKey );
49077     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
49078         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
49079     );
49080     if( pIdxKey==0 ) return SQLITE_NOMEM;
49081     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
49082   }else{
49083     pIdxKey = 0;
49084   }
49085   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
49086   if( pFree ){
49087     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
49088   }
49089   return rc;
49090 }
49091
49092 /*
49093 ** Restore the cursor to the position it was in (or as close to as possible)
49094 ** when saveCursorPosition() was called. Note that this call deletes the 
49095 ** saved position info stored by saveCursorPosition(), so there can be
49096 ** at most one effective restoreCursorPosition() call after each 
49097 ** saveCursorPosition().
49098 */
49099 static int btreeRestoreCursorPosition(BtCursor *pCur){
49100   int rc;
49101   assert( cursorHoldsMutex(pCur) );
49102   assert( pCur->eState>=CURSOR_REQUIRESEEK );
49103   if( pCur->eState==CURSOR_FAULT ){
49104     return pCur->skipNext;
49105   }
49106   pCur->eState = CURSOR_INVALID;
49107   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
49108   if( rc==SQLITE_OK ){
49109     sqlite3_free(pCur->pKey);
49110     pCur->pKey = 0;
49111     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
49112   }
49113   return rc;
49114 }
49115
49116 #define restoreCursorPosition(p) \
49117   (p->eState>=CURSOR_REQUIRESEEK ? \
49118          btreeRestoreCursorPosition(p) : \
49119          SQLITE_OK)
49120
49121 /*
49122 ** Determine whether or not a cursor has moved from the position it
49123 ** was last placed at.  Cursors can move when the row they are pointing
49124 ** at is deleted out from under them.
49125 **
49126 ** This routine returns an error code if something goes wrong.  The
49127 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
49128 */
49129 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
49130   int rc;
49131
49132   rc = restoreCursorPosition(pCur);
49133   if( rc ){
49134     *pHasMoved = 1;
49135     return rc;
49136   }
49137   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
49138     *pHasMoved = 1;
49139   }else{
49140     *pHasMoved = 0;
49141   }
49142   return SQLITE_OK;
49143 }
49144
49145 #ifndef SQLITE_OMIT_AUTOVACUUM
49146 /*
49147 ** Given a page number of a regular database page, return the page
49148 ** number for the pointer-map page that contains the entry for the
49149 ** input page number.
49150 **
49151 ** Return 0 (not a valid page) for pgno==1 since there is
49152 ** no pointer map associated with page 1.  The integrity_check logic
49153 ** requires that ptrmapPageno(*,1)!=1.
49154 */
49155 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
49156   int nPagesPerMapPage;
49157   Pgno iPtrMap, ret;
49158   assert( sqlite3_mutex_held(pBt->mutex) );
49159   if( pgno<2 ) return 0;
49160   nPagesPerMapPage = (pBt->usableSize/5)+1;
49161   iPtrMap = (pgno-2)/nPagesPerMapPage;
49162   ret = (iPtrMap*nPagesPerMapPage) + 2; 
49163   if( ret==PENDING_BYTE_PAGE(pBt) ){
49164     ret++;
49165   }
49166   return ret;
49167 }
49168
49169 /*
49170 ** Write an entry into the pointer map.
49171 **
49172 ** This routine updates the pointer map entry for page number 'key'
49173 ** so that it maps to type 'eType' and parent page number 'pgno'.
49174 **
49175 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
49176 ** a no-op.  If an error occurs, the appropriate error code is written
49177 ** into *pRC.
49178 */
49179 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
49180   DbPage *pDbPage;  /* The pointer map page */
49181   u8 *pPtrmap;      /* The pointer map data */
49182   Pgno iPtrmap;     /* The pointer map page number */
49183   int offset;       /* Offset in pointer map page */
49184   int rc;           /* Return code from subfunctions */
49185
49186   if( *pRC ) return;
49187
49188   assert( sqlite3_mutex_held(pBt->mutex) );
49189   /* The master-journal page number must never be used as a pointer map page */
49190   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
49191
49192   assert( pBt->autoVacuum );
49193   if( key==0 ){
49194     *pRC = SQLITE_CORRUPT_BKPT;
49195     return;
49196   }
49197   iPtrmap = PTRMAP_PAGENO(pBt, key);
49198   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
49199   if( rc!=SQLITE_OK ){
49200     *pRC = rc;
49201     return;
49202   }
49203   offset = PTRMAP_PTROFFSET(iPtrmap, key);
49204   if( offset<0 ){
49205     *pRC = SQLITE_CORRUPT_BKPT;
49206     goto ptrmap_exit;
49207   }
49208   assert( offset <= (int)pBt->usableSize-5 );
49209   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
49210
49211   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
49212     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
49213     *pRC= rc = sqlite3PagerWrite(pDbPage);
49214     if( rc==SQLITE_OK ){
49215       pPtrmap[offset] = eType;
49216       put4byte(&pPtrmap[offset+1], parent);
49217     }
49218   }
49219
49220 ptrmap_exit:
49221   sqlite3PagerUnref(pDbPage);
49222 }
49223
49224 /*
49225 ** Read an entry from the pointer map.
49226 **
49227 ** This routine retrieves the pointer map entry for page 'key', writing
49228 ** the type and parent page number to *pEType and *pPgno respectively.
49229 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
49230 */
49231 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
49232   DbPage *pDbPage;   /* The pointer map page */
49233   int iPtrmap;       /* Pointer map page index */
49234   u8 *pPtrmap;       /* Pointer map page data */
49235   int offset;        /* Offset of entry in pointer map */
49236   int rc;
49237
49238   assert( sqlite3_mutex_held(pBt->mutex) );
49239
49240   iPtrmap = PTRMAP_PAGENO(pBt, key);
49241   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
49242   if( rc!=0 ){
49243     return rc;
49244   }
49245   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
49246
49247   offset = PTRMAP_PTROFFSET(iPtrmap, key);
49248   if( offset<0 ){
49249     sqlite3PagerUnref(pDbPage);
49250     return SQLITE_CORRUPT_BKPT;
49251   }
49252   assert( offset <= (int)pBt->usableSize-5 );
49253   assert( pEType!=0 );
49254   *pEType = pPtrmap[offset];
49255   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
49256
49257   sqlite3PagerUnref(pDbPage);
49258   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
49259   return SQLITE_OK;
49260 }
49261
49262 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
49263   #define ptrmapPut(w,x,y,z,rc)
49264   #define ptrmapGet(w,x,y,z) SQLITE_OK
49265   #define ptrmapPutOvflPtr(x, y, rc)
49266 #endif
49267
49268 /*
49269 ** Given a btree page and a cell index (0 means the first cell on
49270 ** the page, 1 means the second cell, and so forth) return a pointer
49271 ** to the cell content.
49272 **
49273 ** This routine works only for pages that do not contain overflow cells.
49274 */
49275 #define findCell(P,I) \
49276   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
49277 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
49278
49279
49280 /*
49281 ** This a more complex version of findCell() that works for
49282 ** pages that do contain overflow cells.
49283 */
49284 static u8 *findOverflowCell(MemPage *pPage, int iCell){
49285   int i;
49286   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49287   for(i=pPage->nOverflow-1; i>=0; i--){
49288     int k;
49289     k = pPage->aiOvfl[i];
49290     if( k<=iCell ){
49291       if( k==iCell ){
49292         return pPage->apOvfl[i];
49293       }
49294       iCell--;
49295     }
49296   }
49297   return findCell(pPage, iCell);
49298 }
49299
49300 /*
49301 ** Parse a cell content block and fill in the CellInfo structure.  There
49302 ** are two versions of this function.  btreeParseCell() takes a 
49303 ** cell index as the second argument and btreeParseCellPtr() 
49304 ** takes a pointer to the body of the cell as its second argument.
49305 **
49306 ** Within this file, the parseCell() macro can be called instead of
49307 ** btreeParseCellPtr(). Using some compilers, this will be faster.
49308 */
49309 static void btreeParseCellPtr(
49310   MemPage *pPage,         /* Page containing the cell */
49311   u8 *pCell,              /* Pointer to the cell text. */
49312   CellInfo *pInfo         /* Fill in this structure */
49313 ){
49314   u16 n;                  /* Number bytes in cell content header */
49315   u32 nPayload;           /* Number of bytes of cell payload */
49316
49317   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49318
49319   pInfo->pCell = pCell;
49320   assert( pPage->leaf==0 || pPage->leaf==1 );
49321   n = pPage->childPtrSize;
49322   assert( n==4-4*pPage->leaf );
49323   if( pPage->intKey ){
49324     if( pPage->hasData ){
49325       n += getVarint32(&pCell[n], nPayload);
49326     }else{
49327       nPayload = 0;
49328     }
49329     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
49330     pInfo->nData = nPayload;
49331   }else{
49332     pInfo->nData = 0;
49333     n += getVarint32(&pCell[n], nPayload);
49334     pInfo->nKey = nPayload;
49335   }
49336   pInfo->nPayload = nPayload;
49337   pInfo->nHeader = n;
49338   testcase( nPayload==pPage->maxLocal );
49339   testcase( nPayload==pPage->maxLocal+1 );
49340   if( likely(nPayload<=pPage->maxLocal) ){
49341     /* This is the (easy) common case where the entire payload fits
49342     ** on the local page.  No overflow is required.
49343     */
49344     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
49345     pInfo->nLocal = (u16)nPayload;
49346     pInfo->iOverflow = 0;
49347   }else{
49348     /* If the payload will not fit completely on the local page, we have
49349     ** to decide how much to store locally and how much to spill onto
49350     ** overflow pages.  The strategy is to minimize the amount of unused
49351     ** space on overflow pages while keeping the amount of local storage
49352     ** in between minLocal and maxLocal.
49353     **
49354     ** Warning:  changing the way overflow payload is distributed in any
49355     ** way will result in an incompatible file format.
49356     */
49357     int minLocal;  /* Minimum amount of payload held locally */
49358     int maxLocal;  /* Maximum amount of payload held locally */
49359     int surplus;   /* Overflow payload available for local storage */
49360
49361     minLocal = pPage->minLocal;
49362     maxLocal = pPage->maxLocal;
49363     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
49364     testcase( surplus==maxLocal );
49365     testcase( surplus==maxLocal+1 );
49366     if( surplus <= maxLocal ){
49367       pInfo->nLocal = (u16)surplus;
49368     }else{
49369       pInfo->nLocal = (u16)minLocal;
49370     }
49371     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
49372     pInfo->nSize = pInfo->iOverflow + 4;
49373   }
49374 }
49375 #define parseCell(pPage, iCell, pInfo) \
49376   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
49377 static void btreeParseCell(
49378   MemPage *pPage,         /* Page containing the cell */
49379   int iCell,              /* The cell index.  First cell is 0 */
49380   CellInfo *pInfo         /* Fill in this structure */
49381 ){
49382   parseCell(pPage, iCell, pInfo);
49383 }
49384
49385 /*
49386 ** Compute the total number of bytes that a Cell needs in the cell
49387 ** data area of the btree-page.  The return number includes the cell
49388 ** data header and the local payload, but not any overflow page or
49389 ** the space used by the cell pointer.
49390 */
49391 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
49392   u8 *pIter = &pCell[pPage->childPtrSize];
49393   u32 nSize;
49394
49395 #ifdef SQLITE_DEBUG
49396   /* The value returned by this function should always be the same as
49397   ** the (CellInfo.nSize) value found by doing a full parse of the
49398   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
49399   ** this function verifies that this invariant is not violated. */
49400   CellInfo debuginfo;
49401   btreeParseCellPtr(pPage, pCell, &debuginfo);
49402 #endif
49403
49404   if( pPage->intKey ){
49405     u8 *pEnd;
49406     if( pPage->hasData ){
49407       pIter += getVarint32(pIter, nSize);
49408     }else{
49409       nSize = 0;
49410     }
49411
49412     /* pIter now points at the 64-bit integer key value, a variable length 
49413     ** integer. The following block moves pIter to point at the first byte
49414     ** past the end of the key value. */
49415     pEnd = &pIter[9];
49416     while( (*pIter++)&0x80 && pIter<pEnd );
49417   }else{
49418     pIter += getVarint32(pIter, nSize);
49419   }
49420
49421   testcase( nSize==pPage->maxLocal );
49422   testcase( nSize==pPage->maxLocal+1 );
49423   if( nSize>pPage->maxLocal ){
49424     int minLocal = pPage->minLocal;
49425     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
49426     testcase( nSize==pPage->maxLocal );
49427     testcase( nSize==pPage->maxLocal+1 );
49428     if( nSize>pPage->maxLocal ){
49429       nSize = minLocal;
49430     }
49431     nSize += 4;
49432   }
49433   nSize += (u32)(pIter - pCell);
49434
49435   /* The minimum size of any cell is 4 bytes. */
49436   if( nSize<4 ){
49437     nSize = 4;
49438   }
49439
49440   assert( nSize==debuginfo.nSize );
49441   return (u16)nSize;
49442 }
49443
49444 #ifdef SQLITE_DEBUG
49445 /* This variation on cellSizePtr() is used inside of assert() statements
49446 ** only. */
49447 static u16 cellSize(MemPage *pPage, int iCell){
49448   return cellSizePtr(pPage, findCell(pPage, iCell));
49449 }
49450 #endif
49451
49452 #ifndef SQLITE_OMIT_AUTOVACUUM
49453 /*
49454 ** If the cell pCell, part of page pPage contains a pointer
49455 ** to an overflow page, insert an entry into the pointer-map
49456 ** for the overflow page.
49457 */
49458 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
49459   CellInfo info;
49460   if( *pRC ) return;
49461   assert( pCell!=0 );
49462   btreeParseCellPtr(pPage, pCell, &info);
49463   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
49464   if( info.iOverflow ){
49465     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
49466     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
49467   }
49468 }
49469 #endif
49470
49471
49472 /*
49473 ** Defragment the page given.  All Cells are moved to the
49474 ** end of the page and all free space is collected into one
49475 ** big FreeBlk that occurs in between the header and cell
49476 ** pointer array and the cell content area.
49477 */
49478 static int defragmentPage(MemPage *pPage){
49479   int i;                     /* Loop counter */
49480   int pc;                    /* Address of a i-th cell */
49481   int hdr;                   /* Offset to the page header */
49482   int size;                  /* Size of a cell */
49483   int usableSize;            /* Number of usable bytes on a page */
49484   int cellOffset;            /* Offset to the cell pointer array */
49485   int cbrk;                  /* Offset to the cell content area */
49486   int nCell;                 /* Number of cells on the page */
49487   unsigned char *data;       /* The page data */
49488   unsigned char *temp;       /* Temp area for cell content */
49489   int iCellFirst;            /* First allowable cell index */
49490   int iCellLast;             /* Last possible cell index */
49491
49492
49493   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49494   assert( pPage->pBt!=0 );
49495   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
49496   assert( pPage->nOverflow==0 );
49497   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49498   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
49499   data = pPage->aData;
49500   hdr = pPage->hdrOffset;
49501   cellOffset = pPage->cellOffset;
49502   nCell = pPage->nCell;
49503   assert( nCell==get2byte(&data[hdr+3]) );
49504   usableSize = pPage->pBt->usableSize;
49505   cbrk = get2byte(&data[hdr+5]);
49506   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
49507   cbrk = usableSize;
49508   iCellFirst = cellOffset + 2*nCell;
49509   iCellLast = usableSize - 4;
49510   for(i=0; i<nCell; i++){
49511     u8 *pAddr;     /* The i-th cell pointer */
49512     pAddr = &data[cellOffset + i*2];
49513     pc = get2byte(pAddr);
49514     testcase( pc==iCellFirst );
49515     testcase( pc==iCellLast );
49516 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49517     /* These conditions have already been verified in btreeInitPage()
49518     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
49519     */
49520     if( pc<iCellFirst || pc>iCellLast ){
49521       return SQLITE_CORRUPT_BKPT;
49522     }
49523 #endif
49524     assert( pc>=iCellFirst && pc<=iCellLast );
49525     size = cellSizePtr(pPage, &temp[pc]);
49526     cbrk -= size;
49527 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49528     if( cbrk<iCellFirst ){
49529       return SQLITE_CORRUPT_BKPT;
49530     }
49531 #else
49532     if( cbrk<iCellFirst || pc+size>usableSize ){
49533       return SQLITE_CORRUPT_BKPT;
49534     }
49535 #endif
49536     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
49537     testcase( cbrk+size==usableSize );
49538     testcase( pc+size==usableSize );
49539     memcpy(&data[cbrk], &temp[pc], size);
49540     put2byte(pAddr, cbrk);
49541   }
49542   assert( cbrk>=iCellFirst );
49543   put2byte(&data[hdr+5], cbrk);
49544   data[hdr+1] = 0;
49545   data[hdr+2] = 0;
49546   data[hdr+7] = 0;
49547   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
49548   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49549   if( cbrk-iCellFirst!=pPage->nFree ){
49550     return SQLITE_CORRUPT_BKPT;
49551   }
49552   return SQLITE_OK;
49553 }
49554
49555 /*
49556 ** Allocate nByte bytes of space from within the B-Tree page passed
49557 ** as the first argument. Write into *pIdx the index into pPage->aData[]
49558 ** of the first byte of allocated space. Return either SQLITE_OK or
49559 ** an error code (usually SQLITE_CORRUPT).
49560 **
49561 ** The caller guarantees that there is sufficient space to make the
49562 ** allocation.  This routine might need to defragment in order to bring
49563 ** all the space together, however.  This routine will avoid using
49564 ** the first two bytes past the cell pointer area since presumably this
49565 ** allocation is being made in order to insert a new cell, so we will
49566 ** also end up needing a new cell pointer.
49567 */
49568 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
49569   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
49570   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
49571   int nFrag;                           /* Number of fragmented bytes on pPage */
49572   int top;                             /* First byte of cell content area */
49573   int gap;        /* First byte of gap between cell pointers and cell content */
49574   int rc;         /* Integer return code */
49575   int usableSize; /* Usable size of the page */
49576   
49577   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49578   assert( pPage->pBt );
49579   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49580   assert( nByte>=0 );  /* Minimum cell size is 4 */
49581   assert( pPage->nFree>=nByte );
49582   assert( pPage->nOverflow==0 );
49583   usableSize = pPage->pBt->usableSize;
49584   assert( nByte < usableSize-8 );
49585
49586   nFrag = data[hdr+7];
49587   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
49588   gap = pPage->cellOffset + 2*pPage->nCell;
49589   top = get2byteNotZero(&data[hdr+5]);
49590   if( gap>top ) return SQLITE_CORRUPT_BKPT;
49591   testcase( gap+2==top );
49592   testcase( gap+1==top );
49593   testcase( gap==top );
49594
49595   if( nFrag>=60 ){
49596     /* Always defragment highly fragmented pages */
49597     rc = defragmentPage(pPage);
49598     if( rc ) return rc;
49599     top = get2byteNotZero(&data[hdr+5]);
49600   }else if( gap+2<=top ){
49601     /* Search the freelist looking for a free slot big enough to satisfy 
49602     ** the request. The allocation is made from the first free slot in 
49603     ** the list that is large enough to accomadate it.
49604     */
49605     int pc, addr;
49606     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
49607       int size;            /* Size of the free slot */
49608       if( pc>usableSize-4 || pc<addr+4 ){
49609         return SQLITE_CORRUPT_BKPT;
49610       }
49611       size = get2byte(&data[pc+2]);
49612       if( size>=nByte ){
49613         int x = size - nByte;
49614         testcase( x==4 );
49615         testcase( x==3 );
49616         if( x<4 ){
49617           /* Remove the slot from the free-list. Update the number of
49618           ** fragmented bytes within the page. */
49619           memcpy(&data[addr], &data[pc], 2);
49620           data[hdr+7] = (u8)(nFrag + x);
49621         }else if( size+pc > usableSize ){
49622           return SQLITE_CORRUPT_BKPT;
49623         }else{
49624           /* The slot remains on the free-list. Reduce its size to account
49625           ** for the portion used by the new allocation. */
49626           put2byte(&data[pc+2], x);
49627         }
49628         *pIdx = pc + x;
49629         return SQLITE_OK;
49630       }
49631     }
49632   }
49633
49634   /* Check to make sure there is enough space in the gap to satisfy
49635   ** the allocation.  If not, defragment.
49636   */
49637   testcase( gap+2+nByte==top );
49638   if( gap+2+nByte>top ){
49639     rc = defragmentPage(pPage);
49640     if( rc ) return rc;
49641     top = get2byteNotZero(&data[hdr+5]);
49642     assert( gap+nByte<=top );
49643   }
49644
49645
49646   /* Allocate memory from the gap in between the cell pointer array
49647   ** and the cell content area.  The btreeInitPage() call has already
49648   ** validated the freelist.  Given that the freelist is valid, there
49649   ** is no way that the allocation can extend off the end of the page.
49650   ** The assert() below verifies the previous sentence.
49651   */
49652   top -= nByte;
49653   put2byte(&data[hdr+5], top);
49654   assert( top+nByte <= (int)pPage->pBt->usableSize );
49655   *pIdx = top;
49656   return SQLITE_OK;
49657 }
49658
49659 /*
49660 ** Return a section of the pPage->aData to the freelist.
49661 ** The first byte of the new free block is pPage->aDisk[start]
49662 ** and the size of the block is "size" bytes.
49663 **
49664 ** Most of the effort here is involved in coalesing adjacent
49665 ** free blocks into a single big free block.
49666 */
49667 static int freeSpace(MemPage *pPage, int start, int size){
49668   int addr, pbegin, hdr;
49669   int iLast;                        /* Largest possible freeblock offset */
49670   unsigned char *data = pPage->aData;
49671
49672   assert( pPage->pBt!=0 );
49673   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49674   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
49675   assert( (start + size) <= (int)pPage->pBt->usableSize );
49676   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49677   assert( size>=0 );   /* Minimum cell size is 4 */
49678
49679   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
49680     /* Overwrite deleted information with zeros when the secure_delete
49681     ** option is enabled */
49682     memset(&data[start], 0, size);
49683   }
49684
49685   /* Add the space back into the linked list of freeblocks.  Note that
49686   ** even though the freeblock list was checked by btreeInitPage(),
49687   ** btreeInitPage() did not detect overlapping cells or
49688   ** freeblocks that overlapped cells.   Nor does it detect when the
49689   ** cell content area exceeds the value in the page header.  If these
49690   ** situations arise, then subsequent insert operations might corrupt
49691   ** the freelist.  So we do need to check for corruption while scanning
49692   ** the freelist.
49693   */
49694   hdr = pPage->hdrOffset;
49695   addr = hdr + 1;
49696   iLast = pPage->pBt->usableSize - 4;
49697   assert( start<=iLast );
49698   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
49699     if( pbegin<addr+4 ){
49700       return SQLITE_CORRUPT_BKPT;
49701     }
49702     addr = pbegin;
49703   }
49704   if( pbegin>iLast ){
49705     return SQLITE_CORRUPT_BKPT;
49706   }
49707   assert( pbegin>addr || pbegin==0 );
49708   put2byte(&data[addr], start);
49709   put2byte(&data[start], pbegin);
49710   put2byte(&data[start+2], size);
49711   pPage->nFree = pPage->nFree + (u16)size;
49712
49713   /* Coalesce adjacent free blocks */
49714   addr = hdr + 1;
49715   while( (pbegin = get2byte(&data[addr]))>0 ){
49716     int pnext, psize, x;
49717     assert( pbegin>addr );
49718     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
49719     pnext = get2byte(&data[pbegin]);
49720     psize = get2byte(&data[pbegin+2]);
49721     if( pbegin + psize + 3 >= pnext && pnext>0 ){
49722       int frag = pnext - (pbegin+psize);
49723       if( (frag<0) || (frag>(int)data[hdr+7]) ){
49724         return SQLITE_CORRUPT_BKPT;
49725       }
49726       data[hdr+7] -= (u8)frag;
49727       x = get2byte(&data[pnext]);
49728       put2byte(&data[pbegin], x);
49729       x = pnext + get2byte(&data[pnext+2]) - pbegin;
49730       put2byte(&data[pbegin+2], x);
49731     }else{
49732       addr = pbegin;
49733     }
49734   }
49735
49736   /* If the cell content area begins with a freeblock, remove it. */
49737   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
49738     int top;
49739     pbegin = get2byte(&data[hdr+1]);
49740     memcpy(&data[hdr+1], &data[pbegin], 2);
49741     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
49742     put2byte(&data[hdr+5], top);
49743   }
49744   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49745   return SQLITE_OK;
49746 }
49747
49748 /*
49749 ** Decode the flags byte (the first byte of the header) for a page
49750 ** and initialize fields of the MemPage structure accordingly.
49751 **
49752 ** Only the following combinations are supported.  Anything different
49753 ** indicates a corrupt database files:
49754 **
49755 **         PTF_ZERODATA
49756 **         PTF_ZERODATA | PTF_LEAF
49757 **         PTF_LEAFDATA | PTF_INTKEY
49758 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
49759 */
49760 static int decodeFlags(MemPage *pPage, int flagByte){
49761   BtShared *pBt;     /* A copy of pPage->pBt */
49762
49763   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
49764   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49765   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
49766   flagByte &= ~PTF_LEAF;
49767   pPage->childPtrSize = 4-4*pPage->leaf;
49768   pBt = pPage->pBt;
49769   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
49770     pPage->intKey = 1;
49771     pPage->hasData = pPage->leaf;
49772     pPage->maxLocal = pBt->maxLeaf;
49773     pPage->minLocal = pBt->minLeaf;
49774   }else if( flagByte==PTF_ZERODATA ){
49775     pPage->intKey = 0;
49776     pPage->hasData = 0;
49777     pPage->maxLocal = pBt->maxLocal;
49778     pPage->minLocal = pBt->minLocal;
49779   }else{
49780     return SQLITE_CORRUPT_BKPT;
49781   }
49782   pPage->max1bytePayload = pBt->max1bytePayload;
49783   return SQLITE_OK;
49784 }
49785
49786 /*
49787 ** Initialize the auxiliary information for a disk block.
49788 **
49789 ** Return SQLITE_OK on success.  If we see that the page does
49790 ** not contain a well-formed database page, then return 
49791 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
49792 ** guarantee that the page is well-formed.  It only shows that
49793 ** we failed to detect any corruption.
49794 */
49795 static int btreeInitPage(MemPage *pPage){
49796
49797   assert( pPage->pBt!=0 );
49798   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49799   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
49800   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
49801   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
49802
49803   if( !pPage->isInit ){
49804     u16 pc;            /* Address of a freeblock within pPage->aData[] */
49805     u8 hdr;            /* Offset to beginning of page header */
49806     u8 *data;          /* Equal to pPage->aData */
49807     BtShared *pBt;        /* The main btree structure */
49808     int usableSize;    /* Amount of usable space on each page */
49809     u16 cellOffset;    /* Offset from start of page to first cell pointer */
49810     int nFree;         /* Number of unused bytes on the page */
49811     int top;           /* First byte of the cell content area */
49812     int iCellFirst;    /* First allowable cell or freeblock offset */
49813     int iCellLast;     /* Last possible cell or freeblock offset */
49814
49815     pBt = pPage->pBt;
49816
49817     hdr = pPage->hdrOffset;
49818     data = pPage->aData;
49819     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
49820     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49821     pPage->maskPage = (u16)(pBt->pageSize - 1);
49822     pPage->nOverflow = 0;
49823     usableSize = pBt->usableSize;
49824     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
49825     pPage->aDataEnd = &data[usableSize];
49826     pPage->aCellIdx = &data[cellOffset];
49827     top = get2byteNotZero(&data[hdr+5]);
49828     pPage->nCell = get2byte(&data[hdr+3]);
49829     if( pPage->nCell>MX_CELL(pBt) ){
49830       /* To many cells for a single page.  The page must be corrupt */
49831       return SQLITE_CORRUPT_BKPT;
49832     }
49833     testcase( pPage->nCell==MX_CELL(pBt) );
49834
49835     /* A malformed database page might cause us to read past the end
49836     ** of page when parsing a cell.  
49837     **
49838     ** The following block of code checks early to see if a cell extends
49839     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
49840     ** returned if it does.
49841     */
49842     iCellFirst = cellOffset + 2*pPage->nCell;
49843     iCellLast = usableSize - 4;
49844 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49845     {
49846       int i;            /* Index into the cell pointer array */
49847       int sz;           /* Size of a cell */
49848
49849       if( !pPage->leaf ) iCellLast--;
49850       for(i=0; i<pPage->nCell; i++){
49851         pc = get2byte(&data[cellOffset+i*2]);
49852         testcase( pc==iCellFirst );
49853         testcase( pc==iCellLast );
49854         if( pc<iCellFirst || pc>iCellLast ){
49855           return SQLITE_CORRUPT_BKPT;
49856         }
49857         sz = cellSizePtr(pPage, &data[pc]);
49858         testcase( pc+sz==usableSize );
49859         if( pc+sz>usableSize ){
49860           return SQLITE_CORRUPT_BKPT;
49861         }
49862       }
49863       if( !pPage->leaf ) iCellLast++;
49864     }  
49865 #endif
49866
49867     /* Compute the total free space on the page */
49868     pc = get2byte(&data[hdr+1]);
49869     nFree = data[hdr+7] + top;
49870     while( pc>0 ){
49871       u16 next, size;
49872       if( pc<iCellFirst || pc>iCellLast ){
49873         /* Start of free block is off the page */
49874         return SQLITE_CORRUPT_BKPT; 
49875       }
49876       next = get2byte(&data[pc]);
49877       size = get2byte(&data[pc+2]);
49878       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
49879         /* Free blocks must be in ascending order. And the last byte of
49880         ** the free-block must lie on the database page.  */
49881         return SQLITE_CORRUPT_BKPT; 
49882       }
49883       nFree = nFree + size;
49884       pc = next;
49885     }
49886
49887     /* At this point, nFree contains the sum of the offset to the start
49888     ** of the cell-content area plus the number of free bytes within
49889     ** the cell-content area. If this is greater than the usable-size
49890     ** of the page, then the page must be corrupted. This check also
49891     ** serves to verify that the offset to the start of the cell-content
49892     ** area, according to the page header, lies within the page.
49893     */
49894     if( nFree>usableSize ){
49895       return SQLITE_CORRUPT_BKPT; 
49896     }
49897     pPage->nFree = (u16)(nFree - iCellFirst);
49898     pPage->isInit = 1;
49899   }
49900   return SQLITE_OK;
49901 }
49902
49903 /*
49904 ** Set up a raw page so that it looks like a database page holding
49905 ** no entries.
49906 */
49907 static void zeroPage(MemPage *pPage, int flags){
49908   unsigned char *data = pPage->aData;
49909   BtShared *pBt = pPage->pBt;
49910   u8 hdr = pPage->hdrOffset;
49911   u16 first;
49912
49913   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
49914   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
49915   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
49916   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49917   assert( sqlite3_mutex_held(pBt->mutex) );
49918   if( pBt->btsFlags & BTS_SECURE_DELETE ){
49919     memset(&data[hdr], 0, pBt->usableSize - hdr);
49920   }
49921   data[hdr] = (char)flags;
49922   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
49923   memset(&data[hdr+1], 0, 4);
49924   data[hdr+7] = 0;
49925   put2byte(&data[hdr+5], pBt->usableSize);
49926   pPage->nFree = (u16)(pBt->usableSize - first);
49927   decodeFlags(pPage, flags);
49928   pPage->hdrOffset = hdr;
49929   pPage->cellOffset = first;
49930   pPage->aDataEnd = &data[pBt->usableSize];
49931   pPage->aCellIdx = &data[first];
49932   pPage->nOverflow = 0;
49933   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49934   pPage->maskPage = (u16)(pBt->pageSize - 1);
49935   pPage->nCell = 0;
49936   pPage->isInit = 1;
49937 }
49938
49939
49940 /*
49941 ** Convert a DbPage obtained from the pager into a MemPage used by
49942 ** the btree layer.
49943 */
49944 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
49945   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
49946   pPage->aData = sqlite3PagerGetData(pDbPage);
49947   pPage->pDbPage = pDbPage;
49948   pPage->pBt = pBt;
49949   pPage->pgno = pgno;
49950   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
49951   return pPage; 
49952 }
49953
49954 /*
49955 ** Get a page from the pager.  Initialize the MemPage.pBt and
49956 ** MemPage.aData elements if needed.
49957 **
49958 ** If the noContent flag is set, it means that we do not care about
49959 ** the content of the page at this time.  So do not go to the disk
49960 ** to fetch the content.  Just fill in the content with zeros for now.
49961 ** If in the future we call sqlite3PagerWrite() on this page, that
49962 ** means we have started to be concerned about content and the disk
49963 ** read should occur at that point.
49964 */
49965 static int btreeGetPage(
49966   BtShared *pBt,       /* The btree */
49967   Pgno pgno,           /* Number of the page to fetch */
49968   MemPage **ppPage,    /* Return the page in this parameter */
49969   int noContent        /* Do not load page content if true */
49970 ){
49971   int rc;
49972   DbPage *pDbPage;
49973
49974   assert( sqlite3_mutex_held(pBt->mutex) );
49975   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
49976   if( rc ) return rc;
49977   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
49978   return SQLITE_OK;
49979 }
49980
49981 /*
49982 ** Retrieve a page from the pager cache. If the requested page is not
49983 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
49984 ** MemPage.aData elements if needed.
49985 */
49986 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
49987   DbPage *pDbPage;
49988   assert( sqlite3_mutex_held(pBt->mutex) );
49989   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
49990   if( pDbPage ){
49991     return btreePageFromDbPage(pDbPage, pgno, pBt);
49992   }
49993   return 0;
49994 }
49995
49996 /*
49997 ** Return the size of the database file in pages. If there is any kind of
49998 ** error, return ((unsigned int)-1).
49999 */
50000 static Pgno btreePagecount(BtShared *pBt){
50001   return pBt->nPage;
50002 }
50003 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
50004   assert( sqlite3BtreeHoldsMutex(p) );
50005   assert( ((p->pBt->nPage)&0x8000000)==0 );
50006   return (int)btreePagecount(p->pBt);
50007 }
50008
50009 /*
50010 ** Get a page from the pager and initialize it.  This routine is just a
50011 ** convenience wrapper around separate calls to btreeGetPage() and 
50012 ** btreeInitPage().
50013 **
50014 ** If an error occurs, then the value *ppPage is set to is undefined. It
50015 ** may remain unchanged, or it may be set to an invalid value.
50016 */
50017 static int getAndInitPage(
50018   BtShared *pBt,          /* The database file */
50019   Pgno pgno,           /* Number of the page to get */
50020   MemPage **ppPage     /* Write the page pointer here */
50021 ){
50022   int rc;
50023   assert( sqlite3_mutex_held(pBt->mutex) );
50024
50025   if( pgno>btreePagecount(pBt) ){
50026     rc = SQLITE_CORRUPT_BKPT;
50027   }else{
50028     rc = btreeGetPage(pBt, pgno, ppPage, 0);
50029     if( rc==SQLITE_OK ){
50030       rc = btreeInitPage(*ppPage);
50031       if( rc!=SQLITE_OK ){
50032         releasePage(*ppPage);
50033       }
50034     }
50035   }
50036
50037   testcase( pgno==0 );
50038   assert( pgno!=0 || rc==SQLITE_CORRUPT );
50039   return rc;
50040 }
50041
50042 /*
50043 ** Release a MemPage.  This should be called once for each prior
50044 ** call to btreeGetPage.
50045 */
50046 static void releasePage(MemPage *pPage){
50047   if( pPage ){
50048     assert( pPage->aData );
50049     assert( pPage->pBt );
50050     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
50051     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
50052     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50053     sqlite3PagerUnref(pPage->pDbPage);
50054   }
50055 }
50056
50057 /*
50058 ** During a rollback, when the pager reloads information into the cache
50059 ** so that the cache is restored to its original state at the start of
50060 ** the transaction, for each page restored this routine is called.
50061 **
50062 ** This routine needs to reset the extra data section at the end of the
50063 ** page to agree with the restored data.
50064 */
50065 static void pageReinit(DbPage *pData){
50066   MemPage *pPage;
50067   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
50068   assert( sqlite3PagerPageRefcount(pData)>0 );
50069   if( pPage->isInit ){
50070     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50071     pPage->isInit = 0;
50072     if( sqlite3PagerPageRefcount(pData)>1 ){
50073       /* pPage might not be a btree page;  it might be an overflow page
50074       ** or ptrmap page or a free page.  In those cases, the following
50075       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
50076       ** But no harm is done by this.  And it is very important that
50077       ** btreeInitPage() be called on every btree page so we make
50078       ** the call for every page that comes in for re-initing. */
50079       btreeInitPage(pPage);
50080     }
50081   }
50082 }
50083
50084 /*
50085 ** Invoke the busy handler for a btree.
50086 */
50087 static int btreeInvokeBusyHandler(void *pArg){
50088   BtShared *pBt = (BtShared*)pArg;
50089   assert( pBt->db );
50090   assert( sqlite3_mutex_held(pBt->db->mutex) );
50091   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
50092 }
50093
50094 /*
50095 ** Open a database file.
50096 ** 
50097 ** zFilename is the name of the database file.  If zFilename is NULL
50098 ** then an ephemeral database is created.  The ephemeral database might
50099 ** be exclusively in memory, or it might use a disk-based memory cache.
50100 ** Either way, the ephemeral database will be automatically deleted 
50101 ** when sqlite3BtreeClose() is called.
50102 **
50103 ** If zFilename is ":memory:" then an in-memory database is created
50104 ** that is automatically destroyed when it is closed.
50105 **
50106 ** The "flags" parameter is a bitmask that might contain bits like
50107 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
50108 **
50109 ** If the database is already opened in the same database connection
50110 ** and we are in shared cache mode, then the open will fail with an
50111 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
50112 ** objects in the same database connection since doing so will lead
50113 ** to problems with locking.
50114 */
50115 SQLITE_PRIVATE int sqlite3BtreeOpen(
50116   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
50117   const char *zFilename,  /* Name of the file containing the BTree database */
50118   sqlite3 *db,            /* Associated database handle */
50119   Btree **ppBtree,        /* Pointer to new Btree object written here */
50120   int flags,              /* Options */
50121   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
50122 ){
50123   BtShared *pBt = 0;             /* Shared part of btree structure */
50124   Btree *p;                      /* Handle to return */
50125   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
50126   int rc = SQLITE_OK;            /* Result code from this function */
50127   u8 nReserve;                   /* Byte of unused space on each page */
50128   unsigned char zDbHeader[100];  /* Database header content */
50129
50130   /* True if opening an ephemeral, temporary database */
50131   const int isTempDb = zFilename==0 || zFilename[0]==0;
50132
50133   /* Set the variable isMemdb to true for an in-memory database, or 
50134   ** false for a file-based database.
50135   */
50136 #ifdef SQLITE_OMIT_MEMORYDB
50137   const int isMemdb = 0;
50138 #else
50139   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
50140                        || (isTempDb && sqlite3TempInMemory(db))
50141                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
50142 #endif
50143
50144   assert( db!=0 );
50145   assert( pVfs!=0 );
50146   assert( sqlite3_mutex_held(db->mutex) );
50147   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
50148
50149   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
50150   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
50151
50152   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
50153   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
50154
50155   if( isMemdb ){
50156     flags |= BTREE_MEMORY;
50157   }
50158   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
50159     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
50160   }
50161   p = sqlite3MallocZero(sizeof(Btree));
50162   if( !p ){
50163     return SQLITE_NOMEM;
50164   }
50165   p->inTrans = TRANS_NONE;
50166   p->db = db;
50167 #ifndef SQLITE_OMIT_SHARED_CACHE
50168   p->lock.pBtree = p;
50169   p->lock.iTable = 1;
50170 #endif
50171
50172 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
50173   /*
50174   ** If this Btree is a candidate for shared cache, try to find an
50175   ** existing BtShared object that we can share with
50176   */
50177   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
50178     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
50179       int nFullPathname = pVfs->mxPathname+1;
50180       char *zFullPathname = sqlite3Malloc(nFullPathname);
50181       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
50182       p->sharable = 1;
50183       if( !zFullPathname ){
50184         sqlite3_free(p);
50185         return SQLITE_NOMEM;
50186       }
50187       if( isMemdb ){
50188         memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
50189       }else{
50190         rc = sqlite3OsFullPathname(pVfs, zFilename,
50191                                    nFullPathname, zFullPathname);
50192         if( rc ){
50193           sqlite3_free(zFullPathname);
50194           sqlite3_free(p);
50195           return rc;
50196         }
50197       }
50198 #if SQLITE_THREADSAFE
50199       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
50200       sqlite3_mutex_enter(mutexOpen);
50201       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
50202       sqlite3_mutex_enter(mutexShared);
50203 #endif
50204       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
50205         assert( pBt->nRef>0 );
50206         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
50207                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
50208           int iDb;
50209           for(iDb=db->nDb-1; iDb>=0; iDb--){
50210             Btree *pExisting = db->aDb[iDb].pBt;
50211             if( pExisting && pExisting->pBt==pBt ){
50212               sqlite3_mutex_leave(mutexShared);
50213               sqlite3_mutex_leave(mutexOpen);
50214               sqlite3_free(zFullPathname);
50215               sqlite3_free(p);
50216               return SQLITE_CONSTRAINT;
50217             }
50218           }
50219           p->pBt = pBt;
50220           pBt->nRef++;
50221           break;
50222         }
50223       }
50224       sqlite3_mutex_leave(mutexShared);
50225       sqlite3_free(zFullPathname);
50226     }
50227 #ifdef SQLITE_DEBUG
50228     else{
50229       /* In debug mode, we mark all persistent databases as sharable
50230       ** even when they are not.  This exercises the locking code and
50231       ** gives more opportunity for asserts(sqlite3_mutex_held())
50232       ** statements to find locking problems.
50233       */
50234       p->sharable = 1;
50235     }
50236 #endif
50237   }
50238 #endif
50239   if( pBt==0 ){
50240     /*
50241     ** The following asserts make sure that structures used by the btree are
50242     ** the right size.  This is to guard against size changes that result
50243     ** when compiling on a different architecture.
50244     */
50245     assert( sizeof(i64)==8 || sizeof(i64)==4 );
50246     assert( sizeof(u64)==8 || sizeof(u64)==4 );
50247     assert( sizeof(u32)==4 );
50248     assert( sizeof(u16)==2 );
50249     assert( sizeof(Pgno)==4 );
50250   
50251     pBt = sqlite3MallocZero( sizeof(*pBt) );
50252     if( pBt==0 ){
50253       rc = SQLITE_NOMEM;
50254       goto btree_open_out;
50255     }
50256     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
50257                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
50258     if( rc==SQLITE_OK ){
50259       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
50260     }
50261     if( rc!=SQLITE_OK ){
50262       goto btree_open_out;
50263     }
50264     pBt->openFlags = (u8)flags;
50265     pBt->db = db;
50266     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
50267     p->pBt = pBt;
50268   
50269     pBt->pCursor = 0;
50270     pBt->pPage1 = 0;
50271     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
50272 #ifdef SQLITE_SECURE_DELETE
50273     pBt->btsFlags |= BTS_SECURE_DELETE;
50274 #endif
50275     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
50276     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
50277          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
50278       pBt->pageSize = 0;
50279 #ifndef SQLITE_OMIT_AUTOVACUUM
50280       /* If the magic name ":memory:" will create an in-memory database, then
50281       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
50282       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
50283       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
50284       ** regular file-name. In this case the auto-vacuum applies as per normal.
50285       */
50286       if( zFilename && !isMemdb ){
50287         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
50288         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
50289       }
50290 #endif
50291       nReserve = 0;
50292     }else{
50293       nReserve = zDbHeader[20];
50294       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
50295 #ifndef SQLITE_OMIT_AUTOVACUUM
50296       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
50297       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
50298 #endif
50299     }
50300     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
50301     if( rc ) goto btree_open_out;
50302     pBt->usableSize = pBt->pageSize - nReserve;
50303     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
50304    
50305 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
50306     /* Add the new BtShared object to the linked list sharable BtShareds.
50307     */
50308     if( p->sharable ){
50309       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
50310       pBt->nRef = 1;
50311       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
50312       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
50313         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
50314         if( pBt->mutex==0 ){
50315           rc = SQLITE_NOMEM;
50316           db->mallocFailed = 0;
50317           goto btree_open_out;
50318         }
50319       }
50320       sqlite3_mutex_enter(mutexShared);
50321       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
50322       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
50323       sqlite3_mutex_leave(mutexShared);
50324     }
50325 #endif
50326   }
50327
50328 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
50329   /* If the new Btree uses a sharable pBtShared, then link the new
50330   ** Btree into the list of all sharable Btrees for the same connection.
50331   ** The list is kept in ascending order by pBt address.
50332   */
50333   if( p->sharable ){
50334     int i;
50335     Btree *pSib;
50336     for(i=0; i<db->nDb; i++){
50337       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
50338         while( pSib->pPrev ){ pSib = pSib->pPrev; }
50339         if( p->pBt<pSib->pBt ){
50340           p->pNext = pSib;
50341           p->pPrev = 0;
50342           pSib->pPrev = p;
50343         }else{
50344           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
50345             pSib = pSib->pNext;
50346           }
50347           p->pNext = pSib->pNext;
50348           p->pPrev = pSib;
50349           if( p->pNext ){
50350             p->pNext->pPrev = p;
50351           }
50352           pSib->pNext = p;
50353         }
50354         break;
50355       }
50356     }
50357   }
50358 #endif
50359   *ppBtree = p;
50360
50361 btree_open_out:
50362   if( rc!=SQLITE_OK ){
50363     if( pBt && pBt->pPager ){
50364       sqlite3PagerClose(pBt->pPager);
50365     }
50366     sqlite3_free(pBt);
50367     sqlite3_free(p);
50368     *ppBtree = 0;
50369   }else{
50370     /* If the B-Tree was successfully opened, set the pager-cache size to the
50371     ** default value. Except, when opening on an existing shared pager-cache,
50372     ** do not change the pager-cache size.
50373     */
50374     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
50375       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
50376     }
50377   }
50378   if( mutexOpen ){
50379     assert( sqlite3_mutex_held(mutexOpen) );
50380     sqlite3_mutex_leave(mutexOpen);
50381   }
50382   return rc;
50383 }
50384
50385 /*
50386 ** Decrement the BtShared.nRef counter.  When it reaches zero,
50387 ** remove the BtShared structure from the sharing list.  Return
50388 ** true if the BtShared.nRef counter reaches zero and return
50389 ** false if it is still positive.
50390 */
50391 static int removeFromSharingList(BtShared *pBt){
50392 #ifndef SQLITE_OMIT_SHARED_CACHE
50393   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
50394   BtShared *pList;
50395   int removed = 0;
50396
50397   assert( sqlite3_mutex_notheld(pBt->mutex) );
50398   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
50399   sqlite3_mutex_enter(pMaster);
50400   pBt->nRef--;
50401   if( pBt->nRef<=0 ){
50402     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
50403       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
50404     }else{
50405       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
50406       while( ALWAYS(pList) && pList->pNext!=pBt ){
50407         pList=pList->pNext;
50408       }
50409       if( ALWAYS(pList) ){
50410         pList->pNext = pBt->pNext;
50411       }
50412     }
50413     if( SQLITE_THREADSAFE ){
50414       sqlite3_mutex_free(pBt->mutex);
50415     }
50416     removed = 1;
50417   }
50418   sqlite3_mutex_leave(pMaster);
50419   return removed;
50420 #else
50421   return 1;
50422 #endif
50423 }
50424
50425 /*
50426 ** Make sure pBt->pTmpSpace points to an allocation of 
50427 ** MX_CELL_SIZE(pBt) bytes.
50428 */
50429 static void allocateTempSpace(BtShared *pBt){
50430   if( !pBt->pTmpSpace ){
50431     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
50432   }
50433 }
50434
50435 /*
50436 ** Free the pBt->pTmpSpace allocation
50437 */
50438 static void freeTempSpace(BtShared *pBt){
50439   sqlite3PageFree( pBt->pTmpSpace);
50440   pBt->pTmpSpace = 0;
50441 }
50442
50443 /*
50444 ** Close an open database and invalidate all cursors.
50445 */
50446 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
50447   BtShared *pBt = p->pBt;
50448   BtCursor *pCur;
50449
50450   /* Close all cursors opened via this handle.  */
50451   assert( sqlite3_mutex_held(p->db->mutex) );
50452   sqlite3BtreeEnter(p);
50453   pCur = pBt->pCursor;
50454   while( pCur ){
50455     BtCursor *pTmp = pCur;
50456     pCur = pCur->pNext;
50457     if( pTmp->pBtree==p ){
50458       sqlite3BtreeCloseCursor(pTmp);
50459     }
50460   }
50461
50462   /* Rollback any active transaction and free the handle structure.
50463   ** The call to sqlite3BtreeRollback() drops any table-locks held by
50464   ** this handle.
50465   */
50466   sqlite3BtreeRollback(p, SQLITE_OK);
50467   sqlite3BtreeLeave(p);
50468
50469   /* If there are still other outstanding references to the shared-btree
50470   ** structure, return now. The remainder of this procedure cleans 
50471   ** up the shared-btree.
50472   */
50473   assert( p->wantToLock==0 && p->locked==0 );
50474   if( !p->sharable || removeFromSharingList(pBt) ){
50475     /* The pBt is no longer on the sharing list, so we can access
50476     ** it without having to hold the mutex.
50477     **
50478     ** Clean out and delete the BtShared object.
50479     */
50480     assert( !pBt->pCursor );
50481     sqlite3PagerClose(pBt->pPager);
50482     if( pBt->xFreeSchema && pBt->pSchema ){
50483       pBt->xFreeSchema(pBt->pSchema);
50484     }
50485     sqlite3DbFree(0, pBt->pSchema);
50486     freeTempSpace(pBt);
50487     sqlite3_free(pBt);
50488   }
50489
50490 #ifndef SQLITE_OMIT_SHARED_CACHE
50491   assert( p->wantToLock==0 );
50492   assert( p->locked==0 );
50493   if( p->pPrev ) p->pPrev->pNext = p->pNext;
50494   if( p->pNext ) p->pNext->pPrev = p->pPrev;
50495 #endif
50496
50497   sqlite3_free(p);
50498   return SQLITE_OK;
50499 }
50500
50501 /*
50502 ** Change the limit on the number of pages allowed in the cache.
50503 **
50504 ** The maximum number of cache pages is set to the absolute
50505 ** value of mxPage.  If mxPage is negative, the pager will
50506 ** operate asynchronously - it will not stop to do fsync()s
50507 ** to insure data is written to the disk surface before
50508 ** continuing.  Transactions still work if synchronous is off,
50509 ** and the database cannot be corrupted if this program
50510 ** crashes.  But if the operating system crashes or there is
50511 ** an abrupt power failure when synchronous is off, the database
50512 ** could be left in an inconsistent and unrecoverable state.
50513 ** Synchronous is on by default so database corruption is not
50514 ** normally a worry.
50515 */
50516 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
50517   BtShared *pBt = p->pBt;
50518   assert( sqlite3_mutex_held(p->db->mutex) );
50519   sqlite3BtreeEnter(p);
50520   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
50521   sqlite3BtreeLeave(p);
50522   return SQLITE_OK;
50523 }
50524
50525 /*
50526 ** Change the way data is synced to disk in order to increase or decrease
50527 ** how well the database resists damage due to OS crashes and power
50528 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
50529 ** there is a high probability of damage)  Level 2 is the default.  There
50530 ** is a very low but non-zero probability of damage.  Level 3 reduces the
50531 ** probability of damage to near zero but with a write performance reduction.
50532 */
50533 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
50534 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
50535   Btree *p,              /* The btree to set the safety level on */
50536   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
50537   int fullSync,          /* PRAGMA fullfsync. */
50538   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
50539 ){
50540   BtShared *pBt = p->pBt;
50541   assert( sqlite3_mutex_held(p->db->mutex) );
50542   assert( level>=1 && level<=3 );
50543   sqlite3BtreeEnter(p);
50544   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
50545   sqlite3BtreeLeave(p);
50546   return SQLITE_OK;
50547 }
50548 #endif
50549
50550 /*
50551 ** Return TRUE if the given btree is set to safety level 1.  In other
50552 ** words, return TRUE if no sync() occurs on the disk files.
50553 */
50554 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
50555   BtShared *pBt = p->pBt;
50556   int rc;
50557   assert( sqlite3_mutex_held(p->db->mutex) );  
50558   sqlite3BtreeEnter(p);
50559   assert( pBt && pBt->pPager );
50560   rc = sqlite3PagerNosync(pBt->pPager);
50561   sqlite3BtreeLeave(p);
50562   return rc;
50563 }
50564
50565 /*
50566 ** Change the default pages size and the number of reserved bytes per page.
50567 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
50568 ** without changing anything.
50569 **
50570 ** The page size must be a power of 2 between 512 and 65536.  If the page
50571 ** size supplied does not meet this constraint then the page size is not
50572 ** changed.
50573 **
50574 ** Page sizes are constrained to be a power of two so that the region
50575 ** of the database file used for locking (beginning at PENDING_BYTE,
50576 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
50577 ** at the beginning of a page.
50578 **
50579 ** If parameter nReserve is less than zero, then the number of reserved
50580 ** bytes per page is left unchanged.
50581 **
50582 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
50583 ** and autovacuum mode can no longer be changed.
50584 */
50585 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
50586   int rc = SQLITE_OK;
50587   BtShared *pBt = p->pBt;
50588   assert( nReserve>=-1 && nReserve<=255 );
50589   sqlite3BtreeEnter(p);
50590   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
50591     sqlite3BtreeLeave(p);
50592     return SQLITE_READONLY;
50593   }
50594   if( nReserve<0 ){
50595     nReserve = pBt->pageSize - pBt->usableSize;
50596   }
50597   assert( nReserve>=0 && nReserve<=255 );
50598   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
50599         ((pageSize-1)&pageSize)==0 ){
50600     assert( (pageSize & 7)==0 );
50601     assert( !pBt->pPage1 && !pBt->pCursor );
50602     pBt->pageSize = (u32)pageSize;
50603     freeTempSpace(pBt);
50604   }
50605   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
50606   pBt->usableSize = pBt->pageSize - (u16)nReserve;
50607   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
50608   sqlite3BtreeLeave(p);
50609   return rc;
50610 }
50611
50612 /*
50613 ** Return the currently defined page size
50614 */
50615 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
50616   return p->pBt->pageSize;
50617 }
50618
50619 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
50620 /*
50621 ** This function is similar to sqlite3BtreeGetReserve(), except that it
50622 ** may only be called if it is guaranteed that the b-tree mutex is already
50623 ** held.
50624 **
50625 ** This is useful in one special case in the backup API code where it is
50626 ** known that the shared b-tree mutex is held, but the mutex on the 
50627 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
50628 ** were to be called, it might collide with some other operation on the
50629 ** database handle that owns *p, causing undefined behavior.
50630 */
50631 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
50632   assert( sqlite3_mutex_held(p->pBt->mutex) );
50633   return p->pBt->pageSize - p->pBt->usableSize;
50634 }
50635 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
50636
50637 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
50638 /*
50639 ** Return the number of bytes of space at the end of every page that
50640 ** are intentually left unused.  This is the "reserved" space that is
50641 ** sometimes used by extensions.
50642 */
50643 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
50644   int n;
50645   sqlite3BtreeEnter(p);
50646   n = p->pBt->pageSize - p->pBt->usableSize;
50647   sqlite3BtreeLeave(p);
50648   return n;
50649 }
50650
50651 /*
50652 ** Set the maximum page count for a database if mxPage is positive.
50653 ** No changes are made if mxPage is 0 or negative.
50654 ** Regardless of the value of mxPage, return the maximum page count.
50655 */
50656 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
50657   int n;
50658   sqlite3BtreeEnter(p);
50659   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
50660   sqlite3BtreeLeave(p);
50661   return n;
50662 }
50663
50664 /*
50665 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
50666 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
50667 ** setting after the change.
50668 */
50669 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
50670   int b;
50671   if( p==0 ) return 0;
50672   sqlite3BtreeEnter(p);
50673   if( newFlag>=0 ){
50674     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
50675     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
50676   } 
50677   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
50678   sqlite3BtreeLeave(p);
50679   return b;
50680 }
50681 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
50682
50683 /*
50684 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
50685 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
50686 ** is disabled. The default value for the auto-vacuum property is 
50687 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
50688 */
50689 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
50690 #ifdef SQLITE_OMIT_AUTOVACUUM
50691   return SQLITE_READONLY;
50692 #else
50693   BtShared *pBt = p->pBt;
50694   int rc = SQLITE_OK;
50695   u8 av = (u8)autoVacuum;
50696
50697   sqlite3BtreeEnter(p);
50698   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
50699     rc = SQLITE_READONLY;
50700   }else{
50701     pBt->autoVacuum = av ?1:0;
50702     pBt->incrVacuum = av==2 ?1:0;
50703   }
50704   sqlite3BtreeLeave(p);
50705   return rc;
50706 #endif
50707 }
50708
50709 /*
50710 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
50711 ** enabled 1 is returned. Otherwise 0.
50712 */
50713 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
50714 #ifdef SQLITE_OMIT_AUTOVACUUM
50715   return BTREE_AUTOVACUUM_NONE;
50716 #else
50717   int rc;
50718   sqlite3BtreeEnter(p);
50719   rc = (
50720     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
50721     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
50722     BTREE_AUTOVACUUM_INCR
50723   );
50724   sqlite3BtreeLeave(p);
50725   return rc;
50726 #endif
50727 }
50728
50729
50730 /*
50731 ** Get a reference to pPage1 of the database file.  This will
50732 ** also acquire a readlock on that file.
50733 **
50734 ** SQLITE_OK is returned on success.  If the file is not a
50735 ** well-formed database file, then SQLITE_CORRUPT is returned.
50736 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
50737 ** is returned if we run out of memory. 
50738 */
50739 static int lockBtree(BtShared *pBt){
50740   int rc;              /* Result code from subfunctions */
50741   MemPage *pPage1;     /* Page 1 of the database file */
50742   int nPage;           /* Number of pages in the database */
50743   int nPageFile = 0;   /* Number of pages in the database file */
50744   int nPageHeader;     /* Number of pages in the database according to hdr */
50745
50746   assert( sqlite3_mutex_held(pBt->mutex) );
50747   assert( pBt->pPage1==0 );
50748   rc = sqlite3PagerSharedLock(pBt->pPager);
50749   if( rc!=SQLITE_OK ) return rc;
50750   rc = btreeGetPage(pBt, 1, &pPage1, 0);
50751   if( rc!=SQLITE_OK ) return rc;
50752
50753   /* Do some checking to help insure the file we opened really is
50754   ** a valid database file. 
50755   */
50756   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
50757   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
50758   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
50759     nPage = nPageFile;
50760   }
50761   if( nPage>0 ){
50762     u32 pageSize;
50763     u32 usableSize;
50764     u8 *page1 = pPage1->aData;
50765     rc = SQLITE_NOTADB;
50766     if( memcmp(page1, zMagicHeader, 16)!=0 ){
50767       goto page1_init_failed;
50768     }
50769
50770 #ifdef SQLITE_OMIT_WAL
50771     if( page1[18]>1 ){
50772       pBt->btsFlags |= BTS_READ_ONLY;
50773     }
50774     if( page1[19]>1 ){
50775       goto page1_init_failed;
50776     }
50777 #else
50778     if( page1[18]>2 ){
50779       pBt->btsFlags |= BTS_READ_ONLY;
50780     }
50781     if( page1[19]>2 ){
50782       goto page1_init_failed;
50783     }
50784
50785     /* If the write version is set to 2, this database should be accessed
50786     ** in WAL mode. If the log is not already open, open it now. Then 
50787     ** return SQLITE_OK and return without populating BtShared.pPage1.
50788     ** The caller detects this and calls this function again. This is
50789     ** required as the version of page 1 currently in the page1 buffer
50790     ** may not be the latest version - there may be a newer one in the log
50791     ** file.
50792     */
50793     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
50794       int isOpen = 0;
50795       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
50796       if( rc!=SQLITE_OK ){
50797         goto page1_init_failed;
50798       }else if( isOpen==0 ){
50799         releasePage(pPage1);
50800         return SQLITE_OK;
50801       }
50802       rc = SQLITE_NOTADB;
50803     }
50804 #endif
50805
50806     /* The maximum embedded fraction must be exactly 25%.  And the minimum
50807     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
50808     ** The original design allowed these amounts to vary, but as of
50809     ** version 3.6.0, we require them to be fixed.
50810     */
50811     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
50812       goto page1_init_failed;
50813     }
50814     pageSize = (page1[16]<<8) | (page1[17]<<16);
50815     if( ((pageSize-1)&pageSize)!=0
50816      || pageSize>SQLITE_MAX_PAGE_SIZE 
50817      || pageSize<=256 
50818     ){
50819       goto page1_init_failed;
50820     }
50821     assert( (pageSize & 7)==0 );
50822     usableSize = pageSize - page1[20];
50823     if( (u32)pageSize!=pBt->pageSize ){
50824       /* After reading the first page of the database assuming a page size
50825       ** of BtShared.pageSize, we have discovered that the page-size is
50826       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
50827       ** zero and return SQLITE_OK. The caller will call this function
50828       ** again with the correct page-size.
50829       */
50830       releasePage(pPage1);
50831       pBt->usableSize = usableSize;
50832       pBt->pageSize = pageSize;
50833       freeTempSpace(pBt);
50834       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
50835                                    pageSize-usableSize);
50836       return rc;
50837     }
50838     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
50839       rc = SQLITE_CORRUPT_BKPT;
50840       goto page1_init_failed;
50841     }
50842     if( usableSize<480 ){
50843       goto page1_init_failed;
50844     }
50845     pBt->pageSize = pageSize;
50846     pBt->usableSize = usableSize;
50847 #ifndef SQLITE_OMIT_AUTOVACUUM
50848     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
50849     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
50850 #endif
50851   }
50852
50853   /* maxLocal is the maximum amount of payload to store locally for
50854   ** a cell.  Make sure it is small enough so that at least minFanout
50855   ** cells can will fit on one page.  We assume a 10-byte page header.
50856   ** Besides the payload, the cell must store:
50857   **     2-byte pointer to the cell
50858   **     4-byte child pointer
50859   **     9-byte nKey value
50860   **     4-byte nData value
50861   **     4-byte overflow page pointer
50862   ** So a cell consists of a 2-byte pointer, a header which is as much as
50863   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
50864   ** page pointer.
50865   */
50866   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
50867   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
50868   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
50869   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
50870   if( pBt->maxLocal>127 ){
50871     pBt->max1bytePayload = 127;
50872   }else{
50873     pBt->max1bytePayload = (u8)pBt->maxLocal;
50874   }
50875   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
50876   pBt->pPage1 = pPage1;
50877   pBt->nPage = nPage;
50878   return SQLITE_OK;
50879
50880 page1_init_failed:
50881   releasePage(pPage1);
50882   pBt->pPage1 = 0;
50883   return rc;
50884 }
50885
50886 /*
50887 ** If there are no outstanding cursors and we are not in the middle
50888 ** of a transaction but there is a read lock on the database, then
50889 ** this routine unrefs the first page of the database file which 
50890 ** has the effect of releasing the read lock.
50891 **
50892 ** If there is a transaction in progress, this routine is a no-op.
50893 */
50894 static void unlockBtreeIfUnused(BtShared *pBt){
50895   assert( sqlite3_mutex_held(pBt->mutex) );
50896   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
50897   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
50898     assert( pBt->pPage1->aData );
50899     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
50900     assert( pBt->pPage1->aData );
50901     releasePage(pBt->pPage1);
50902     pBt->pPage1 = 0;
50903   }
50904 }
50905
50906 /*
50907 ** If pBt points to an empty file then convert that empty file
50908 ** into a new empty database by initializing the first page of
50909 ** the database.
50910 */
50911 static int newDatabase(BtShared *pBt){
50912   MemPage *pP1;
50913   unsigned char *data;
50914   int rc;
50915
50916   assert( sqlite3_mutex_held(pBt->mutex) );
50917   if( pBt->nPage>0 ){
50918     return SQLITE_OK;
50919   }
50920   pP1 = pBt->pPage1;
50921   assert( pP1!=0 );
50922   data = pP1->aData;
50923   rc = sqlite3PagerWrite(pP1->pDbPage);
50924   if( rc ) return rc;
50925   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
50926   assert( sizeof(zMagicHeader)==16 );
50927   data[16] = (u8)((pBt->pageSize>>8)&0xff);
50928   data[17] = (u8)((pBt->pageSize>>16)&0xff);
50929   data[18] = 1;
50930   data[19] = 1;
50931   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
50932   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
50933   data[21] = 64;
50934   data[22] = 32;
50935   data[23] = 32;
50936   memset(&data[24], 0, 100-24);
50937   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
50938   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
50939 #ifndef SQLITE_OMIT_AUTOVACUUM
50940   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
50941   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
50942   put4byte(&data[36 + 4*4], pBt->autoVacuum);
50943   put4byte(&data[36 + 7*4], pBt->incrVacuum);
50944 #endif
50945   pBt->nPage = 1;
50946   data[31] = 1;
50947   return SQLITE_OK;
50948 }
50949
50950 /*
50951 ** Initialize the first page of the database file (creating a database
50952 ** consisting of a single page and no schema objects). Return SQLITE_OK
50953 ** if successful, or an SQLite error code otherwise.
50954 */
50955 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
50956   int rc;
50957   sqlite3BtreeEnter(p);
50958   p->pBt->nPage = 0;
50959   rc = newDatabase(p->pBt);
50960   sqlite3BtreeLeave(p);
50961   return rc;
50962 }
50963
50964 /*
50965 ** Attempt to start a new transaction. A write-transaction
50966 ** is started if the second argument is nonzero, otherwise a read-
50967 ** transaction.  If the second argument is 2 or more and exclusive
50968 ** transaction is started, meaning that no other process is allowed
50969 ** to access the database.  A preexisting transaction may not be
50970 ** upgraded to exclusive by calling this routine a second time - the
50971 ** exclusivity flag only works for a new transaction.
50972 **
50973 ** A write-transaction must be started before attempting any 
50974 ** changes to the database.  None of the following routines 
50975 ** will work unless a transaction is started first:
50976 **
50977 **      sqlite3BtreeCreateTable()
50978 **      sqlite3BtreeCreateIndex()
50979 **      sqlite3BtreeClearTable()
50980 **      sqlite3BtreeDropTable()
50981 **      sqlite3BtreeInsert()
50982 **      sqlite3BtreeDelete()
50983 **      sqlite3BtreeUpdateMeta()
50984 **
50985 ** If an initial attempt to acquire the lock fails because of lock contention
50986 ** and the database was previously unlocked, then invoke the busy handler
50987 ** if there is one.  But if there was previously a read-lock, do not
50988 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
50989 ** returned when there is already a read-lock in order to avoid a deadlock.
50990 **
50991 ** Suppose there are two processes A and B.  A has a read lock and B has
50992 ** a reserved lock.  B tries to promote to exclusive but is blocked because
50993 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
50994 ** One or the other of the two processes must give way or there can be
50995 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
50996 ** when A already has a read lock, we encourage A to give up and let B
50997 ** proceed.
50998 */
50999 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
51000   sqlite3 *pBlock = 0;
51001   BtShared *pBt = p->pBt;
51002   int rc = SQLITE_OK;
51003
51004   sqlite3BtreeEnter(p);
51005   btreeIntegrity(p);
51006
51007   /* If the btree is already in a write-transaction, or it
51008   ** is already in a read-transaction and a read-transaction
51009   ** is requested, this is a no-op.
51010   */
51011   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
51012     goto trans_begun;
51013   }
51014   assert( IfNotOmitAV(pBt->bDoTruncate)==0 );
51015
51016   /* Write transactions are not possible on a read-only database */
51017   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
51018     rc = SQLITE_READONLY;
51019     goto trans_begun;
51020   }
51021
51022 #ifndef SQLITE_OMIT_SHARED_CACHE
51023   /* If another database handle has already opened a write transaction 
51024   ** on this shared-btree structure and a second write transaction is
51025   ** requested, return SQLITE_LOCKED.
51026   */
51027   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
51028    || (pBt->btsFlags & BTS_PENDING)!=0
51029   ){
51030     pBlock = pBt->pWriter->db;
51031   }else if( wrflag>1 ){
51032     BtLock *pIter;
51033     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
51034       if( pIter->pBtree!=p ){
51035         pBlock = pIter->pBtree->db;
51036         break;
51037       }
51038     }
51039   }
51040   if( pBlock ){
51041     sqlite3ConnectionBlocked(p->db, pBlock);
51042     rc = SQLITE_LOCKED_SHAREDCACHE;
51043     goto trans_begun;
51044   }
51045 #endif
51046
51047   /* Any read-only or read-write transaction implies a read-lock on 
51048   ** page 1. So if some other shared-cache client already has a write-lock 
51049   ** on page 1, the transaction cannot be opened. */
51050   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
51051   if( SQLITE_OK!=rc ) goto trans_begun;
51052
51053   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
51054   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
51055   do {
51056     /* Call lockBtree() until either pBt->pPage1 is populated or
51057     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
51058     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
51059     ** reading page 1 it discovers that the page-size of the database 
51060     ** file is not pBt->pageSize. In this case lockBtree() will update
51061     ** pBt->pageSize to the page-size of the file on disk.
51062     */
51063     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
51064
51065     if( rc==SQLITE_OK && wrflag ){
51066       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
51067         rc = SQLITE_READONLY;
51068       }else{
51069         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
51070         if( rc==SQLITE_OK ){
51071           rc = newDatabase(pBt);
51072         }
51073       }
51074     }
51075   
51076     if( rc!=SQLITE_OK ){
51077       unlockBtreeIfUnused(pBt);
51078     }
51079   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
51080           btreeInvokeBusyHandler(pBt) );
51081
51082   if( rc==SQLITE_OK ){
51083     if( p->inTrans==TRANS_NONE ){
51084       pBt->nTransaction++;
51085 #ifndef SQLITE_OMIT_SHARED_CACHE
51086       if( p->sharable ){
51087         assert( p->lock.pBtree==p && p->lock.iTable==1 );
51088         p->lock.eLock = READ_LOCK;
51089         p->lock.pNext = pBt->pLock;
51090         pBt->pLock = &p->lock;
51091       }
51092 #endif
51093     }
51094     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
51095     if( p->inTrans>pBt->inTransaction ){
51096       pBt->inTransaction = p->inTrans;
51097     }
51098     if( wrflag ){
51099       MemPage *pPage1 = pBt->pPage1;
51100 #ifndef SQLITE_OMIT_SHARED_CACHE
51101       assert( !pBt->pWriter );
51102       pBt->pWriter = p;
51103       pBt->btsFlags &= ~BTS_EXCLUSIVE;
51104       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
51105 #endif
51106
51107       /* If the db-size header field is incorrect (as it may be if an old
51108       ** client has been writing the database file), update it now. Doing
51109       ** this sooner rather than later means the database size can safely 
51110       ** re-read the database size from page 1 if a savepoint or transaction
51111       ** rollback occurs within the transaction.
51112       */
51113       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
51114         rc = sqlite3PagerWrite(pPage1->pDbPage);
51115         if( rc==SQLITE_OK ){
51116           put4byte(&pPage1->aData[28], pBt->nPage);
51117         }
51118       }
51119     }
51120   }
51121
51122
51123 trans_begun:
51124   if( rc==SQLITE_OK && wrflag ){
51125     /* This call makes sure that the pager has the correct number of
51126     ** open savepoints. If the second parameter is greater than 0 and
51127     ** the sub-journal is not already open, then it will be opened here.
51128     */
51129     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
51130   }
51131
51132   btreeIntegrity(p);
51133   sqlite3BtreeLeave(p);
51134   return rc;
51135 }
51136
51137 #ifndef SQLITE_OMIT_AUTOVACUUM
51138
51139 /*
51140 ** Set the pointer-map entries for all children of page pPage. Also, if
51141 ** pPage contains cells that point to overflow pages, set the pointer
51142 ** map entries for the overflow pages as well.
51143 */
51144 static int setChildPtrmaps(MemPage *pPage){
51145   int i;                             /* Counter variable */
51146   int nCell;                         /* Number of cells in page pPage */
51147   int rc;                            /* Return code */
51148   BtShared *pBt = pPage->pBt;
51149   u8 isInitOrig = pPage->isInit;
51150   Pgno pgno = pPage->pgno;
51151
51152   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51153   rc = btreeInitPage(pPage);
51154   if( rc!=SQLITE_OK ){
51155     goto set_child_ptrmaps_out;
51156   }
51157   nCell = pPage->nCell;
51158
51159   for(i=0; i<nCell; i++){
51160     u8 *pCell = findCell(pPage, i);
51161
51162     ptrmapPutOvflPtr(pPage, pCell, &rc);
51163
51164     if( !pPage->leaf ){
51165       Pgno childPgno = get4byte(pCell);
51166       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
51167     }
51168   }
51169
51170   if( !pPage->leaf ){
51171     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51172     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
51173   }
51174
51175 set_child_ptrmaps_out:
51176   pPage->isInit = isInitOrig;
51177   return rc;
51178 }
51179
51180 /*
51181 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
51182 ** that it points to iTo. Parameter eType describes the type of pointer to
51183 ** be modified, as  follows:
51184 **
51185 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
51186 **                   page of pPage.
51187 **
51188 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
51189 **                   page pointed to by one of the cells on pPage.
51190 **
51191 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
51192 **                   overflow page in the list.
51193 */
51194 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
51195   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51196   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51197   if( eType==PTRMAP_OVERFLOW2 ){
51198     /* The pointer is always the first 4 bytes of the page in this case.  */
51199     if( get4byte(pPage->aData)!=iFrom ){
51200       return SQLITE_CORRUPT_BKPT;
51201     }
51202     put4byte(pPage->aData, iTo);
51203   }else{
51204     u8 isInitOrig = pPage->isInit;
51205     int i;
51206     int nCell;
51207
51208     btreeInitPage(pPage);
51209     nCell = pPage->nCell;
51210
51211     for(i=0; i<nCell; i++){
51212       u8 *pCell = findCell(pPage, i);
51213       if( eType==PTRMAP_OVERFLOW1 ){
51214         CellInfo info;
51215         btreeParseCellPtr(pPage, pCell, &info);
51216         if( info.iOverflow
51217          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
51218          && iFrom==get4byte(&pCell[info.iOverflow])
51219         ){
51220           put4byte(&pCell[info.iOverflow], iTo);
51221           break;
51222         }
51223       }else{
51224         if( get4byte(pCell)==iFrom ){
51225           put4byte(pCell, iTo);
51226           break;
51227         }
51228       }
51229     }
51230   
51231     if( i==nCell ){
51232       if( eType!=PTRMAP_BTREE || 
51233           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
51234         return SQLITE_CORRUPT_BKPT;
51235       }
51236       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
51237     }
51238
51239     pPage->isInit = isInitOrig;
51240   }
51241   return SQLITE_OK;
51242 }
51243
51244
51245 /*
51246 ** Move the open database page pDbPage to location iFreePage in the 
51247 ** database. The pDbPage reference remains valid.
51248 **
51249 ** The isCommit flag indicates that there is no need to remember that
51250 ** the journal needs to be sync()ed before database page pDbPage->pgno 
51251 ** can be written to. The caller has already promised not to write to that
51252 ** page.
51253 */
51254 static int relocatePage(
51255   BtShared *pBt,           /* Btree */
51256   MemPage *pDbPage,        /* Open page to move */
51257   u8 eType,                /* Pointer map 'type' entry for pDbPage */
51258   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
51259   Pgno iFreePage,          /* The location to move pDbPage to */
51260   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
51261 ){
51262   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
51263   Pgno iDbPage = pDbPage->pgno;
51264   Pager *pPager = pBt->pPager;
51265   int rc;
51266
51267   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
51268       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
51269   assert( sqlite3_mutex_held(pBt->mutex) );
51270   assert( pDbPage->pBt==pBt );
51271
51272   /* Move page iDbPage from its current location to page number iFreePage */
51273   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
51274       iDbPage, iFreePage, iPtrPage, eType));
51275   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
51276   if( rc!=SQLITE_OK ){
51277     return rc;
51278   }
51279   pDbPage->pgno = iFreePage;
51280
51281   /* If pDbPage was a btree-page, then it may have child pages and/or cells
51282   ** that point to overflow pages. The pointer map entries for all these
51283   ** pages need to be changed.
51284   **
51285   ** If pDbPage is an overflow page, then the first 4 bytes may store a
51286   ** pointer to a subsequent overflow page. If this is the case, then
51287   ** the pointer map needs to be updated for the subsequent overflow page.
51288   */
51289   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
51290     rc = setChildPtrmaps(pDbPage);
51291     if( rc!=SQLITE_OK ){
51292       return rc;
51293     }
51294   }else{
51295     Pgno nextOvfl = get4byte(pDbPage->aData);
51296     if( nextOvfl!=0 ){
51297       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
51298       if( rc!=SQLITE_OK ){
51299         return rc;
51300       }
51301     }
51302   }
51303
51304   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
51305   ** that it points at iFreePage. Also fix the pointer map entry for
51306   ** iPtrPage.
51307   */
51308   if( eType!=PTRMAP_ROOTPAGE ){
51309     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
51310     if( rc!=SQLITE_OK ){
51311       return rc;
51312     }
51313     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
51314     if( rc!=SQLITE_OK ){
51315       releasePage(pPtrPage);
51316       return rc;
51317     }
51318     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
51319     releasePage(pPtrPage);
51320     if( rc==SQLITE_OK ){
51321       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
51322     }
51323   }
51324   return rc;
51325 }
51326
51327 /* Forward declaration required by incrVacuumStep(). */
51328 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
51329
51330 /*
51331 ** Perform a single step of an incremental-vacuum. If successful, return
51332 ** SQLITE_OK. If there is no work to do (and therefore no point in 
51333 ** calling this function again), return SQLITE_DONE. Or, if an error 
51334 ** occurs, return some other error code.
51335 **
51336 ** More specificly, this function attempts to re-organize the database so 
51337 ** that the last page of the file currently in use is no longer in use.
51338 **
51339 ** Parameter nFin is the number of pages that this database would contain
51340 ** were this function called until it returns SQLITE_DONE.
51341 **
51342 ** If the bCommit parameter is non-zero, this function assumes that the 
51343 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE 
51344 ** or an error. bCommit is passed true for an auto-vacuum-on-commmit 
51345 ** operation, or false for an incremental vacuum.
51346 */
51347 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
51348   Pgno nFreeList;           /* Number of pages still on the free-list */
51349   int rc;
51350
51351   assert( sqlite3_mutex_held(pBt->mutex) );
51352   assert( iLastPg>nFin );
51353
51354   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
51355     u8 eType;
51356     Pgno iPtrPage;
51357
51358     nFreeList = get4byte(&pBt->pPage1->aData[36]);
51359     if( nFreeList==0 ){
51360       return SQLITE_DONE;
51361     }
51362
51363     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
51364     if( rc!=SQLITE_OK ){
51365       return rc;
51366     }
51367     if( eType==PTRMAP_ROOTPAGE ){
51368       return SQLITE_CORRUPT_BKPT;
51369     }
51370
51371     if( eType==PTRMAP_FREEPAGE ){
51372       if( bCommit==0 ){
51373         /* Remove the page from the files free-list. This is not required
51374         ** if bCommit is non-zero. In that case, the free-list will be
51375         ** truncated to zero after this function returns, so it doesn't 
51376         ** matter if it still contains some garbage entries.
51377         */
51378         Pgno iFreePg;
51379         MemPage *pFreePg;
51380         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
51381         if( rc!=SQLITE_OK ){
51382           return rc;
51383         }
51384         assert( iFreePg==iLastPg );
51385         releasePage(pFreePg);
51386       }
51387     } else {
51388       Pgno iFreePg;             /* Index of free page to move pLastPg to */
51389       MemPage *pLastPg;
51390       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
51391       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
51392
51393       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
51394       if( rc!=SQLITE_OK ){
51395         return rc;
51396       }
51397
51398       /* If bCommit is zero, this loop runs exactly once and page pLastPg
51399       ** is swapped with the first free page pulled off the free list.
51400       **
51401       ** On the other hand, if bCommit is greater than zero, then keep
51402       ** looping until a free-page located within the first nFin pages
51403       ** of the file is found.
51404       */
51405       if( bCommit==0 ){
51406         eMode = BTALLOC_LE;
51407         iNear = nFin;
51408       }
51409       do {
51410         MemPage *pFreePg;
51411         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
51412         if( rc!=SQLITE_OK ){
51413           releasePage(pLastPg);
51414           return rc;
51415         }
51416         releasePage(pFreePg);
51417       }while( bCommit && iFreePg>nFin );
51418       assert( iFreePg<iLastPg );
51419       
51420       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
51421       releasePage(pLastPg);
51422       if( rc!=SQLITE_OK ){
51423         return rc;
51424       }
51425     }
51426   }
51427
51428   if( bCommit==0 ){
51429     do {
51430       iLastPg--;
51431     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
51432     pBt->bDoTruncate = 1;
51433     pBt->nPage = iLastPg;
51434   }
51435   return SQLITE_OK;
51436 }
51437
51438 /*
51439 ** The database opened by the first argument is an auto-vacuum database
51440 ** nOrig pages in size containing nFree free pages. Return the expected 
51441 ** size of the database in pages following an auto-vacuum operation.
51442 */
51443 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
51444   int nEntry;                     /* Number of entries on one ptrmap page */
51445   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
51446   Pgno nFin;                      /* Return value */
51447
51448   nEntry = pBt->usableSize/5;
51449   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
51450   nFin = nOrig - nFree - nPtrmap;
51451   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
51452     nFin--;
51453   }
51454   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
51455     nFin--;
51456   }
51457
51458   return nFin;
51459 }
51460
51461 /*
51462 ** A write-transaction must be opened before calling this function.
51463 ** It performs a single unit of work towards an incremental vacuum.
51464 **
51465 ** If the incremental vacuum is finished after this function has run,
51466 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
51467 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
51468 */
51469 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
51470   int rc;
51471   BtShared *pBt = p->pBt;
51472
51473   sqlite3BtreeEnter(p);
51474   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
51475   if( !pBt->autoVacuum ){
51476     rc = SQLITE_DONE;
51477   }else{
51478     Pgno nOrig = btreePagecount(pBt);
51479     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
51480     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
51481
51482     if( nOrig<nFin ){
51483       rc = SQLITE_CORRUPT_BKPT;
51484     }else if( nFree>0 ){
51485       invalidateAllOverflowCache(pBt);
51486       rc = incrVacuumStep(pBt, nFin, nOrig, 0);
51487       if( rc==SQLITE_OK ){
51488         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51489         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
51490       }
51491     }else{
51492       rc = SQLITE_DONE;
51493     }
51494   }
51495   sqlite3BtreeLeave(p);
51496   return rc;
51497 }
51498
51499 /*
51500 ** This routine is called prior to sqlite3PagerCommit when a transaction
51501 ** is commited for an auto-vacuum database.
51502 **
51503 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
51504 ** the database file should be truncated to during the commit process. 
51505 ** i.e. the database has been reorganized so that only the first *pnTrunc
51506 ** pages are in use.
51507 */
51508 static int autoVacuumCommit(BtShared *pBt){
51509   int rc = SQLITE_OK;
51510   Pager *pPager = pBt->pPager;
51511   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
51512
51513   assert( sqlite3_mutex_held(pBt->mutex) );
51514   invalidateAllOverflowCache(pBt);
51515   assert(pBt->autoVacuum);
51516   if( !pBt->incrVacuum ){
51517     Pgno nFin;         /* Number of pages in database after autovacuuming */
51518     Pgno nFree;        /* Number of pages on the freelist initially */
51519     Pgno iFree;        /* The next page to be freed */
51520     Pgno nOrig;        /* Database size before freeing */
51521
51522     nOrig = btreePagecount(pBt);
51523     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
51524       /* It is not possible to create a database for which the final page
51525       ** is either a pointer-map page or the pending-byte page. If one
51526       ** is encountered, this indicates corruption.
51527       */
51528       return SQLITE_CORRUPT_BKPT;
51529     }
51530
51531     nFree = get4byte(&pBt->pPage1->aData[36]);
51532     nFin = finalDbSize(pBt, nOrig, nFree);
51533     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
51534
51535     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
51536       rc = incrVacuumStep(pBt, nFin, iFree, 1);
51537     }
51538     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
51539       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51540       put4byte(&pBt->pPage1->aData[32], 0);
51541       put4byte(&pBt->pPage1->aData[36], 0);
51542       put4byte(&pBt->pPage1->aData[28], nFin);
51543       pBt->bDoTruncate = 1;
51544       pBt->nPage = nFin;
51545     }
51546     if( rc!=SQLITE_OK ){
51547       sqlite3PagerRollback(pPager);
51548     }
51549   }
51550
51551   assert( nRef==sqlite3PagerRefcount(pPager) );
51552   return rc;
51553 }
51554
51555 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
51556 # define setChildPtrmaps(x) SQLITE_OK
51557 #endif
51558
51559 /*
51560 ** This routine does the first phase of a two-phase commit.  This routine
51561 ** causes a rollback journal to be created (if it does not already exist)
51562 ** and populated with enough information so that if a power loss occurs
51563 ** the database can be restored to its original state by playing back
51564 ** the journal.  Then the contents of the journal are flushed out to
51565 ** the disk.  After the journal is safely on oxide, the changes to the
51566 ** database are written into the database file and flushed to oxide.
51567 ** At the end of this call, the rollback journal still exists on the
51568 ** disk and we are still holding all locks, so the transaction has not
51569 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
51570 ** commit process.
51571 **
51572 ** This call is a no-op if no write-transaction is currently active on pBt.
51573 **
51574 ** Otherwise, sync the database file for the btree pBt. zMaster points to
51575 ** the name of a master journal file that should be written into the
51576 ** individual journal file, or is NULL, indicating no master journal file 
51577 ** (single database transaction).
51578 **
51579 ** When this is called, the master journal should already have been
51580 ** created, populated with this journal pointer and synced to disk.
51581 **
51582 ** Once this is routine has returned, the only thing required to commit
51583 ** the write-transaction for this database file is to delete the journal.
51584 */
51585 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
51586   int rc = SQLITE_OK;
51587   if( p->inTrans==TRANS_WRITE ){
51588     BtShared *pBt = p->pBt;
51589     sqlite3BtreeEnter(p);
51590 #ifndef SQLITE_OMIT_AUTOVACUUM
51591     if( pBt->autoVacuum ){
51592       rc = autoVacuumCommit(pBt);
51593       if( rc!=SQLITE_OK ){
51594         sqlite3BtreeLeave(p);
51595         return rc;
51596       }
51597     }
51598     if( pBt->bDoTruncate ){
51599       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
51600     }
51601 #endif
51602     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
51603     sqlite3BtreeLeave(p);
51604   }
51605   return rc;
51606 }
51607
51608 /*
51609 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
51610 ** at the conclusion of a transaction.
51611 */
51612 static void btreeEndTransaction(Btree *p){
51613   BtShared *pBt = p->pBt;
51614   assert( sqlite3BtreeHoldsMutex(p) );
51615
51616 #ifndef SQLITE_OMIT_AUTOVACUUM
51617   pBt->bDoTruncate = 0;
51618 #endif
51619   btreeClearHasContent(pBt);
51620   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
51621     /* If there are other active statements that belong to this database
51622     ** handle, downgrade to a read-only transaction. The other statements
51623     ** may still be reading from the database.  */
51624     downgradeAllSharedCacheTableLocks(p);
51625     p->inTrans = TRANS_READ;
51626   }else{
51627     /* If the handle had any kind of transaction open, decrement the 
51628     ** transaction count of the shared btree. If the transaction count 
51629     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
51630     ** call below will unlock the pager.  */
51631     if( p->inTrans!=TRANS_NONE ){
51632       clearAllSharedCacheTableLocks(p);
51633       pBt->nTransaction--;
51634       if( 0==pBt->nTransaction ){
51635         pBt->inTransaction = TRANS_NONE;
51636       }
51637     }
51638
51639     /* Set the current transaction state to TRANS_NONE and unlock the 
51640     ** pager if this call closed the only read or write transaction.  */
51641     p->inTrans = TRANS_NONE;
51642     unlockBtreeIfUnused(pBt);
51643   }
51644
51645   btreeIntegrity(p);
51646 }
51647
51648 /*
51649 ** Commit the transaction currently in progress.
51650 **
51651 ** This routine implements the second phase of a 2-phase commit.  The
51652 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
51653 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
51654 ** routine did all the work of writing information out to disk and flushing the
51655 ** contents so that they are written onto the disk platter.  All this
51656 ** routine has to do is delete or truncate or zero the header in the
51657 ** the rollback journal (which causes the transaction to commit) and
51658 ** drop locks.
51659 **
51660 ** Normally, if an error occurs while the pager layer is attempting to 
51661 ** finalize the underlying journal file, this function returns an error and
51662 ** the upper layer will attempt a rollback. However, if the second argument
51663 ** is non-zero then this b-tree transaction is part of a multi-file 
51664 ** transaction. In this case, the transaction has already been committed 
51665 ** (by deleting a master journal file) and the caller will ignore this 
51666 ** functions return code. So, even if an error occurs in the pager layer,
51667 ** reset the b-tree objects internal state to indicate that the write
51668 ** transaction has been closed. This is quite safe, as the pager will have
51669 ** transitioned to the error state.
51670 **
51671 ** This will release the write lock on the database file.  If there
51672 ** are no active cursors, it also releases the read lock.
51673 */
51674 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
51675
51676   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
51677   sqlite3BtreeEnter(p);
51678   btreeIntegrity(p);
51679
51680   /* If the handle has a write-transaction open, commit the shared-btrees 
51681   ** transaction and set the shared state to TRANS_READ.
51682   */
51683   if( p->inTrans==TRANS_WRITE ){
51684     int rc;
51685     BtShared *pBt = p->pBt;
51686     assert( pBt->inTransaction==TRANS_WRITE );
51687     assert( pBt->nTransaction>0 );
51688     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
51689     if( rc!=SQLITE_OK && bCleanup==0 ){
51690       sqlite3BtreeLeave(p);
51691       return rc;
51692     }
51693     pBt->inTransaction = TRANS_READ;
51694   }
51695
51696   btreeEndTransaction(p);
51697   sqlite3BtreeLeave(p);
51698   return SQLITE_OK;
51699 }
51700
51701 /*
51702 ** Do both phases of a commit.
51703 */
51704 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
51705   int rc;
51706   sqlite3BtreeEnter(p);
51707   rc = sqlite3BtreeCommitPhaseOne(p, 0);
51708   if( rc==SQLITE_OK ){
51709     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
51710   }
51711   sqlite3BtreeLeave(p);
51712   return rc;
51713 }
51714
51715 #ifndef NDEBUG
51716 /*
51717 ** Return the number of write-cursors open on this handle. This is for use
51718 ** in assert() expressions, so it is only compiled if NDEBUG is not
51719 ** defined.
51720 **
51721 ** For the purposes of this routine, a write-cursor is any cursor that
51722 ** is capable of writing to the databse.  That means the cursor was
51723 ** originally opened for writing and the cursor has not be disabled
51724 ** by having its state changed to CURSOR_FAULT.
51725 */
51726 static int countWriteCursors(BtShared *pBt){
51727   BtCursor *pCur;
51728   int r = 0;
51729   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
51730     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
51731   }
51732   return r;
51733 }
51734 #endif
51735
51736 /*
51737 ** This routine sets the state to CURSOR_FAULT and the error
51738 ** code to errCode for every cursor on BtShared that pBtree
51739 ** references.
51740 **
51741 ** Every cursor is tripped, including cursors that belong
51742 ** to other database connections that happen to be sharing
51743 ** the cache with pBtree.
51744 **
51745 ** This routine gets called when a rollback occurs.
51746 ** All cursors using the same cache must be tripped
51747 ** to prevent them from trying to use the btree after
51748 ** the rollback.  The rollback may have deleted tables
51749 ** or moved root pages, so it is not sufficient to
51750 ** save the state of the cursor.  The cursor must be
51751 ** invalidated.
51752 */
51753 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
51754   BtCursor *p;
51755   if( pBtree==0 ) return;
51756   sqlite3BtreeEnter(pBtree);
51757   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
51758     int i;
51759     sqlite3BtreeClearCursor(p);
51760     p->eState = CURSOR_FAULT;
51761     p->skipNext = errCode;
51762     for(i=0; i<=p->iPage; i++){
51763       releasePage(p->apPage[i]);
51764       p->apPage[i] = 0;
51765     }
51766   }
51767   sqlite3BtreeLeave(pBtree);
51768 }
51769
51770 /*
51771 ** Rollback the transaction in progress.  All cursors will be
51772 ** invalided by this operation.  Any attempt to use a cursor
51773 ** that was open at the beginning of this operation will result
51774 ** in an error.
51775 **
51776 ** This will release the write lock on the database file.  If there
51777 ** are no active cursors, it also releases the read lock.
51778 */
51779 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
51780   int rc;
51781   BtShared *pBt = p->pBt;
51782   MemPage *pPage1;
51783
51784   sqlite3BtreeEnter(p);
51785   if( tripCode==SQLITE_OK ){
51786     rc = tripCode = saveAllCursors(pBt, 0, 0);
51787   }else{
51788     rc = SQLITE_OK;
51789   }
51790   if( tripCode ){
51791     sqlite3BtreeTripAllCursors(p, tripCode);
51792   }
51793   btreeIntegrity(p);
51794
51795   if( p->inTrans==TRANS_WRITE ){
51796     int rc2;
51797
51798     assert( TRANS_WRITE==pBt->inTransaction );
51799     rc2 = sqlite3PagerRollback(pBt->pPager);
51800     if( rc2!=SQLITE_OK ){
51801       rc = rc2;
51802     }
51803
51804     /* The rollback may have destroyed the pPage1->aData value.  So
51805     ** call btreeGetPage() on page 1 again to make
51806     ** sure pPage1->aData is set correctly. */
51807     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
51808       int nPage = get4byte(28+(u8*)pPage1->aData);
51809       testcase( nPage==0 );
51810       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
51811       testcase( pBt->nPage!=nPage );
51812       pBt->nPage = nPage;
51813       releasePage(pPage1);
51814     }
51815     assert( countWriteCursors(pBt)==0 );
51816     pBt->inTransaction = TRANS_READ;
51817   }
51818
51819   btreeEndTransaction(p);
51820   sqlite3BtreeLeave(p);
51821   return rc;
51822 }
51823
51824 /*
51825 ** Start a statement subtransaction. The subtransaction can can be rolled
51826 ** back independently of the main transaction. You must start a transaction 
51827 ** before starting a subtransaction. The subtransaction is ended automatically 
51828 ** if the main transaction commits or rolls back.
51829 **
51830 ** Statement subtransactions are used around individual SQL statements
51831 ** that are contained within a BEGIN...COMMIT block.  If a constraint
51832 ** error occurs within the statement, the effect of that one statement
51833 ** can be rolled back without having to rollback the entire transaction.
51834 **
51835 ** A statement sub-transaction is implemented as an anonymous savepoint. The
51836 ** value passed as the second parameter is the total number of savepoints,
51837 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
51838 ** are no active savepoints and no other statement-transactions open,
51839 ** iStatement is 1. This anonymous savepoint can be released or rolled back
51840 ** using the sqlite3BtreeSavepoint() function.
51841 */
51842 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
51843   int rc;
51844   BtShared *pBt = p->pBt;
51845   sqlite3BtreeEnter(p);
51846   assert( p->inTrans==TRANS_WRITE );
51847   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
51848   assert( iStatement>0 );
51849   assert( iStatement>p->db->nSavepoint );
51850   assert( pBt->inTransaction==TRANS_WRITE );
51851   /* At the pager level, a statement transaction is a savepoint with
51852   ** an index greater than all savepoints created explicitly using
51853   ** SQL statements. It is illegal to open, release or rollback any
51854   ** such savepoints while the statement transaction savepoint is active.
51855   */
51856   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
51857   sqlite3BtreeLeave(p);
51858   return rc;
51859 }
51860
51861 /*
51862 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
51863 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
51864 ** savepoint identified by parameter iSavepoint, depending on the value 
51865 ** of op.
51866 **
51867 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
51868 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
51869 ** contents of the entire transaction are rolled back. This is different
51870 ** from a normal transaction rollback, as no locks are released and the
51871 ** transaction remains open.
51872 */
51873 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
51874   int rc = SQLITE_OK;
51875   if( p && p->inTrans==TRANS_WRITE ){
51876     BtShared *pBt = p->pBt;
51877     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
51878     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
51879     sqlite3BtreeEnter(p);
51880     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
51881     if( rc==SQLITE_OK ){
51882       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
51883         pBt->nPage = 0;
51884       }
51885       rc = newDatabase(pBt);
51886       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
51887
51888       /* The database size was written into the offset 28 of the header
51889       ** when the transaction started, so we know that the value at offset
51890       ** 28 is nonzero. */
51891       assert( pBt->nPage>0 );
51892     }
51893     sqlite3BtreeLeave(p);
51894   }
51895   return rc;
51896 }
51897
51898 /*
51899 ** Create a new cursor for the BTree whose root is on the page
51900 ** iTable. If a read-only cursor is requested, it is assumed that
51901 ** the caller already has at least a read-only transaction open
51902 ** on the database already. If a write-cursor is requested, then
51903 ** the caller is assumed to have an open write transaction.
51904 **
51905 ** If wrFlag==0, then the cursor can only be used for reading.
51906 ** If wrFlag==1, then the cursor can be used for reading or for
51907 ** writing if other conditions for writing are also met.  These
51908 ** are the conditions that must be met in order for writing to
51909 ** be allowed:
51910 **
51911 ** 1:  The cursor must have been opened with wrFlag==1
51912 **
51913 ** 2:  Other database connections that share the same pager cache
51914 **     but which are not in the READ_UNCOMMITTED state may not have
51915 **     cursors open with wrFlag==0 on the same table.  Otherwise
51916 **     the changes made by this write cursor would be visible to
51917 **     the read cursors in the other database connection.
51918 **
51919 ** 3:  The database must be writable (not on read-only media)
51920 **
51921 ** 4:  There must be an active transaction.
51922 **
51923 ** No checking is done to make sure that page iTable really is the
51924 ** root page of a b-tree.  If it is not, then the cursor acquired
51925 ** will not work correctly.
51926 **
51927 ** It is assumed that the sqlite3BtreeCursorZero() has been called
51928 ** on pCur to initialize the memory space prior to invoking this routine.
51929 */
51930 static int btreeCursor(
51931   Btree *p,                              /* The btree */
51932   int iTable,                            /* Root page of table to open */
51933   int wrFlag,                            /* 1 to write. 0 read-only */
51934   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
51935   BtCursor *pCur                         /* Space for new cursor */
51936 ){
51937   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
51938
51939   assert( sqlite3BtreeHoldsMutex(p) );
51940   assert( wrFlag==0 || wrFlag==1 );
51941
51942   /* The following assert statements verify that if this is a sharable 
51943   ** b-tree database, the connection is holding the required table locks, 
51944   ** and that no other connection has any open cursor that conflicts with 
51945   ** this lock.  */
51946   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
51947   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
51948
51949   /* Assert that the caller has opened the required transaction. */
51950   assert( p->inTrans>TRANS_NONE );
51951   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
51952   assert( pBt->pPage1 && pBt->pPage1->aData );
51953
51954   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
51955     return SQLITE_READONLY;
51956   }
51957   if( iTable==1 && btreePagecount(pBt)==0 ){
51958     assert( wrFlag==0 );
51959     iTable = 0;
51960   }
51961
51962   /* Now that no other errors can occur, finish filling in the BtCursor
51963   ** variables and link the cursor into the BtShared list.  */
51964   pCur->pgnoRoot = (Pgno)iTable;
51965   pCur->iPage = -1;
51966   pCur->pKeyInfo = pKeyInfo;
51967   pCur->pBtree = p;
51968   pCur->pBt = pBt;
51969   pCur->wrFlag = (u8)wrFlag;
51970   pCur->pNext = pBt->pCursor;
51971   if( pCur->pNext ){
51972     pCur->pNext->pPrev = pCur;
51973   }
51974   pBt->pCursor = pCur;
51975   pCur->eState = CURSOR_INVALID;
51976   pCur->cachedRowid = 0;
51977   return SQLITE_OK;
51978 }
51979 SQLITE_PRIVATE int sqlite3BtreeCursor(
51980   Btree *p,                                   /* The btree */
51981   int iTable,                                 /* Root page of table to open */
51982   int wrFlag,                                 /* 1 to write. 0 read-only */
51983   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
51984   BtCursor *pCur                              /* Write new cursor here */
51985 ){
51986   int rc;
51987   sqlite3BtreeEnter(p);
51988   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
51989   sqlite3BtreeLeave(p);
51990   return rc;
51991 }
51992
51993 /*
51994 ** Return the size of a BtCursor object in bytes.
51995 **
51996 ** This interfaces is needed so that users of cursors can preallocate
51997 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
51998 ** to users so they cannot do the sizeof() themselves - they must call
51999 ** this routine.
52000 */
52001 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
52002   return ROUND8(sizeof(BtCursor));
52003 }
52004
52005 /*
52006 ** Initialize memory that will be converted into a BtCursor object.
52007 **
52008 ** The simple approach here would be to memset() the entire object
52009 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
52010 ** do not need to be zeroed and they are large, so we can save a lot
52011 ** of run-time by skipping the initialization of those elements.
52012 */
52013 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
52014   memset(p, 0, offsetof(BtCursor, iPage));
52015 }
52016
52017 /*
52018 ** Set the cached rowid value of every cursor in the same database file
52019 ** as pCur and having the same root page number as pCur.  The value is
52020 ** set to iRowid.
52021 **
52022 ** Only positive rowid values are considered valid for this cache.
52023 ** The cache is initialized to zero, indicating an invalid cache.
52024 ** A btree will work fine with zero or negative rowids.  We just cannot
52025 ** cache zero or negative rowids, which means tables that use zero or
52026 ** negative rowids might run a little slower.  But in practice, zero
52027 ** or negative rowids are very uncommon so this should not be a problem.
52028 */
52029 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
52030   BtCursor *p;
52031   for(p=pCur->pBt->pCursor; p; p=p->pNext){
52032     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
52033   }
52034   assert( pCur->cachedRowid==iRowid );
52035 }
52036
52037 /*
52038 ** Return the cached rowid for the given cursor.  A negative or zero
52039 ** return value indicates that the rowid cache is invalid and should be
52040 ** ignored.  If the rowid cache has never before been set, then a
52041 ** zero is returned.
52042 */
52043 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
52044   return pCur->cachedRowid;
52045 }
52046
52047 /*
52048 ** Close a cursor.  The read lock on the database file is released
52049 ** when the last cursor is closed.
52050 */
52051 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
52052   Btree *pBtree = pCur->pBtree;
52053   if( pBtree ){
52054     int i;
52055     BtShared *pBt = pCur->pBt;
52056     sqlite3BtreeEnter(pBtree);
52057     sqlite3BtreeClearCursor(pCur);
52058     if( pCur->pPrev ){
52059       pCur->pPrev->pNext = pCur->pNext;
52060     }else{
52061       pBt->pCursor = pCur->pNext;
52062     }
52063     if( pCur->pNext ){
52064       pCur->pNext->pPrev = pCur->pPrev;
52065     }
52066     for(i=0; i<=pCur->iPage; i++){
52067       releasePage(pCur->apPage[i]);
52068     }
52069     unlockBtreeIfUnused(pBt);
52070     invalidateOverflowCache(pCur);
52071     /* sqlite3_free(pCur); */
52072     sqlite3BtreeLeave(pBtree);
52073   }
52074   return SQLITE_OK;
52075 }
52076
52077 /*
52078 ** Make sure the BtCursor* given in the argument has a valid
52079 ** BtCursor.info structure.  If it is not already valid, call
52080 ** btreeParseCell() to fill it in.
52081 **
52082 ** BtCursor.info is a cache of the information in the current cell.
52083 ** Using this cache reduces the number of calls to btreeParseCell().
52084 **
52085 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
52086 ** compiler to crash when getCellInfo() is implemented as a macro.
52087 ** But there is a measureable speed advantage to using the macro on gcc
52088 ** (when less compiler optimizations like -Os or -O0 are used and the
52089 ** compiler is not doing agressive inlining.)  So we use a real function
52090 ** for MSVC and a macro for everything else.  Ticket #2457.
52091 */
52092 #ifndef NDEBUG
52093   static void assertCellInfo(BtCursor *pCur){
52094     CellInfo info;
52095     int iPage = pCur->iPage;
52096     memset(&info, 0, sizeof(info));
52097     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
52098     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
52099   }
52100 #else
52101   #define assertCellInfo(x)
52102 #endif
52103 #ifdef _MSC_VER
52104   /* Use a real function in MSVC to work around bugs in that compiler. */
52105   static void getCellInfo(BtCursor *pCur){
52106     if( pCur->info.nSize==0 ){
52107       int iPage = pCur->iPage;
52108       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
52109       pCur->validNKey = 1;
52110     }else{
52111       assertCellInfo(pCur);
52112     }
52113   }
52114 #else /* if not _MSC_VER */
52115   /* Use a macro in all other compilers so that the function is inlined */
52116 #define getCellInfo(pCur)                                                      \
52117   if( pCur->info.nSize==0 ){                                                   \
52118     int iPage = pCur->iPage;                                                   \
52119     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
52120     pCur->validNKey = 1;                                                       \
52121   }else{                                                                       \
52122     assertCellInfo(pCur);                                                      \
52123   }
52124 #endif /* _MSC_VER */
52125
52126 #ifndef NDEBUG  /* The next routine used only within assert() statements */
52127 /*
52128 ** Return true if the given BtCursor is valid.  A valid cursor is one
52129 ** that is currently pointing to a row in a (non-empty) table.
52130 ** This is a verification routine is used only within assert() statements.
52131 */
52132 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
52133   return pCur && pCur->eState==CURSOR_VALID;
52134 }
52135 #endif /* NDEBUG */
52136
52137 /*
52138 ** Set *pSize to the size of the buffer needed to hold the value of
52139 ** the key for the current entry.  If the cursor is not pointing
52140 ** to a valid entry, *pSize is set to 0. 
52141 **
52142 ** For a table with the INTKEY flag set, this routine returns the key
52143 ** itself, not the number of bytes in the key.
52144 **
52145 ** The caller must position the cursor prior to invoking this routine.
52146 ** 
52147 ** This routine cannot fail.  It always returns SQLITE_OK.  
52148 */
52149 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
52150   assert( cursorHoldsMutex(pCur) );
52151   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
52152   if( pCur->eState!=CURSOR_VALID ){
52153     *pSize = 0;
52154   }else{
52155     getCellInfo(pCur);
52156     *pSize = pCur->info.nKey;
52157   }
52158   return SQLITE_OK;
52159 }
52160
52161 /*
52162 ** Set *pSize to the number of bytes of data in the entry the
52163 ** cursor currently points to.
52164 **
52165 ** The caller must guarantee that the cursor is pointing to a non-NULL
52166 ** valid entry.  In other words, the calling procedure must guarantee
52167 ** that the cursor has Cursor.eState==CURSOR_VALID.
52168 **
52169 ** Failure is not possible.  This function always returns SQLITE_OK.
52170 ** It might just as well be a procedure (returning void) but we continue
52171 ** to return an integer result code for historical reasons.
52172 */
52173 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
52174   assert( cursorHoldsMutex(pCur) );
52175   assert( pCur->eState==CURSOR_VALID );
52176   getCellInfo(pCur);
52177   *pSize = pCur->info.nData;
52178   return SQLITE_OK;
52179 }
52180
52181 /*
52182 ** Given the page number of an overflow page in the database (parameter
52183 ** ovfl), this function finds the page number of the next page in the 
52184 ** linked list of overflow pages. If possible, it uses the auto-vacuum
52185 ** pointer-map data instead of reading the content of page ovfl to do so. 
52186 **
52187 ** If an error occurs an SQLite error code is returned. Otherwise:
52188 **
52189 ** The page number of the next overflow page in the linked list is 
52190 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
52191 ** list, *pPgnoNext is set to zero. 
52192 **
52193 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
52194 ** to page number pOvfl was obtained, then *ppPage is set to point to that
52195 ** reference. It is the responsibility of the caller to call releasePage()
52196 ** on *ppPage to free the reference. In no reference was obtained (because
52197 ** the pointer-map was used to obtain the value for *pPgnoNext), then
52198 ** *ppPage is set to zero.
52199 */
52200 static int getOverflowPage(
52201   BtShared *pBt,               /* The database file */
52202   Pgno ovfl,                   /* Current overflow page number */
52203   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
52204   Pgno *pPgnoNext              /* OUT: Next overflow page number */
52205 ){
52206   Pgno next = 0;
52207   MemPage *pPage = 0;
52208   int rc = SQLITE_OK;
52209
52210   assert( sqlite3_mutex_held(pBt->mutex) );
52211   assert(pPgnoNext);
52212
52213 #ifndef SQLITE_OMIT_AUTOVACUUM
52214   /* Try to find the next page in the overflow list using the
52215   ** autovacuum pointer-map pages. Guess that the next page in 
52216   ** the overflow list is page number (ovfl+1). If that guess turns 
52217   ** out to be wrong, fall back to loading the data of page 
52218   ** number ovfl to determine the next page number.
52219   */
52220   if( pBt->autoVacuum ){
52221     Pgno pgno;
52222     Pgno iGuess = ovfl+1;
52223     u8 eType;
52224
52225     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
52226       iGuess++;
52227     }
52228
52229     if( iGuess<=btreePagecount(pBt) ){
52230       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
52231       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
52232         next = iGuess;
52233         rc = SQLITE_DONE;
52234       }
52235     }
52236   }
52237 #endif
52238
52239   assert( next==0 || rc==SQLITE_DONE );
52240   if( rc==SQLITE_OK ){
52241     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
52242     assert( rc==SQLITE_OK || pPage==0 );
52243     if( rc==SQLITE_OK ){
52244       next = get4byte(pPage->aData);
52245     }
52246   }
52247
52248   *pPgnoNext = next;
52249   if( ppPage ){
52250     *ppPage = pPage;
52251   }else{
52252     releasePage(pPage);
52253   }
52254   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
52255 }
52256
52257 /*
52258 ** Copy data from a buffer to a page, or from a page to a buffer.
52259 **
52260 ** pPayload is a pointer to data stored on database page pDbPage.
52261 ** If argument eOp is false, then nByte bytes of data are copied
52262 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
52263 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
52264 ** of data are copied from the buffer pBuf to pPayload.
52265 **
52266 ** SQLITE_OK is returned on success, otherwise an error code.
52267 */
52268 static int copyPayload(
52269   void *pPayload,           /* Pointer to page data */
52270   void *pBuf,               /* Pointer to buffer */
52271   int nByte,                /* Number of bytes to copy */
52272   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
52273   DbPage *pDbPage           /* Page containing pPayload */
52274 ){
52275   if( eOp ){
52276     /* Copy data from buffer to page (a write operation) */
52277     int rc = sqlite3PagerWrite(pDbPage);
52278     if( rc!=SQLITE_OK ){
52279       return rc;
52280     }
52281     memcpy(pPayload, pBuf, nByte);
52282   }else{
52283     /* Copy data from page to buffer (a read operation) */
52284     memcpy(pBuf, pPayload, nByte);
52285   }
52286   return SQLITE_OK;
52287 }
52288
52289 /*
52290 ** This function is used to read or overwrite payload information
52291 ** for the entry that the pCur cursor is pointing to. If the eOp
52292 ** parameter is 0, this is a read operation (data copied into
52293 ** buffer pBuf). If it is non-zero, a write (data copied from
52294 ** buffer pBuf).
52295 **
52296 ** A total of "amt" bytes are read or written beginning at "offset".
52297 ** Data is read to or from the buffer pBuf.
52298 **
52299 ** The content being read or written might appear on the main page
52300 ** or be scattered out on multiple overflow pages.
52301 **
52302 ** If the BtCursor.isIncrblobHandle flag is set, and the current
52303 ** cursor entry uses one or more overflow pages, this function
52304 ** allocates space for and lazily popluates the overflow page-list 
52305 ** cache array (BtCursor.aOverflow). Subsequent calls use this
52306 ** cache to make seeking to the supplied offset more efficient.
52307 **
52308 ** Once an overflow page-list cache has been allocated, it may be
52309 ** invalidated if some other cursor writes to the same table, or if
52310 ** the cursor is moved to a different row. Additionally, in auto-vacuum
52311 ** mode, the following events may invalidate an overflow page-list cache.
52312 **
52313 **   * An incremental vacuum,
52314 **   * A commit in auto_vacuum="full" mode,
52315 **   * Creating a table (may require moving an overflow page).
52316 */
52317 static int accessPayload(
52318   BtCursor *pCur,      /* Cursor pointing to entry to read from */
52319   u32 offset,          /* Begin reading this far into payload */
52320   u32 amt,             /* Read this many bytes */
52321   unsigned char *pBuf, /* Write the bytes into this buffer */ 
52322   int eOp              /* zero to read. non-zero to write. */
52323 ){
52324   unsigned char *aPayload;
52325   int rc = SQLITE_OK;
52326   u32 nKey;
52327   int iIdx = 0;
52328   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
52329   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
52330
52331   assert( pPage );
52332   assert( pCur->eState==CURSOR_VALID );
52333   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52334   assert( cursorHoldsMutex(pCur) );
52335
52336   getCellInfo(pCur);
52337   aPayload = pCur->info.pCell + pCur->info.nHeader;
52338   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
52339
52340   if( NEVER(offset+amt > nKey+pCur->info.nData) 
52341    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
52342   ){
52343     /* Trying to read or write past the end of the data is an error */
52344     return SQLITE_CORRUPT_BKPT;
52345   }
52346
52347   /* Check if data must be read/written to/from the btree page itself. */
52348   if( offset<pCur->info.nLocal ){
52349     int a = amt;
52350     if( a+offset>pCur->info.nLocal ){
52351       a = pCur->info.nLocal - offset;
52352     }
52353     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
52354     offset = 0;
52355     pBuf += a;
52356     amt -= a;
52357   }else{
52358     offset -= pCur->info.nLocal;
52359   }
52360
52361   if( rc==SQLITE_OK && amt>0 ){
52362     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
52363     Pgno nextPage;
52364
52365     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
52366
52367 #ifndef SQLITE_OMIT_INCRBLOB
52368     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
52369     ** has not been allocated, allocate it now. The array is sized at
52370     ** one entry for each overflow page in the overflow chain. The
52371     ** page number of the first overflow page is stored in aOverflow[0],
52372     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
52373     ** (the cache is lazily populated).
52374     */
52375     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
52376       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
52377       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
52378       /* nOvfl is always positive.  If it were zero, fetchPayload would have
52379       ** been used instead of this routine. */
52380       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
52381         rc = SQLITE_NOMEM;
52382       }
52383     }
52384
52385     /* If the overflow page-list cache has been allocated and the
52386     ** entry for the first required overflow page is valid, skip
52387     ** directly to it.
52388     */
52389     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
52390       iIdx = (offset/ovflSize);
52391       nextPage = pCur->aOverflow[iIdx];
52392       offset = (offset%ovflSize);
52393     }
52394 #endif
52395
52396     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
52397
52398 #ifndef SQLITE_OMIT_INCRBLOB
52399       /* If required, populate the overflow page-list cache. */
52400       if( pCur->aOverflow ){
52401         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
52402         pCur->aOverflow[iIdx] = nextPage;
52403       }
52404 #endif
52405
52406       if( offset>=ovflSize ){
52407         /* The only reason to read this page is to obtain the page
52408         ** number for the next page in the overflow chain. The page
52409         ** data is not required. So first try to lookup the overflow
52410         ** page-list cache, if any, then fall back to the getOverflowPage()
52411         ** function.
52412         */
52413 #ifndef SQLITE_OMIT_INCRBLOB
52414         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
52415           nextPage = pCur->aOverflow[iIdx+1];
52416         } else 
52417 #endif
52418           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
52419         offset -= ovflSize;
52420       }else{
52421         /* Need to read this page properly. It contains some of the
52422         ** range of data that is being read (eOp==0) or written (eOp!=0).
52423         */
52424 #ifdef SQLITE_DIRECT_OVERFLOW_READ
52425         sqlite3_file *fd;
52426 #endif
52427         int a = amt;
52428         if( a + offset > ovflSize ){
52429           a = ovflSize - offset;
52430         }
52431
52432 #ifdef SQLITE_DIRECT_OVERFLOW_READ
52433         /* If all the following are true:
52434         **
52435         **   1) this is a read operation, and 
52436         **   2) data is required from the start of this overflow page, and
52437         **   3) the database is file-backed, and
52438         **   4) there is no open write-transaction, and
52439         **   5) the database is not a WAL database,
52440         **
52441         ** then data can be read directly from the database file into the
52442         ** output buffer, bypassing the page-cache altogether. This speeds
52443         ** up loading large records that span many overflow pages.
52444         */
52445         if( eOp==0                                             /* (1) */
52446          && offset==0                                          /* (2) */
52447          && pBt->inTransaction==TRANS_READ                     /* (4) */
52448          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
52449          && pBt->pPage1->aData[19]==0x01                       /* (5) */
52450         ){
52451           u8 aSave[4];
52452           u8 *aWrite = &pBuf[-4];
52453           memcpy(aSave, aWrite, 4);
52454           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
52455           nextPage = get4byte(aWrite);
52456           memcpy(aWrite, aSave, 4);
52457         }else
52458 #endif
52459
52460         {
52461           DbPage *pDbPage;
52462           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
52463           if( rc==SQLITE_OK ){
52464             aPayload = sqlite3PagerGetData(pDbPage);
52465             nextPage = get4byte(aPayload);
52466             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
52467             sqlite3PagerUnref(pDbPage);
52468             offset = 0;
52469           }
52470         }
52471         amt -= a;
52472         pBuf += a;
52473       }
52474     }
52475   }
52476
52477   if( rc==SQLITE_OK && amt>0 ){
52478     return SQLITE_CORRUPT_BKPT;
52479   }
52480   return rc;
52481 }
52482
52483 /*
52484 ** Read part of the key associated with cursor pCur.  Exactly
52485 ** "amt" bytes will be transfered into pBuf[].  The transfer
52486 ** begins at "offset".
52487 **
52488 ** The caller must ensure that pCur is pointing to a valid row
52489 ** in the table.
52490 **
52491 ** Return SQLITE_OK on success or an error code if anything goes
52492 ** wrong.  An error is returned if "offset+amt" is larger than
52493 ** the available payload.
52494 */
52495 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
52496   assert( cursorHoldsMutex(pCur) );
52497   assert( pCur->eState==CURSOR_VALID );
52498   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
52499   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52500   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
52501 }
52502
52503 /*
52504 ** Read part of the data associated with cursor pCur.  Exactly
52505 ** "amt" bytes will be transfered into pBuf[].  The transfer
52506 ** begins at "offset".
52507 **
52508 ** Return SQLITE_OK on success or an error code if anything goes
52509 ** wrong.  An error is returned if "offset+amt" is larger than
52510 ** the available payload.
52511 */
52512 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
52513   int rc;
52514
52515 #ifndef SQLITE_OMIT_INCRBLOB
52516   if ( pCur->eState==CURSOR_INVALID ){
52517     return SQLITE_ABORT;
52518   }
52519 #endif
52520
52521   assert( cursorHoldsMutex(pCur) );
52522   rc = restoreCursorPosition(pCur);
52523   if( rc==SQLITE_OK ){
52524     assert( pCur->eState==CURSOR_VALID );
52525     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
52526     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52527     rc = accessPayload(pCur, offset, amt, pBuf, 0);
52528   }
52529   return rc;
52530 }
52531
52532 /*
52533 ** Return a pointer to payload information from the entry that the 
52534 ** pCur cursor is pointing to.  The pointer is to the beginning of
52535 ** the key if skipKey==0 and it points to the beginning of data if
52536 ** skipKey==1.  The number of bytes of available key/data is written
52537 ** into *pAmt.  If *pAmt==0, then the value returned will not be
52538 ** a valid pointer.
52539 **
52540 ** This routine is an optimization.  It is common for the entire key
52541 ** and data to fit on the local page and for there to be no overflow
52542 ** pages.  When that is so, this routine can be used to access the
52543 ** key and data without making a copy.  If the key and/or data spills
52544 ** onto overflow pages, then accessPayload() must be used to reassemble
52545 ** the key/data and copy it into a preallocated buffer.
52546 **
52547 ** The pointer returned by this routine looks directly into the cached
52548 ** page of the database.  The data might change or move the next time
52549 ** any btree routine is called.
52550 */
52551 static const unsigned char *fetchPayload(
52552   BtCursor *pCur,      /* Cursor pointing to entry to read from */
52553   int *pAmt,           /* Write the number of available bytes here */
52554   int skipKey          /* read beginning at data if this is true */
52555 ){
52556   unsigned char *aPayload;
52557   MemPage *pPage;
52558   u32 nKey;
52559   u32 nLocal;
52560
52561   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
52562   assert( pCur->eState==CURSOR_VALID );
52563   assert( cursorHoldsMutex(pCur) );
52564   pPage = pCur->apPage[pCur->iPage];
52565   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52566   if( NEVER(pCur->info.nSize==0) ){
52567     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
52568                    &pCur->info);
52569   }
52570   aPayload = pCur->info.pCell;
52571   aPayload += pCur->info.nHeader;
52572   if( pPage->intKey ){
52573     nKey = 0;
52574   }else{
52575     nKey = (int)pCur->info.nKey;
52576   }
52577   if( skipKey ){
52578     aPayload += nKey;
52579     nLocal = pCur->info.nLocal - nKey;
52580   }else{
52581     nLocal = pCur->info.nLocal;
52582     assert( nLocal<=nKey );
52583   }
52584   *pAmt = nLocal;
52585   return aPayload;
52586 }
52587
52588
52589 /*
52590 ** For the entry that cursor pCur is point to, return as
52591 ** many bytes of the key or data as are available on the local
52592 ** b-tree page.  Write the number of available bytes into *pAmt.
52593 **
52594 ** The pointer returned is ephemeral.  The key/data may move
52595 ** or be destroyed on the next call to any Btree routine,
52596 ** including calls from other threads against the same cache.
52597 ** Hence, a mutex on the BtShared should be held prior to calling
52598 ** this routine.
52599 **
52600 ** These routines is used to get quick access to key and data
52601 ** in the common case where no overflow pages are used.
52602 */
52603 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
52604   const void *p = 0;
52605   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52606   assert( cursorHoldsMutex(pCur) );
52607   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
52608     p = (const void*)fetchPayload(pCur, pAmt, 0);
52609   }
52610   return p;
52611 }
52612 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
52613   const void *p = 0;
52614   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52615   assert( cursorHoldsMutex(pCur) );
52616   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
52617     p = (const void*)fetchPayload(pCur, pAmt, 1);
52618   }
52619   return p;
52620 }
52621
52622
52623 /*
52624 ** Move the cursor down to a new child page.  The newPgno argument is the
52625 ** page number of the child page to move to.
52626 **
52627 ** This function returns SQLITE_CORRUPT if the page-header flags field of
52628 ** the new child page does not match the flags field of the parent (i.e.
52629 ** if an intkey page appears to be the parent of a non-intkey page, or
52630 ** vice-versa).
52631 */
52632 static int moveToChild(BtCursor *pCur, u32 newPgno){
52633   int rc;
52634   int i = pCur->iPage;
52635   MemPage *pNewPage;
52636   BtShared *pBt = pCur->pBt;
52637
52638   assert( cursorHoldsMutex(pCur) );
52639   assert( pCur->eState==CURSOR_VALID );
52640   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
52641   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
52642     return SQLITE_CORRUPT_BKPT;
52643   }
52644   rc = getAndInitPage(pBt, newPgno, &pNewPage);
52645   if( rc ) return rc;
52646   pCur->apPage[i+1] = pNewPage;
52647   pCur->aiIdx[i+1] = 0;
52648   pCur->iPage++;
52649
52650   pCur->info.nSize = 0;
52651   pCur->validNKey = 0;
52652   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
52653     return SQLITE_CORRUPT_BKPT;
52654   }
52655   return SQLITE_OK;
52656 }
52657
52658 #if 0
52659 /*
52660 ** Page pParent is an internal (non-leaf) tree page. This function 
52661 ** asserts that page number iChild is the left-child if the iIdx'th
52662 ** cell in page pParent. Or, if iIdx is equal to the total number of
52663 ** cells in pParent, that page number iChild is the right-child of
52664 ** the page.
52665 */
52666 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
52667   assert( iIdx<=pParent->nCell );
52668   if( iIdx==pParent->nCell ){
52669     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
52670   }else{
52671     assert( get4byte(findCell(pParent, iIdx))==iChild );
52672   }
52673 }
52674 #else
52675 #  define assertParentIndex(x,y,z) 
52676 #endif
52677
52678 /*
52679 ** Move the cursor up to the parent page.
52680 **
52681 ** pCur->idx is set to the cell index that contains the pointer
52682 ** to the page we are coming from.  If we are coming from the
52683 ** right-most child page then pCur->idx is set to one more than
52684 ** the largest cell index.
52685 */
52686 static void moveToParent(BtCursor *pCur){
52687   assert( cursorHoldsMutex(pCur) );
52688   assert( pCur->eState==CURSOR_VALID );
52689   assert( pCur->iPage>0 );
52690   assert( pCur->apPage[pCur->iPage] );
52691
52692   /* UPDATE: It is actually possible for the condition tested by the assert
52693   ** below to be untrue if the database file is corrupt. This can occur if
52694   ** one cursor has modified page pParent while a reference to it is held 
52695   ** by a second cursor. Which can only happen if a single page is linked
52696   ** into more than one b-tree structure in a corrupt database.  */
52697 #if 0
52698   assertParentIndex(
52699     pCur->apPage[pCur->iPage-1], 
52700     pCur->aiIdx[pCur->iPage-1], 
52701     pCur->apPage[pCur->iPage]->pgno
52702   );
52703 #endif
52704   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
52705
52706   releasePage(pCur->apPage[pCur->iPage]);
52707   pCur->iPage--;
52708   pCur->info.nSize = 0;
52709   pCur->validNKey = 0;
52710 }
52711
52712 /*
52713 ** Move the cursor to point to the root page of its b-tree structure.
52714 **
52715 ** If the table has a virtual root page, then the cursor is moved to point
52716 ** to the virtual root page instead of the actual root page. A table has a
52717 ** virtual root page when the actual root page contains no cells and a 
52718 ** single child page. This can only happen with the table rooted at page 1.
52719 **
52720 ** If the b-tree structure is empty, the cursor state is set to 
52721 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
52722 ** cell located on the root (or virtual root) page and the cursor state
52723 ** is set to CURSOR_VALID.
52724 **
52725 ** If this function returns successfully, it may be assumed that the
52726 ** page-header flags indicate that the [virtual] root-page is the expected 
52727 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
52728 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
52729 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
52730 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
52731 ** b-tree).
52732 */
52733 static int moveToRoot(BtCursor *pCur){
52734   MemPage *pRoot;
52735   int rc = SQLITE_OK;
52736   Btree *p = pCur->pBtree;
52737   BtShared *pBt = p->pBt;
52738
52739   assert( cursorHoldsMutex(pCur) );
52740   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
52741   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
52742   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
52743   if( pCur->eState>=CURSOR_REQUIRESEEK ){
52744     if( pCur->eState==CURSOR_FAULT ){
52745       assert( pCur->skipNext!=SQLITE_OK );
52746       return pCur->skipNext;
52747     }
52748     sqlite3BtreeClearCursor(pCur);
52749   }
52750
52751   if( pCur->iPage>=0 ){
52752     int i;
52753     for(i=1; i<=pCur->iPage; i++){
52754       releasePage(pCur->apPage[i]);
52755     }
52756     pCur->iPage = 0;
52757   }else if( pCur->pgnoRoot==0 ){
52758     pCur->eState = CURSOR_INVALID;
52759     return SQLITE_OK;
52760   }else{
52761     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
52762     if( rc!=SQLITE_OK ){
52763       pCur->eState = CURSOR_INVALID;
52764       return rc;
52765     }
52766     pCur->iPage = 0;
52767
52768     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
52769     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
52770     ** NULL, the caller expects a table b-tree. If this is not the case,
52771     ** return an SQLITE_CORRUPT error.  */
52772     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
52773     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
52774       return SQLITE_CORRUPT_BKPT;
52775     }
52776   }
52777
52778   /* Assert that the root page is of the correct type. This must be the
52779   ** case as the call to this function that loaded the root-page (either
52780   ** this call or a previous invocation) would have detected corruption 
52781   ** if the assumption were not true, and it is not possible for the flags 
52782   ** byte to have been modified while this cursor is holding a reference
52783   ** to the page.  */
52784   pRoot = pCur->apPage[0];
52785   assert( pRoot->pgno==pCur->pgnoRoot );
52786   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
52787
52788   pCur->aiIdx[0] = 0;
52789   pCur->info.nSize = 0;
52790   pCur->atLast = 0;
52791   pCur->validNKey = 0;
52792
52793   if( pRoot->nCell==0 && !pRoot->leaf ){
52794     Pgno subpage;
52795     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
52796     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
52797     pCur->eState = CURSOR_VALID;
52798     rc = moveToChild(pCur, subpage);
52799   }else{
52800     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
52801   }
52802   return rc;
52803 }
52804
52805 /*
52806 ** Move the cursor down to the left-most leaf entry beneath the
52807 ** entry to which it is currently pointing.
52808 **
52809 ** The left-most leaf is the one with the smallest key - the first
52810 ** in ascending order.
52811 */
52812 static int moveToLeftmost(BtCursor *pCur){
52813   Pgno pgno;
52814   int rc = SQLITE_OK;
52815   MemPage *pPage;
52816
52817   assert( cursorHoldsMutex(pCur) );
52818   assert( pCur->eState==CURSOR_VALID );
52819   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
52820     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52821     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
52822     rc = moveToChild(pCur, pgno);
52823   }
52824   return rc;
52825 }
52826
52827 /*
52828 ** Move the cursor down to the right-most leaf entry beneath the
52829 ** page to which it is currently pointing.  Notice the difference
52830 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
52831 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
52832 ** finds the right-most entry beneath the *page*.
52833 **
52834 ** The right-most entry is the one with the largest key - the last
52835 ** key in ascending order.
52836 */
52837 static int moveToRightmost(BtCursor *pCur){
52838   Pgno pgno;
52839   int rc = SQLITE_OK;
52840   MemPage *pPage = 0;
52841
52842   assert( cursorHoldsMutex(pCur) );
52843   assert( pCur->eState==CURSOR_VALID );
52844   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
52845     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52846     pCur->aiIdx[pCur->iPage] = pPage->nCell;
52847     rc = moveToChild(pCur, pgno);
52848   }
52849   if( rc==SQLITE_OK ){
52850     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
52851     pCur->info.nSize = 0;
52852     pCur->validNKey = 0;
52853   }
52854   return rc;
52855 }
52856
52857 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
52858 ** on success.  Set *pRes to 0 if the cursor actually points to something
52859 ** or set *pRes to 1 if the table is empty.
52860 */
52861 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
52862   int rc;
52863
52864   assert( cursorHoldsMutex(pCur) );
52865   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52866   rc = moveToRoot(pCur);
52867   if( rc==SQLITE_OK ){
52868     if( pCur->eState==CURSOR_INVALID ){
52869       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52870       *pRes = 1;
52871     }else{
52872       assert( pCur->apPage[pCur->iPage]->nCell>0 );
52873       *pRes = 0;
52874       rc = moveToLeftmost(pCur);
52875     }
52876   }
52877   return rc;
52878 }
52879
52880 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
52881 ** on success.  Set *pRes to 0 if the cursor actually points to something
52882 ** or set *pRes to 1 if the table is empty.
52883 */
52884 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
52885   int rc;
52886  
52887   assert( cursorHoldsMutex(pCur) );
52888   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52889
52890   /* If the cursor already points to the last entry, this is a no-op. */
52891   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
52892 #ifdef SQLITE_DEBUG
52893     /* This block serves to assert() that the cursor really does point 
52894     ** to the last entry in the b-tree. */
52895     int ii;
52896     for(ii=0; ii<pCur->iPage; ii++){
52897       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
52898     }
52899     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
52900     assert( pCur->apPage[pCur->iPage]->leaf );
52901 #endif
52902     return SQLITE_OK;
52903   }
52904
52905   rc = moveToRoot(pCur);
52906   if( rc==SQLITE_OK ){
52907     if( CURSOR_INVALID==pCur->eState ){
52908       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52909       *pRes = 1;
52910     }else{
52911       assert( pCur->eState==CURSOR_VALID );
52912       *pRes = 0;
52913       rc = moveToRightmost(pCur);
52914       pCur->atLast = rc==SQLITE_OK ?1:0;
52915     }
52916   }
52917   return rc;
52918 }
52919
52920 /* Move the cursor so that it points to an entry near the key 
52921 ** specified by pIdxKey or intKey.   Return a success code.
52922 **
52923 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
52924 ** must be NULL.  For index tables, pIdxKey is used and intKey
52925 ** is ignored.
52926 **
52927 ** If an exact match is not found, then the cursor is always
52928 ** left pointing at a leaf page which would hold the entry if it
52929 ** were present.  The cursor might point to an entry that comes
52930 ** before or after the key.
52931 **
52932 ** An integer is written into *pRes which is the result of
52933 ** comparing the key with the entry to which the cursor is 
52934 ** pointing.  The meaning of the integer written into
52935 ** *pRes is as follows:
52936 **
52937 **     *pRes<0      The cursor is left pointing at an entry that
52938 **                  is smaller than intKey/pIdxKey or if the table is empty
52939 **                  and the cursor is therefore left point to nothing.
52940 **
52941 **     *pRes==0     The cursor is left pointing at an entry that
52942 **                  exactly matches intKey/pIdxKey.
52943 **
52944 **     *pRes>0      The cursor is left pointing at an entry that
52945 **                  is larger than intKey/pIdxKey.
52946 **
52947 */
52948 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
52949   BtCursor *pCur,          /* The cursor to be moved */
52950   UnpackedRecord *pIdxKey, /* Unpacked index key */
52951   i64 intKey,              /* The table key */
52952   int biasRight,           /* If true, bias the search to the high end */
52953   int *pRes                /* Write search results here */
52954 ){
52955   int rc;
52956
52957   assert( cursorHoldsMutex(pCur) );
52958   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52959   assert( pRes );
52960   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
52961
52962   /* If the cursor is already positioned at the point we are trying
52963   ** to move to, then just return without doing any work */
52964   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
52965    && pCur->apPage[0]->intKey 
52966   ){
52967     if( pCur->info.nKey==intKey ){
52968       *pRes = 0;
52969       return SQLITE_OK;
52970     }
52971     if( pCur->atLast && pCur->info.nKey<intKey ){
52972       *pRes = -1;
52973       return SQLITE_OK;
52974     }
52975   }
52976
52977   rc = moveToRoot(pCur);
52978   if( rc ){
52979     return rc;
52980   }
52981   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
52982   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
52983   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
52984   if( pCur->eState==CURSOR_INVALID ){
52985     *pRes = -1;
52986     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52987     return SQLITE_OK;
52988   }
52989   assert( pCur->apPage[0]->intKey || pIdxKey );
52990   for(;;){
52991     int lwr, upr, idx;
52992     Pgno chldPg;
52993     MemPage *pPage = pCur->apPage[pCur->iPage];
52994     int c;
52995
52996     /* pPage->nCell must be greater than zero. If this is the root-page
52997     ** the cursor would have been INVALID above and this for(;;) loop
52998     ** not run. If this is not the root-page, then the moveToChild() routine
52999     ** would have already detected db corruption. Similarly, pPage must
53000     ** be the right kind (index or table) of b-tree page. Otherwise
53001     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
53002     assert( pPage->nCell>0 );
53003     assert( pPage->intKey==(pIdxKey==0) );
53004     lwr = 0;
53005     upr = pPage->nCell-1;
53006     if( biasRight ){
53007       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
53008     }else{
53009       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
53010     }
53011     for(;;){
53012       u8 *pCell;                          /* Pointer to current cell in pPage */
53013
53014       assert( idx==pCur->aiIdx[pCur->iPage] );
53015       pCur->info.nSize = 0;
53016       pCell = findCell(pPage, idx) + pPage->childPtrSize;
53017       if( pPage->intKey ){
53018         i64 nCellKey;
53019         if( pPage->hasData ){
53020           u32 dummy;
53021           pCell += getVarint32(pCell, dummy);
53022         }
53023         getVarint(pCell, (u64*)&nCellKey);
53024         if( nCellKey==intKey ){
53025           c = 0;
53026         }else if( nCellKey<intKey ){
53027           c = -1;
53028         }else{
53029           assert( nCellKey>intKey );
53030           c = +1;
53031         }
53032         pCur->validNKey = 1;
53033         pCur->info.nKey = nCellKey;
53034       }else{
53035         /* The maximum supported page-size is 65536 bytes. This means that
53036         ** the maximum number of record bytes stored on an index B-Tree
53037         ** page is less than 16384 bytes and may be stored as a 2-byte
53038         ** varint. This information is used to attempt to avoid parsing 
53039         ** the entire cell by checking for the cases where the record is 
53040         ** stored entirely within the b-tree page by inspecting the first 
53041         ** 2 bytes of the cell.
53042         */
53043         int nCell = pCell[0];
53044         if( nCell<=pPage->max1bytePayload
53045          /* && (pCell+nCell)<pPage->aDataEnd */
53046         ){
53047           /* This branch runs if the record-size field of the cell is a
53048           ** single byte varint and the record fits entirely on the main
53049           ** b-tree page.  */
53050           testcase( pCell+nCell+1==pPage->aDataEnd );
53051           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
53052         }else if( !(pCell[1] & 0x80) 
53053           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
53054           /* && (pCell+nCell+2)<=pPage->aDataEnd */
53055         ){
53056           /* The record-size field is a 2 byte varint and the record 
53057           ** fits entirely on the main b-tree page.  */
53058           testcase( pCell+nCell+2==pPage->aDataEnd );
53059           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
53060         }else{
53061           /* The record flows over onto one or more overflow pages. In
53062           ** this case the whole cell needs to be parsed, a buffer allocated
53063           ** and accessPayload() used to retrieve the record into the
53064           ** buffer before VdbeRecordCompare() can be called. */
53065           void *pCellKey;
53066           u8 * const pCellBody = pCell - pPage->childPtrSize;
53067           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
53068           nCell = (int)pCur->info.nKey;
53069           pCellKey = sqlite3Malloc( nCell );
53070           if( pCellKey==0 ){
53071             rc = SQLITE_NOMEM;
53072             goto moveto_finish;
53073           }
53074           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
53075           if( rc ){
53076             sqlite3_free(pCellKey);
53077             goto moveto_finish;
53078           }
53079           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
53080           sqlite3_free(pCellKey);
53081         }
53082       }
53083       if( c==0 ){
53084         if( pPage->intKey && !pPage->leaf ){
53085           lwr = idx;
53086           break;
53087         }else{
53088           *pRes = 0;
53089           rc = SQLITE_OK;
53090           goto moveto_finish;
53091         }
53092       }
53093       if( c<0 ){
53094         lwr = idx+1;
53095       }else{
53096         upr = idx-1;
53097       }
53098       if( lwr>upr ){
53099         break;
53100       }
53101       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
53102     }
53103     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
53104     assert( pPage->isInit );
53105     if( pPage->leaf ){
53106       chldPg = 0;
53107     }else if( lwr>=pPage->nCell ){
53108       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
53109     }else{
53110       chldPg = get4byte(findCell(pPage, lwr));
53111     }
53112     if( chldPg==0 ){
53113       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53114       *pRes = c;
53115       rc = SQLITE_OK;
53116       goto moveto_finish;
53117     }
53118     pCur->aiIdx[pCur->iPage] = (u16)lwr;
53119     pCur->info.nSize = 0;
53120     pCur->validNKey = 0;
53121     rc = moveToChild(pCur, chldPg);
53122     if( rc ) goto moveto_finish;
53123   }
53124 moveto_finish:
53125   return rc;
53126 }
53127
53128
53129 /*
53130 ** Return TRUE if the cursor is not pointing at an entry of the table.
53131 **
53132 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
53133 ** past the last entry in the table or sqlite3BtreePrev() moves past
53134 ** the first entry.  TRUE is also returned if the table is empty.
53135 */
53136 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
53137   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
53138   ** have been deleted? This API will need to change to return an error code
53139   ** as well as the boolean result value.
53140   */
53141   return (CURSOR_VALID!=pCur->eState);
53142 }
53143
53144 /*
53145 ** Advance the cursor to the next entry in the database.  If
53146 ** successful then set *pRes=0.  If the cursor
53147 ** was already pointing to the last entry in the database before
53148 ** this routine was called, then set *pRes=1.
53149 */
53150 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
53151   int rc;
53152   int idx;
53153   MemPage *pPage;
53154
53155   assert( cursorHoldsMutex(pCur) );
53156   rc = restoreCursorPosition(pCur);
53157   if( rc!=SQLITE_OK ){
53158     return rc;
53159   }
53160   assert( pRes!=0 );
53161   if( CURSOR_INVALID==pCur->eState ){
53162     *pRes = 1;
53163     return SQLITE_OK;
53164   }
53165   if( pCur->skipNext>0 ){
53166     pCur->skipNext = 0;
53167     *pRes = 0;
53168     return SQLITE_OK;
53169   }
53170   pCur->skipNext = 0;
53171
53172   pPage = pCur->apPage[pCur->iPage];
53173   idx = ++pCur->aiIdx[pCur->iPage];
53174   assert( pPage->isInit );
53175
53176   /* If the database file is corrupt, it is possible for the value of idx 
53177   ** to be invalid here. This can only occur if a second cursor modifies
53178   ** the page while cursor pCur is holding a reference to it. Which can
53179   ** only happen if the database is corrupt in such a way as to link the
53180   ** page into more than one b-tree structure. */
53181   testcase( idx>pPage->nCell );
53182
53183   pCur->info.nSize = 0;
53184   pCur->validNKey = 0;
53185   if( idx>=pPage->nCell ){
53186     if( !pPage->leaf ){
53187       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
53188       if( rc ) return rc;
53189       rc = moveToLeftmost(pCur);
53190       *pRes = 0;
53191       return rc;
53192     }
53193     do{
53194       if( pCur->iPage==0 ){
53195         *pRes = 1;
53196         pCur->eState = CURSOR_INVALID;
53197         return SQLITE_OK;
53198       }
53199       moveToParent(pCur);
53200       pPage = pCur->apPage[pCur->iPage];
53201     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
53202     *pRes = 0;
53203     if( pPage->intKey ){
53204       rc = sqlite3BtreeNext(pCur, pRes);
53205     }else{
53206       rc = SQLITE_OK;
53207     }
53208     return rc;
53209   }
53210   *pRes = 0;
53211   if( pPage->leaf ){
53212     return SQLITE_OK;
53213   }
53214   rc = moveToLeftmost(pCur);
53215   return rc;
53216 }
53217
53218
53219 /*
53220 ** Step the cursor to the back to the previous entry in the database.  If
53221 ** successful then set *pRes=0.  If the cursor
53222 ** was already pointing to the first entry in the database before
53223 ** this routine was called, then set *pRes=1.
53224 */
53225 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
53226   int rc;
53227   MemPage *pPage;
53228
53229   assert( cursorHoldsMutex(pCur) );
53230   rc = restoreCursorPosition(pCur);
53231   if( rc!=SQLITE_OK ){
53232     return rc;
53233   }
53234   pCur->atLast = 0;
53235   if( CURSOR_INVALID==pCur->eState ){
53236     *pRes = 1;
53237     return SQLITE_OK;
53238   }
53239   if( pCur->skipNext<0 ){
53240     pCur->skipNext = 0;
53241     *pRes = 0;
53242     return SQLITE_OK;
53243   }
53244   pCur->skipNext = 0;
53245
53246   pPage = pCur->apPage[pCur->iPage];
53247   assert( pPage->isInit );
53248   if( !pPage->leaf ){
53249     int idx = pCur->aiIdx[pCur->iPage];
53250     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
53251     if( rc ){
53252       return rc;
53253     }
53254     rc = moveToRightmost(pCur);
53255   }else{
53256     while( pCur->aiIdx[pCur->iPage]==0 ){
53257       if( pCur->iPage==0 ){
53258         pCur->eState = CURSOR_INVALID;
53259         *pRes = 1;
53260         return SQLITE_OK;
53261       }
53262       moveToParent(pCur);
53263     }
53264     pCur->info.nSize = 0;
53265     pCur->validNKey = 0;
53266
53267     pCur->aiIdx[pCur->iPage]--;
53268     pPage = pCur->apPage[pCur->iPage];
53269     if( pPage->intKey && !pPage->leaf ){
53270       rc = sqlite3BtreePrevious(pCur, pRes);
53271     }else{
53272       rc = SQLITE_OK;
53273     }
53274   }
53275   *pRes = 0;
53276   return rc;
53277 }
53278
53279 /*
53280 ** Allocate a new page from the database file.
53281 **
53282 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
53283 ** has already been called on the new page.)  The new page has also
53284 ** been referenced and the calling routine is responsible for calling
53285 ** sqlite3PagerUnref() on the new page when it is done.
53286 **
53287 ** SQLITE_OK is returned on success.  Any other return value indicates
53288 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
53289 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
53290 **
53291 ** If the "nearby" parameter is not 0, then an effort is made to 
53292 ** locate a page close to the page number "nearby".  This can be used in an
53293 ** attempt to keep related pages close to each other in the database file,
53294 ** which in turn can make database access faster.
53295 **
53296 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
53297 ** anywhere on the free-list, then it is guaranteed to be returned.  If
53298 ** eMode is BTALLOC_LT then the page returned will be less than or equal
53299 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
53300 ** are no restrictions on which page is returned.
53301 */
53302 static int allocateBtreePage(
53303   BtShared *pBt,         /* The btree */
53304   MemPage **ppPage,      /* Store pointer to the allocated page here */
53305   Pgno *pPgno,           /* Store the page number here */
53306   Pgno nearby,           /* Search for a page near this one */
53307   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
53308 ){
53309   MemPage *pPage1;
53310   int rc;
53311   u32 n;     /* Number of pages on the freelist */
53312   u32 k;     /* Number of leaves on the trunk of the freelist */
53313   MemPage *pTrunk = 0;
53314   MemPage *pPrevTrunk = 0;
53315   Pgno mxPage;     /* Total size of the database file */
53316
53317   assert( sqlite3_mutex_held(pBt->mutex) );
53318   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
53319   pPage1 = pBt->pPage1;
53320   mxPage = btreePagecount(pBt);
53321   n = get4byte(&pPage1->aData[36]);
53322   testcase( n==mxPage-1 );
53323   if( n>=mxPage ){
53324     return SQLITE_CORRUPT_BKPT;
53325   }
53326   if( n>0 ){
53327     /* There are pages on the freelist.  Reuse one of those pages. */
53328     Pgno iTrunk;
53329     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
53330     
53331     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
53332     ** shows that the page 'nearby' is somewhere on the free-list, then
53333     ** the entire-list will be searched for that page.
53334     */
53335 #ifndef SQLITE_OMIT_AUTOVACUUM
53336     if( eMode==BTALLOC_EXACT ){
53337       if( nearby<=mxPage ){
53338         u8 eType;
53339         assert( nearby>0 );
53340         assert( pBt->autoVacuum );
53341         rc = ptrmapGet(pBt, nearby, &eType, 0);
53342         if( rc ) return rc;
53343         if( eType==PTRMAP_FREEPAGE ){
53344           searchList = 1;
53345         }
53346       }
53347     }else if( eMode==BTALLOC_LE ){
53348       searchList = 1;
53349     }
53350 #endif
53351
53352     /* Decrement the free-list count by 1. Set iTrunk to the index of the
53353     ** first free-list trunk page. iPrevTrunk is initially 1.
53354     */
53355     rc = sqlite3PagerWrite(pPage1->pDbPage);
53356     if( rc ) return rc;
53357     put4byte(&pPage1->aData[36], n-1);
53358
53359     /* The code within this loop is run only once if the 'searchList' variable
53360     ** is not true. Otherwise, it runs once for each trunk-page on the
53361     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
53362     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
53363     */
53364     do {
53365       pPrevTrunk = pTrunk;
53366       if( pPrevTrunk ){
53367         iTrunk = get4byte(&pPrevTrunk->aData[0]);
53368       }else{
53369         iTrunk = get4byte(&pPage1->aData[32]);
53370       }
53371       testcase( iTrunk==mxPage );
53372       if( iTrunk>mxPage ){
53373         rc = SQLITE_CORRUPT_BKPT;
53374       }else{
53375         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
53376       }
53377       if( rc ){
53378         pTrunk = 0;
53379         goto end_allocate_page;
53380       }
53381       assert( pTrunk!=0 );
53382       assert( pTrunk->aData!=0 );
53383
53384       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
53385       if( k==0 && !searchList ){
53386         /* The trunk has no leaves and the list is not being searched. 
53387         ** So extract the trunk page itself and use it as the newly 
53388         ** allocated page */
53389         assert( pPrevTrunk==0 );
53390         rc = sqlite3PagerWrite(pTrunk->pDbPage);
53391         if( rc ){
53392           goto end_allocate_page;
53393         }
53394         *pPgno = iTrunk;
53395         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
53396         *ppPage = pTrunk;
53397         pTrunk = 0;
53398         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
53399       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
53400         /* Value of k is out of range.  Database corruption */
53401         rc = SQLITE_CORRUPT_BKPT;
53402         goto end_allocate_page;
53403 #ifndef SQLITE_OMIT_AUTOVACUUM
53404       }else if( searchList 
53405             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) 
53406       ){
53407         /* The list is being searched and this trunk page is the page
53408         ** to allocate, regardless of whether it has leaves.
53409         */
53410         *pPgno = iTrunk;
53411         *ppPage = pTrunk;
53412         searchList = 0;
53413         rc = sqlite3PagerWrite(pTrunk->pDbPage);
53414         if( rc ){
53415           goto end_allocate_page;
53416         }
53417         if( k==0 ){
53418           if( !pPrevTrunk ){
53419             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
53420           }else{
53421             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
53422             if( rc!=SQLITE_OK ){
53423               goto end_allocate_page;
53424             }
53425             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
53426           }
53427         }else{
53428           /* The trunk page is required by the caller but it contains 
53429           ** pointers to free-list leaves. The first leaf becomes a trunk
53430           ** page in this case.
53431           */
53432           MemPage *pNewTrunk;
53433           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
53434           if( iNewTrunk>mxPage ){ 
53435             rc = SQLITE_CORRUPT_BKPT;
53436             goto end_allocate_page;
53437           }
53438           testcase( iNewTrunk==mxPage );
53439           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
53440           if( rc!=SQLITE_OK ){
53441             goto end_allocate_page;
53442           }
53443           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
53444           if( rc!=SQLITE_OK ){
53445             releasePage(pNewTrunk);
53446             goto end_allocate_page;
53447           }
53448           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
53449           put4byte(&pNewTrunk->aData[4], k-1);
53450           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
53451           releasePage(pNewTrunk);
53452           if( !pPrevTrunk ){
53453             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
53454             put4byte(&pPage1->aData[32], iNewTrunk);
53455           }else{
53456             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
53457             if( rc ){
53458               goto end_allocate_page;
53459             }
53460             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
53461           }
53462         }
53463         pTrunk = 0;
53464         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
53465 #endif
53466       }else if( k>0 ){
53467         /* Extract a leaf from the trunk */
53468         u32 closest;
53469         Pgno iPage;
53470         unsigned char *aData = pTrunk->aData;
53471         if( nearby>0 ){
53472           u32 i;
53473           closest = 0;
53474           if( eMode==BTALLOC_LE ){
53475             for(i=0; i<k; i++){
53476               iPage = get4byte(&aData[8+i*4]);
53477               if( iPage<=nearby ){
53478                 closest = i;
53479                 break;
53480               }
53481             }
53482           }else{
53483             int dist;
53484             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
53485             for(i=1; i<k; i++){
53486               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
53487               if( d2<dist ){
53488                 closest = i;
53489                 dist = d2;
53490               }
53491             }
53492           }
53493         }else{
53494           closest = 0;
53495         }
53496
53497         iPage = get4byte(&aData[8+closest*4]);
53498         testcase( iPage==mxPage );
53499         if( iPage>mxPage ){
53500           rc = SQLITE_CORRUPT_BKPT;
53501           goto end_allocate_page;
53502         }
53503         testcase( iPage==mxPage );
53504         if( !searchList 
53505          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) 
53506         ){
53507           int noContent;
53508           *pPgno = iPage;
53509           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
53510                  ": %d more free pages\n",
53511                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
53512           rc = sqlite3PagerWrite(pTrunk->pDbPage);
53513           if( rc ) goto end_allocate_page;
53514           if( closest<k-1 ){
53515             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
53516           }
53517           put4byte(&aData[4], k-1);
53518           noContent = !btreeGetHasContent(pBt, *pPgno);
53519           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
53520           if( rc==SQLITE_OK ){
53521             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
53522             if( rc!=SQLITE_OK ){
53523               releasePage(*ppPage);
53524             }
53525           }
53526           searchList = 0;
53527         }
53528       }
53529       releasePage(pPrevTrunk);
53530       pPrevTrunk = 0;
53531     }while( searchList );
53532   }else{
53533     /* There are no pages on the freelist, so append a new page to the
53534     ** database image.
53535     **
53536     ** Normally, new pages allocated by this block can be requested from the
53537     ** pager layer with the 'no-content' flag set. This prevents the pager
53538     ** from trying to read the pages content from disk. However, if the
53539     ** current transaction has already run one or more incremental-vacuum
53540     ** steps, then the page we are about to allocate may contain content
53541     ** that is required in the event of a rollback. In this case, do
53542     ** not set the no-content flag. This causes the pager to load and journal
53543     ** the current page content before overwriting it.
53544     **
53545     ** Note that the pager will not actually attempt to load or journal 
53546     ** content for any page that really does lie past the end of the database
53547     ** file on disk. So the effects of disabling the no-content optimization
53548     ** here are confined to those pages that lie between the end of the
53549     ** database image and the end of the database file.
53550     */
53551     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate));
53552
53553     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53554     if( rc ) return rc;
53555     pBt->nPage++;
53556     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
53557
53558 #ifndef SQLITE_OMIT_AUTOVACUUM
53559     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
53560       /* If *pPgno refers to a pointer-map page, allocate two new pages
53561       ** at the end of the file instead of one. The first allocated page
53562       ** becomes a new pointer-map page, the second is used by the caller.
53563       */
53564       MemPage *pPg = 0;
53565       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
53566       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
53567       rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
53568       if( rc==SQLITE_OK ){
53569         rc = sqlite3PagerWrite(pPg->pDbPage);
53570         releasePage(pPg);
53571       }
53572       if( rc ) return rc;
53573       pBt->nPage++;
53574       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
53575     }
53576 #endif
53577     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
53578     *pPgno = pBt->nPage;
53579
53580     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
53581     rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
53582     if( rc ) return rc;
53583     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
53584     if( rc!=SQLITE_OK ){
53585       releasePage(*ppPage);
53586     }
53587     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
53588   }
53589
53590   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
53591
53592 end_allocate_page:
53593   releasePage(pTrunk);
53594   releasePage(pPrevTrunk);
53595   if( rc==SQLITE_OK ){
53596     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
53597       releasePage(*ppPage);
53598       return SQLITE_CORRUPT_BKPT;
53599     }
53600     (*ppPage)->isInit = 0;
53601   }else{
53602     *ppPage = 0;
53603   }
53604   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
53605   return rc;
53606 }
53607
53608 /*
53609 ** This function is used to add page iPage to the database file free-list. 
53610 ** It is assumed that the page is not already a part of the free-list.
53611 **
53612 ** The value passed as the second argument to this function is optional.
53613 ** If the caller happens to have a pointer to the MemPage object 
53614 ** corresponding to page iPage handy, it may pass it as the second value. 
53615 ** Otherwise, it may pass NULL.
53616 **
53617 ** If a pointer to a MemPage object is passed as the second argument,
53618 ** its reference count is not altered by this function.
53619 */
53620 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
53621   MemPage *pTrunk = 0;                /* Free-list trunk page */
53622   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
53623   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
53624   MemPage *pPage;                     /* Page being freed. May be NULL. */
53625   int rc;                             /* Return Code */
53626   int nFree;                          /* Initial number of pages on free-list */
53627
53628   assert( sqlite3_mutex_held(pBt->mutex) );
53629   assert( iPage>1 );
53630   assert( !pMemPage || pMemPage->pgno==iPage );
53631
53632   if( pMemPage ){
53633     pPage = pMemPage;
53634     sqlite3PagerRef(pPage->pDbPage);
53635   }else{
53636     pPage = btreePageLookup(pBt, iPage);
53637   }
53638
53639   /* Increment the free page count on pPage1 */
53640   rc = sqlite3PagerWrite(pPage1->pDbPage);
53641   if( rc ) goto freepage_out;
53642   nFree = get4byte(&pPage1->aData[36]);
53643   put4byte(&pPage1->aData[36], nFree+1);
53644
53645   if( pBt->btsFlags & BTS_SECURE_DELETE ){
53646     /* If the secure_delete option is enabled, then
53647     ** always fully overwrite deleted information with zeros.
53648     */
53649     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
53650      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
53651     ){
53652       goto freepage_out;
53653     }
53654     memset(pPage->aData, 0, pPage->pBt->pageSize);
53655   }
53656
53657   /* If the database supports auto-vacuum, write an entry in the pointer-map
53658   ** to indicate that the page is free.
53659   */
53660   if( ISAUTOVACUUM ){
53661     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
53662     if( rc ) goto freepage_out;
53663   }
53664
53665   /* Now manipulate the actual database free-list structure. There are two
53666   ** possibilities. If the free-list is currently empty, or if the first
53667   ** trunk page in the free-list is full, then this page will become a
53668   ** new free-list trunk page. Otherwise, it will become a leaf of the
53669   ** first trunk page in the current free-list. This block tests if it
53670   ** is possible to add the page as a new free-list leaf.
53671   */
53672   if( nFree!=0 ){
53673     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
53674
53675     iTrunk = get4byte(&pPage1->aData[32]);
53676     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
53677     if( rc!=SQLITE_OK ){
53678       goto freepage_out;
53679     }
53680
53681     nLeaf = get4byte(&pTrunk->aData[4]);
53682     assert( pBt->usableSize>32 );
53683     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
53684       rc = SQLITE_CORRUPT_BKPT;
53685       goto freepage_out;
53686     }
53687     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
53688       /* In this case there is room on the trunk page to insert the page
53689       ** being freed as a new leaf.
53690       **
53691       ** Note that the trunk page is not really full until it contains
53692       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
53693       ** coded.  But due to a coding error in versions of SQLite prior to
53694       ** 3.6.0, databases with freelist trunk pages holding more than
53695       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
53696       ** to maintain backwards compatibility with older versions of SQLite,
53697       ** we will continue to restrict the number of entries to usableSize/4 - 8
53698       ** for now.  At some point in the future (once everyone has upgraded
53699       ** to 3.6.0 or later) we should consider fixing the conditional above
53700       ** to read "usableSize/4-2" instead of "usableSize/4-8".
53701       */
53702       rc = sqlite3PagerWrite(pTrunk->pDbPage);
53703       if( rc==SQLITE_OK ){
53704         put4byte(&pTrunk->aData[4], nLeaf+1);
53705         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
53706         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
53707           sqlite3PagerDontWrite(pPage->pDbPage);
53708         }
53709         rc = btreeSetHasContent(pBt, iPage);
53710       }
53711       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
53712       goto freepage_out;
53713     }
53714   }
53715
53716   /* If control flows to this point, then it was not possible to add the
53717   ** the page being freed as a leaf page of the first trunk in the free-list.
53718   ** Possibly because the free-list is empty, or possibly because the 
53719   ** first trunk in the free-list is full. Either way, the page being freed
53720   ** will become the new first trunk page in the free-list.
53721   */
53722   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
53723     goto freepage_out;
53724   }
53725   rc = sqlite3PagerWrite(pPage->pDbPage);
53726   if( rc!=SQLITE_OK ){
53727     goto freepage_out;
53728   }
53729   put4byte(pPage->aData, iTrunk);
53730   put4byte(&pPage->aData[4], 0);
53731   put4byte(&pPage1->aData[32], iPage);
53732   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
53733
53734 freepage_out:
53735   if( pPage ){
53736     pPage->isInit = 0;
53737   }
53738   releasePage(pPage);
53739   releasePage(pTrunk);
53740   return rc;
53741 }
53742 static void freePage(MemPage *pPage, int *pRC){
53743   if( (*pRC)==SQLITE_OK ){
53744     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
53745   }
53746 }
53747
53748 /*
53749 ** Free any overflow pages associated with the given Cell.
53750 */
53751 static int clearCell(MemPage *pPage, unsigned char *pCell){
53752   BtShared *pBt = pPage->pBt;
53753   CellInfo info;
53754   Pgno ovflPgno;
53755   int rc;
53756   int nOvfl;
53757   u32 ovflPageSize;
53758
53759   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53760   btreeParseCellPtr(pPage, pCell, &info);
53761   if( info.iOverflow==0 ){
53762     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
53763   }
53764   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
53765     return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
53766   }
53767   ovflPgno = get4byte(&pCell[info.iOverflow]);
53768   assert( pBt->usableSize > 4 );
53769   ovflPageSize = pBt->usableSize - 4;
53770   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
53771   assert( ovflPgno==0 || nOvfl>0 );
53772   while( nOvfl-- ){
53773     Pgno iNext = 0;
53774     MemPage *pOvfl = 0;
53775     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
53776       /* 0 is not a legal page number and page 1 cannot be an 
53777       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
53778       ** file the database must be corrupt. */
53779       return SQLITE_CORRUPT_BKPT;
53780     }
53781     if( nOvfl ){
53782       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
53783       if( rc ) return rc;
53784     }
53785
53786     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
53787      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
53788     ){
53789       /* There is no reason any cursor should have an outstanding reference 
53790       ** to an overflow page belonging to a cell that is being deleted/updated.
53791       ** So if there exists more than one reference to this page, then it 
53792       ** must not really be an overflow page and the database must be corrupt. 
53793       ** It is helpful to detect this before calling freePage2(), as 
53794       ** freePage2() may zero the page contents if secure-delete mode is
53795       ** enabled. If this 'overflow' page happens to be a page that the
53796       ** caller is iterating through or using in some other way, this
53797       ** can be problematic.
53798       */
53799       rc = SQLITE_CORRUPT_BKPT;
53800     }else{
53801       rc = freePage2(pBt, pOvfl, ovflPgno);
53802     }
53803
53804     if( pOvfl ){
53805       sqlite3PagerUnref(pOvfl->pDbPage);
53806     }
53807     if( rc ) return rc;
53808     ovflPgno = iNext;
53809   }
53810   return SQLITE_OK;
53811 }
53812
53813 /*
53814 ** Create the byte sequence used to represent a cell on page pPage
53815 ** and write that byte sequence into pCell[].  Overflow pages are
53816 ** allocated and filled in as necessary.  The calling procedure
53817 ** is responsible for making sure sufficient space has been allocated
53818 ** for pCell[].
53819 **
53820 ** Note that pCell does not necessary need to point to the pPage->aData
53821 ** area.  pCell might point to some temporary storage.  The cell will
53822 ** be constructed in this temporary area then copied into pPage->aData
53823 ** later.
53824 */
53825 static int fillInCell(
53826   MemPage *pPage,                /* The page that contains the cell */
53827   unsigned char *pCell,          /* Complete text of the cell */
53828   const void *pKey, i64 nKey,    /* The key */
53829   const void *pData,int nData,   /* The data */
53830   int nZero,                     /* Extra zero bytes to append to pData */
53831   int *pnSize                    /* Write cell size here */
53832 ){
53833   int nPayload;
53834   const u8 *pSrc;
53835   int nSrc, n, rc;
53836   int spaceLeft;
53837   MemPage *pOvfl = 0;
53838   MemPage *pToRelease = 0;
53839   unsigned char *pPrior;
53840   unsigned char *pPayload;
53841   BtShared *pBt = pPage->pBt;
53842   Pgno pgnoOvfl = 0;
53843   int nHeader;
53844   CellInfo info;
53845
53846   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53847
53848   /* pPage is not necessarily writeable since pCell might be auxiliary
53849   ** buffer space that is separate from the pPage buffer area */
53850   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
53851             || sqlite3PagerIswriteable(pPage->pDbPage) );
53852
53853   /* Fill in the header. */
53854   nHeader = 0;
53855   if( !pPage->leaf ){
53856     nHeader += 4;
53857   }
53858   if( pPage->hasData ){
53859     nHeader += putVarint(&pCell[nHeader], nData+nZero);
53860   }else{
53861     nData = nZero = 0;
53862   }
53863   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
53864   btreeParseCellPtr(pPage, pCell, &info);
53865   assert( info.nHeader==nHeader );
53866   assert( info.nKey==nKey );
53867   assert( info.nData==(u32)(nData+nZero) );
53868   
53869   /* Fill in the payload */
53870   nPayload = nData + nZero;
53871   if( pPage->intKey ){
53872     pSrc = pData;
53873     nSrc = nData;
53874     nData = 0;
53875   }else{ 
53876     if( NEVER(nKey>0x7fffffff || pKey==0) ){
53877       return SQLITE_CORRUPT_BKPT;
53878     }
53879     nPayload += (int)nKey;
53880     pSrc = pKey;
53881     nSrc = (int)nKey;
53882   }
53883   *pnSize = info.nSize;
53884   spaceLeft = info.nLocal;
53885   pPayload = &pCell[nHeader];
53886   pPrior = &pCell[info.iOverflow];
53887
53888   while( nPayload>0 ){
53889     if( spaceLeft==0 ){
53890 #ifndef SQLITE_OMIT_AUTOVACUUM
53891       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
53892       if( pBt->autoVacuum ){
53893         do{
53894           pgnoOvfl++;
53895         } while( 
53896           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
53897         );
53898       }
53899 #endif
53900       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
53901 #ifndef SQLITE_OMIT_AUTOVACUUM
53902       /* If the database supports auto-vacuum, and the second or subsequent
53903       ** overflow page is being allocated, add an entry to the pointer-map
53904       ** for that page now. 
53905       **
53906       ** If this is the first overflow page, then write a partial entry 
53907       ** to the pointer-map. If we write nothing to this pointer-map slot,
53908       ** then the optimistic overflow chain processing in clearCell()
53909       ** may misinterpret the uninitialized values and delete the
53910       ** wrong pages from the database.
53911       */
53912       if( pBt->autoVacuum && rc==SQLITE_OK ){
53913         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
53914         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
53915         if( rc ){
53916           releasePage(pOvfl);
53917         }
53918       }
53919 #endif
53920       if( rc ){
53921         releasePage(pToRelease);
53922         return rc;
53923       }
53924
53925       /* If pToRelease is not zero than pPrior points into the data area
53926       ** of pToRelease.  Make sure pToRelease is still writeable. */
53927       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
53928
53929       /* If pPrior is part of the data area of pPage, then make sure pPage
53930       ** is still writeable */
53931       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
53932             || sqlite3PagerIswriteable(pPage->pDbPage) );
53933
53934       put4byte(pPrior, pgnoOvfl);
53935       releasePage(pToRelease);
53936       pToRelease = pOvfl;
53937       pPrior = pOvfl->aData;
53938       put4byte(pPrior, 0);
53939       pPayload = &pOvfl->aData[4];
53940       spaceLeft = pBt->usableSize - 4;
53941     }
53942     n = nPayload;
53943     if( n>spaceLeft ) n = spaceLeft;
53944
53945     /* If pToRelease is not zero than pPayload points into the data area
53946     ** of pToRelease.  Make sure pToRelease is still writeable. */
53947     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
53948
53949     /* If pPayload is part of the data area of pPage, then make sure pPage
53950     ** is still writeable */
53951     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
53952             || sqlite3PagerIswriteable(pPage->pDbPage) );
53953
53954     if( nSrc>0 ){
53955       if( n>nSrc ) n = nSrc;
53956       assert( pSrc );
53957       memcpy(pPayload, pSrc, n);
53958     }else{
53959       memset(pPayload, 0, n);
53960     }
53961     nPayload -= n;
53962     pPayload += n;
53963     pSrc += n;
53964     nSrc -= n;
53965     spaceLeft -= n;
53966     if( nSrc==0 ){
53967       nSrc = nData;
53968       pSrc = pData;
53969     }
53970   }
53971   releasePage(pToRelease);
53972   return SQLITE_OK;
53973 }
53974
53975 /*
53976 ** Remove the i-th cell from pPage.  This routine effects pPage only.
53977 ** The cell content is not freed or deallocated.  It is assumed that
53978 ** the cell content has been copied someplace else.  This routine just
53979 ** removes the reference to the cell from pPage.
53980 **
53981 ** "sz" must be the number of bytes in the cell.
53982 */
53983 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
53984   u32 pc;         /* Offset to cell content of cell being deleted */
53985   u8 *data;       /* pPage->aData */
53986   u8 *ptr;        /* Used to move bytes around within data[] */
53987   u8 *endPtr;     /* End of loop */
53988   int rc;         /* The return code */
53989   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
53990
53991   if( *pRC ) return;
53992
53993   assert( idx>=0 && idx<pPage->nCell );
53994   assert( sz==cellSize(pPage, idx) );
53995   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53996   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53997   data = pPage->aData;
53998   ptr = &pPage->aCellIdx[2*idx];
53999   pc = get2byte(ptr);
54000   hdr = pPage->hdrOffset;
54001   testcase( pc==get2byte(&data[hdr+5]) );
54002   testcase( pc+sz==pPage->pBt->usableSize );
54003   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
54004     *pRC = SQLITE_CORRUPT_BKPT;
54005     return;
54006   }
54007   rc = freeSpace(pPage, pc, sz);
54008   if( rc ){
54009     *pRC = rc;
54010     return;
54011   }
54012   endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
54013   assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
54014   while( ptr<endPtr ){
54015     *(u16*)ptr = *(u16*)&ptr[2];
54016     ptr += 2;
54017   }
54018   pPage->nCell--;
54019   put2byte(&data[hdr+3], pPage->nCell);
54020   pPage->nFree += 2;
54021 }
54022
54023 /*
54024 ** Insert a new cell on pPage at cell index "i".  pCell points to the
54025 ** content of the cell.
54026 **
54027 ** If the cell content will fit on the page, then put it there.  If it
54028 ** will not fit, then make a copy of the cell content into pTemp if
54029 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
54030 ** in pPage->apOvfl[] and make it point to the cell content (either
54031 ** in pTemp or the original pCell) and also record its index. 
54032 ** Allocating a new entry in pPage->aCell[] implies that 
54033 ** pPage->nOverflow is incremented.
54034 **
54035 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
54036 ** cell. The caller will overwrite them after this function returns. If
54037 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
54038 ** (but pCell+nSkip is always valid).
54039 */
54040 static void insertCell(
54041   MemPage *pPage,   /* Page into which we are copying */
54042   int i,            /* New cell becomes the i-th cell of the page */
54043   u8 *pCell,        /* Content of the new cell */
54044   int sz,           /* Bytes of content in pCell */
54045   u8 *pTemp,        /* Temp storage space for pCell, if needed */
54046   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
54047   int *pRC          /* Read and write return code from here */
54048 ){
54049   int idx = 0;      /* Where to write new cell content in data[] */
54050   int j;            /* Loop counter */
54051   int end;          /* First byte past the last cell pointer in data[] */
54052   int ins;          /* Index in data[] where new cell pointer is inserted */
54053   int cellOffset;   /* Address of first cell pointer in data[] */
54054   u8 *data;         /* The content of the whole page */
54055   u8 *ptr;          /* Used for moving information around in data[] */
54056   u8 *endPtr;       /* End of the loop */
54057
54058   int nSkip = (iChild ? 4 : 0);
54059
54060   if( *pRC ) return;
54061
54062   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
54063   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
54064   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
54065   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
54066   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54067   /* The cell should normally be sized correctly.  However, when moving a
54068   ** malformed cell from a leaf page to an interior page, if the cell size
54069   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
54070   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
54071   ** the term after the || in the following assert(). */
54072   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
54073   if( pPage->nOverflow || sz+2>pPage->nFree ){
54074     if( pTemp ){
54075       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
54076       pCell = pTemp;
54077     }
54078     if( iChild ){
54079       put4byte(pCell, iChild);
54080     }
54081     j = pPage->nOverflow++;
54082     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
54083     pPage->apOvfl[j] = pCell;
54084     pPage->aiOvfl[j] = (u16)i;
54085   }else{
54086     int rc = sqlite3PagerWrite(pPage->pDbPage);
54087     if( rc!=SQLITE_OK ){
54088       *pRC = rc;
54089       return;
54090     }
54091     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54092     data = pPage->aData;
54093     cellOffset = pPage->cellOffset;
54094     end = cellOffset + 2*pPage->nCell;
54095     ins = cellOffset + 2*i;
54096     rc = allocateSpace(pPage, sz, &idx);
54097     if( rc ){ *pRC = rc; return; }
54098     /* The allocateSpace() routine guarantees the following two properties
54099     ** if it returns success */
54100     assert( idx >= end+2 );
54101     assert( idx+sz <= (int)pPage->pBt->usableSize );
54102     pPage->nCell++;
54103     pPage->nFree -= (u16)(2 + sz);
54104     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
54105     if( iChild ){
54106       put4byte(&data[idx], iChild);
54107     }
54108     ptr = &data[end];
54109     endPtr = &data[ins];
54110     assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
54111     while( ptr>endPtr ){
54112       *(u16*)ptr = *(u16*)&ptr[-2];
54113       ptr -= 2;
54114     }
54115     put2byte(&data[ins], idx);
54116     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
54117 #ifndef SQLITE_OMIT_AUTOVACUUM
54118     if( pPage->pBt->autoVacuum ){
54119       /* The cell may contain a pointer to an overflow page. If so, write
54120       ** the entry for the overflow page into the pointer map.
54121       */
54122       ptrmapPutOvflPtr(pPage, pCell, pRC);
54123     }
54124 #endif
54125   }
54126 }
54127
54128 /*
54129 ** Add a list of cells to a page.  The page should be initially empty.
54130 ** The cells are guaranteed to fit on the page.
54131 */
54132 static void assemblePage(
54133   MemPage *pPage,   /* The page to be assemblied */
54134   int nCell,        /* The number of cells to add to this page */
54135   u8 **apCell,      /* Pointers to cell bodies */
54136   u16 *aSize        /* Sizes of the cells */
54137 ){
54138   int i;            /* Loop counter */
54139   u8 *pCellptr;     /* Address of next cell pointer */
54140   int cellbody;     /* Address of next cell body */
54141   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
54142   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
54143   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
54144
54145   assert( pPage->nOverflow==0 );
54146   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54147   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
54148             && (int)MX_CELL(pPage->pBt)<=10921);
54149   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54150
54151   /* Check that the page has just been zeroed by zeroPage() */
54152   assert( pPage->nCell==0 );
54153   assert( get2byteNotZero(&data[hdr+5])==nUsable );
54154
54155   pCellptr = &pPage->aCellIdx[nCell*2];
54156   cellbody = nUsable;
54157   for(i=nCell-1; i>=0; i--){
54158     u16 sz = aSize[i];
54159     pCellptr -= 2;
54160     cellbody -= sz;
54161     put2byte(pCellptr, cellbody);
54162     memcpy(&data[cellbody], apCell[i], sz);
54163   }
54164   put2byte(&data[hdr+3], nCell);
54165   put2byte(&data[hdr+5], cellbody);
54166   pPage->nFree -= (nCell*2 + nUsable - cellbody);
54167   pPage->nCell = (u16)nCell;
54168 }
54169
54170 /*
54171 ** The following parameters determine how many adjacent pages get involved
54172 ** in a balancing operation.  NN is the number of neighbors on either side
54173 ** of the page that participate in the balancing operation.  NB is the
54174 ** total number of pages that participate, including the target page and
54175 ** NN neighbors on either side.
54176 **
54177 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
54178 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
54179 ** in exchange for a larger degradation in INSERT and UPDATE performance.
54180 ** The value of NN appears to give the best results overall.
54181 */
54182 #define NN 1             /* Number of neighbors on either side of pPage */
54183 #define NB (NN*2+1)      /* Total pages involved in the balance */
54184
54185
54186 #ifndef SQLITE_OMIT_QUICKBALANCE
54187 /*
54188 ** This version of balance() handles the common special case where
54189 ** a new entry is being inserted on the extreme right-end of the
54190 ** tree, in other words, when the new entry will become the largest
54191 ** entry in the tree.
54192 **
54193 ** Instead of trying to balance the 3 right-most leaf pages, just add
54194 ** a new page to the right-hand side and put the one new entry in
54195 ** that page.  This leaves the right side of the tree somewhat
54196 ** unbalanced.  But odds are that we will be inserting new entries
54197 ** at the end soon afterwards so the nearly empty page will quickly
54198 ** fill up.  On average.
54199 **
54200 ** pPage is the leaf page which is the right-most page in the tree.
54201 ** pParent is its parent.  pPage must have a single overflow entry
54202 ** which is also the right-most entry on the page.
54203 **
54204 ** The pSpace buffer is used to store a temporary copy of the divider
54205 ** cell that will be inserted into pParent. Such a cell consists of a 4
54206 ** byte page number followed by a variable length integer. In other
54207 ** words, at most 13 bytes. Hence the pSpace buffer must be at
54208 ** least 13 bytes in size.
54209 */
54210 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
54211   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
54212   MemPage *pNew;                       /* Newly allocated page */
54213   int rc;                              /* Return Code */
54214   Pgno pgnoNew;                        /* Page number of pNew */
54215
54216   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54217   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54218   assert( pPage->nOverflow==1 );
54219
54220   /* This error condition is now caught prior to reaching this function */
54221   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
54222
54223   /* Allocate a new page. This page will become the right-sibling of 
54224   ** pPage. Make the parent page writable, so that the new divider cell
54225   ** may be inserted. If both these operations are successful, proceed.
54226   */
54227   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
54228
54229   if( rc==SQLITE_OK ){
54230
54231     u8 *pOut = &pSpace[4];
54232     u8 *pCell = pPage->apOvfl[0];
54233     u16 szCell = cellSizePtr(pPage, pCell);
54234     u8 *pStop;
54235
54236     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
54237     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
54238     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
54239     assemblePage(pNew, 1, &pCell, &szCell);
54240
54241     /* If this is an auto-vacuum database, update the pointer map
54242     ** with entries for the new page, and any pointer from the 
54243     ** cell on the page to an overflow page. If either of these
54244     ** operations fails, the return code is set, but the contents
54245     ** of the parent page are still manipulated by thh code below.
54246     ** That is Ok, at this point the parent page is guaranteed to
54247     ** be marked as dirty. Returning an error code will cause a
54248     ** rollback, undoing any changes made to the parent page.
54249     */
54250     if( ISAUTOVACUUM ){
54251       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
54252       if( szCell>pNew->minLocal ){
54253         ptrmapPutOvflPtr(pNew, pCell, &rc);
54254       }
54255     }
54256   
54257     /* Create a divider cell to insert into pParent. The divider cell
54258     ** consists of a 4-byte page number (the page number of pPage) and
54259     ** a variable length key value (which must be the same value as the
54260     ** largest key on pPage).
54261     **
54262     ** To find the largest key value on pPage, first find the right-most 
54263     ** cell on pPage. The first two fields of this cell are the 
54264     ** record-length (a variable length integer at most 32-bits in size)
54265     ** and the key value (a variable length integer, may have any value).
54266     ** The first of the while(...) loops below skips over the record-length
54267     ** field. The second while(...) loop copies the key value from the
54268     ** cell on pPage into the pSpace buffer.
54269     */
54270     pCell = findCell(pPage, pPage->nCell-1);
54271     pStop = &pCell[9];
54272     while( (*(pCell++)&0x80) && pCell<pStop );
54273     pStop = &pCell[9];
54274     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
54275
54276     /* Insert the new divider cell into pParent. */
54277     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
54278                0, pPage->pgno, &rc);
54279
54280     /* Set the right-child pointer of pParent to point to the new page. */
54281     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
54282   
54283     /* Release the reference to the new page. */
54284     releasePage(pNew);
54285   }
54286
54287   return rc;
54288 }
54289 #endif /* SQLITE_OMIT_QUICKBALANCE */
54290
54291 #if 0
54292 /*
54293 ** This function does not contribute anything to the operation of SQLite.
54294 ** it is sometimes activated temporarily while debugging code responsible 
54295 ** for setting pointer-map entries.
54296 */
54297 static int ptrmapCheckPages(MemPage **apPage, int nPage){
54298   int i, j;
54299   for(i=0; i<nPage; i++){
54300     Pgno n;
54301     u8 e;
54302     MemPage *pPage = apPage[i];
54303     BtShared *pBt = pPage->pBt;
54304     assert( pPage->isInit );
54305
54306     for(j=0; j<pPage->nCell; j++){
54307       CellInfo info;
54308       u8 *z;
54309      
54310       z = findCell(pPage, j);
54311       btreeParseCellPtr(pPage, z, &info);
54312       if( info.iOverflow ){
54313         Pgno ovfl = get4byte(&z[info.iOverflow]);
54314         ptrmapGet(pBt, ovfl, &e, &n);
54315         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
54316       }
54317       if( !pPage->leaf ){
54318         Pgno child = get4byte(z);
54319         ptrmapGet(pBt, child, &e, &n);
54320         assert( n==pPage->pgno && e==PTRMAP_BTREE );
54321       }
54322     }
54323     if( !pPage->leaf ){
54324       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54325       ptrmapGet(pBt, child, &e, &n);
54326       assert( n==pPage->pgno && e==PTRMAP_BTREE );
54327     }
54328   }
54329   return 1;
54330 }
54331 #endif
54332
54333 /*
54334 ** This function is used to copy the contents of the b-tree node stored 
54335 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
54336 ** the pointer-map entries for each child page are updated so that the
54337 ** parent page stored in the pointer map is page pTo. If pFrom contained
54338 ** any cells with overflow page pointers, then the corresponding pointer
54339 ** map entries are also updated so that the parent page is page pTo.
54340 **
54341 ** If pFrom is currently carrying any overflow cells (entries in the
54342 ** MemPage.apOvfl[] array), they are not copied to pTo. 
54343 **
54344 ** Before returning, page pTo is reinitialized using btreeInitPage().
54345 **
54346 ** The performance of this function is not critical. It is only used by 
54347 ** the balance_shallower() and balance_deeper() procedures, neither of
54348 ** which are called often under normal circumstances.
54349 */
54350 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
54351   if( (*pRC)==SQLITE_OK ){
54352     BtShared * const pBt = pFrom->pBt;
54353     u8 * const aFrom = pFrom->aData;
54354     u8 * const aTo = pTo->aData;
54355     int const iFromHdr = pFrom->hdrOffset;
54356     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
54357     int rc;
54358     int iData;
54359   
54360   
54361     assert( pFrom->isInit );
54362     assert( pFrom->nFree>=iToHdr );
54363     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
54364   
54365     /* Copy the b-tree node content from page pFrom to page pTo. */
54366     iData = get2byte(&aFrom[iFromHdr+5]);
54367     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
54368     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
54369   
54370     /* Reinitialize page pTo so that the contents of the MemPage structure
54371     ** match the new data. The initialization of pTo can actually fail under
54372     ** fairly obscure circumstances, even though it is a copy of initialized 
54373     ** page pFrom.
54374     */
54375     pTo->isInit = 0;
54376     rc = btreeInitPage(pTo);
54377     if( rc!=SQLITE_OK ){
54378       *pRC = rc;
54379       return;
54380     }
54381   
54382     /* If this is an auto-vacuum database, update the pointer-map entries
54383     ** for any b-tree or overflow pages that pTo now contains the pointers to.
54384     */
54385     if( ISAUTOVACUUM ){
54386       *pRC = setChildPtrmaps(pTo);
54387     }
54388   }
54389 }
54390
54391 /*
54392 ** This routine redistributes cells on the iParentIdx'th child of pParent
54393 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
54394 ** same amount of free space. Usually a single sibling on either side of the
54395 ** page are used in the balancing, though both siblings might come from one
54396 ** side if the page is the first or last child of its parent. If the page 
54397 ** has fewer than 2 siblings (something which can only happen if the page
54398 ** is a root page or a child of a root page) then all available siblings
54399 ** participate in the balancing.
54400 **
54401 ** The number of siblings of the page might be increased or decreased by 
54402 ** one or two in an effort to keep pages nearly full but not over full. 
54403 **
54404 ** Note that when this routine is called, some of the cells on the page
54405 ** might not actually be stored in MemPage.aData[]. This can happen
54406 ** if the page is overfull. This routine ensures that all cells allocated
54407 ** to the page and its siblings fit into MemPage.aData[] before returning.
54408 **
54409 ** In the course of balancing the page and its siblings, cells may be
54410 ** inserted into or removed from the parent page (pParent). Doing so
54411 ** may cause the parent page to become overfull or underfull. If this
54412 ** happens, it is the responsibility of the caller to invoke the correct
54413 ** balancing routine to fix this problem (see the balance() routine). 
54414 **
54415 ** If this routine fails for any reason, it might leave the database
54416 ** in a corrupted state. So if this routine fails, the database should
54417 ** be rolled back.
54418 **
54419 ** The third argument to this function, aOvflSpace, is a pointer to a
54420 ** buffer big enough to hold one page. If while inserting cells into the parent
54421 ** page (pParent) the parent page becomes overfull, this buffer is
54422 ** used to store the parent's overflow cells. Because this function inserts
54423 ** a maximum of four divider cells into the parent page, and the maximum
54424 ** size of a cell stored within an internal node is always less than 1/4
54425 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
54426 ** enough for all overflow cells.
54427 **
54428 ** If aOvflSpace is set to a null pointer, this function returns 
54429 ** SQLITE_NOMEM.
54430 */
54431 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
54432 #pragma optimize("", off)
54433 #endif
54434 static int balance_nonroot(
54435   MemPage *pParent,               /* Parent page of siblings being balanced */
54436   int iParentIdx,                 /* Index of "the page" in pParent */
54437   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
54438   int isRoot,                     /* True if pParent is a root-page */
54439   int bBulk                       /* True if this call is part of a bulk load */
54440 ){
54441   BtShared *pBt;               /* The whole database */
54442   int nCell = 0;               /* Number of cells in apCell[] */
54443   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
54444   int nNew = 0;                /* Number of pages in apNew[] */
54445   int nOld;                    /* Number of pages in apOld[] */
54446   int i, j, k;                 /* Loop counters */
54447   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
54448   int rc = SQLITE_OK;          /* The return code */
54449   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
54450   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
54451   int usableSpace;             /* Bytes in pPage beyond the header */
54452   int pageFlags;               /* Value of pPage->aData[0] */
54453   int subtotal;                /* Subtotal of bytes in cells on one page */
54454   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
54455   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
54456   int szScratch;               /* Size of scratch memory requested */
54457   MemPage *apOld[NB];          /* pPage and up to two siblings */
54458   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
54459   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
54460   u8 *pRight;                  /* Location in parent of right-sibling pointer */
54461   u8 *apDiv[NB-1];             /* Divider cells in pParent */
54462   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
54463   int szNew[NB+2];             /* Combined size of cells place on i-th page */
54464   u8 **apCell = 0;             /* All cells begin balanced */
54465   u16 *szCell;                 /* Local size of all cells in apCell[] */
54466   u8 *aSpace1;                 /* Space for copies of dividers cells */
54467   Pgno pgno;                   /* Temp var to store a page number in */
54468
54469   pBt = pParent->pBt;
54470   assert( sqlite3_mutex_held(pBt->mutex) );
54471   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54472
54473 #if 0
54474   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
54475 #endif
54476
54477   /* At this point pParent may have at most one overflow cell. And if
54478   ** this overflow cell is present, it must be the cell with 
54479   ** index iParentIdx. This scenario comes about when this function
54480   ** is called (indirectly) from sqlite3BtreeDelete().
54481   */
54482   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
54483   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
54484
54485   if( !aOvflSpace ){
54486     return SQLITE_NOMEM;
54487   }
54488
54489   /* Find the sibling pages to balance. Also locate the cells in pParent 
54490   ** that divide the siblings. An attempt is made to find NN siblings on 
54491   ** either side of pPage. More siblings are taken from one side, however, 
54492   ** if there are fewer than NN siblings on the other side. If pParent
54493   ** has NB or fewer children then all children of pParent are taken.  
54494   **
54495   ** This loop also drops the divider cells from the parent page. This
54496   ** way, the remainder of the function does not have to deal with any
54497   ** overflow cells in the parent page, since if any existed they will
54498   ** have already been removed.
54499   */
54500   i = pParent->nOverflow + pParent->nCell;
54501   if( i<2 ){
54502     nxDiv = 0;
54503   }else{
54504     assert( bBulk==0 || bBulk==1 );
54505     if( iParentIdx==0 ){                 
54506       nxDiv = 0;
54507     }else if( iParentIdx==i ){
54508       nxDiv = i-2+bBulk;
54509     }else{
54510       assert( bBulk==0 );
54511       nxDiv = iParentIdx-1;
54512     }
54513     i = 2-bBulk;
54514   }
54515   nOld = i+1;
54516   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
54517     pRight = &pParent->aData[pParent->hdrOffset+8];
54518   }else{
54519     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
54520   }
54521   pgno = get4byte(pRight);
54522   while( 1 ){
54523     rc = getAndInitPage(pBt, pgno, &apOld[i]);
54524     if( rc ){
54525       memset(apOld, 0, (i+1)*sizeof(MemPage*));
54526       goto balance_cleanup;
54527     }
54528     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
54529     if( (i--)==0 ) break;
54530
54531     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
54532       apDiv[i] = pParent->apOvfl[0];
54533       pgno = get4byte(apDiv[i]);
54534       szNew[i] = cellSizePtr(pParent, apDiv[i]);
54535       pParent->nOverflow = 0;
54536     }else{
54537       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
54538       pgno = get4byte(apDiv[i]);
54539       szNew[i] = cellSizePtr(pParent, apDiv[i]);
54540
54541       /* Drop the cell from the parent page. apDiv[i] still points to
54542       ** the cell within the parent, even though it has been dropped.
54543       ** This is safe because dropping a cell only overwrites the first
54544       ** four bytes of it, and this function does not need the first
54545       ** four bytes of the divider cell. So the pointer is safe to use
54546       ** later on.  
54547       **
54548       ** But not if we are in secure-delete mode. In secure-delete mode,
54549       ** the dropCell() routine will overwrite the entire cell with zeroes.
54550       ** In this case, temporarily copy the cell into the aOvflSpace[]
54551       ** buffer. It will be copied out again as soon as the aSpace[] buffer
54552       ** is allocated.  */
54553       if( pBt->btsFlags & BTS_SECURE_DELETE ){
54554         int iOff;
54555
54556         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
54557         if( (iOff+szNew[i])>(int)pBt->usableSize ){
54558           rc = SQLITE_CORRUPT_BKPT;
54559           memset(apOld, 0, (i+1)*sizeof(MemPage*));
54560           goto balance_cleanup;
54561         }else{
54562           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
54563           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
54564         }
54565       }
54566       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
54567     }
54568   }
54569
54570   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
54571   ** alignment */
54572   nMaxCells = (nMaxCells + 3)&~3;
54573
54574   /*
54575   ** Allocate space for memory structures
54576   */
54577   k = pBt->pageSize + ROUND8(sizeof(MemPage));
54578   szScratch =
54579        nMaxCells*sizeof(u8*)                       /* apCell */
54580      + nMaxCells*sizeof(u16)                       /* szCell */
54581      + pBt->pageSize                               /* aSpace1 */
54582      + k*nOld;                                     /* Page copies (apCopy) */
54583   apCell = sqlite3ScratchMalloc( szScratch ); 
54584   if( apCell==0 ){
54585     rc = SQLITE_NOMEM;
54586     goto balance_cleanup;
54587   }
54588   szCell = (u16*)&apCell[nMaxCells];
54589   aSpace1 = (u8*)&szCell[nMaxCells];
54590   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
54591
54592   /*
54593   ** Load pointers to all cells on sibling pages and the divider cells
54594   ** into the local apCell[] array.  Make copies of the divider cells
54595   ** into space obtained from aSpace1[] and remove the divider cells
54596   ** from pParent.
54597   **
54598   ** If the siblings are on leaf pages, then the child pointers of the
54599   ** divider cells are stripped from the cells before they are copied
54600   ** into aSpace1[].  In this way, all cells in apCell[] are without
54601   ** child pointers.  If siblings are not leaves, then all cell in
54602   ** apCell[] include child pointers.  Either way, all cells in apCell[]
54603   ** are alike.
54604   **
54605   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
54606   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
54607   */
54608   leafCorrection = apOld[0]->leaf*4;
54609   leafData = apOld[0]->hasData;
54610   for(i=0; i<nOld; i++){
54611     int limit;
54612     
54613     /* Before doing anything else, take a copy of the i'th original sibling
54614     ** The rest of this function will use data from the copies rather
54615     ** that the original pages since the original pages will be in the
54616     ** process of being overwritten.  */
54617     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
54618     memcpy(pOld, apOld[i], sizeof(MemPage));
54619     pOld->aData = (void*)&pOld[1];
54620     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
54621
54622     limit = pOld->nCell+pOld->nOverflow;
54623     if( pOld->nOverflow>0 ){
54624       for(j=0; j<limit; j++){
54625         assert( nCell<nMaxCells );
54626         apCell[nCell] = findOverflowCell(pOld, j);
54627         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
54628         nCell++;
54629       }
54630     }else{
54631       u8 *aData = pOld->aData;
54632       u16 maskPage = pOld->maskPage;
54633       u16 cellOffset = pOld->cellOffset;
54634       for(j=0; j<limit; j++){
54635         assert( nCell<nMaxCells );
54636         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
54637         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
54638         nCell++;
54639       }
54640     }       
54641     if( i<nOld-1 && !leafData){
54642       u16 sz = (u16)szNew[i];
54643       u8 *pTemp;
54644       assert( nCell<nMaxCells );
54645       szCell[nCell] = sz;
54646       pTemp = &aSpace1[iSpace1];
54647       iSpace1 += sz;
54648       assert( sz<=pBt->maxLocal+23 );
54649       assert( iSpace1 <= (int)pBt->pageSize );
54650       memcpy(pTemp, apDiv[i], sz);
54651       apCell[nCell] = pTemp+leafCorrection;
54652       assert( leafCorrection==0 || leafCorrection==4 );
54653       szCell[nCell] = szCell[nCell] - leafCorrection;
54654       if( !pOld->leaf ){
54655         assert( leafCorrection==0 );
54656         assert( pOld->hdrOffset==0 );
54657         /* The right pointer of the child page pOld becomes the left
54658         ** pointer of the divider cell */
54659         memcpy(apCell[nCell], &pOld->aData[8], 4);
54660       }else{
54661         assert( leafCorrection==4 );
54662         if( szCell[nCell]<4 ){
54663           /* Do not allow any cells smaller than 4 bytes. */
54664           szCell[nCell] = 4;
54665         }
54666       }
54667       nCell++;
54668     }
54669   }
54670
54671   /*
54672   ** Figure out the number of pages needed to hold all nCell cells.
54673   ** Store this number in "k".  Also compute szNew[] which is the total
54674   ** size of all cells on the i-th page and cntNew[] which is the index
54675   ** in apCell[] of the cell that divides page i from page i+1.  
54676   ** cntNew[k] should equal nCell.
54677   **
54678   ** Values computed by this block:
54679   **
54680   **           k: The total number of sibling pages
54681   **    szNew[i]: Spaced used on the i-th sibling page.
54682   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
54683   **              the right of the i-th sibling page.
54684   ** usableSpace: Number of bytes of space available on each sibling.
54685   ** 
54686   */
54687   usableSpace = pBt->usableSize - 12 + leafCorrection;
54688   for(subtotal=k=i=0; i<nCell; i++){
54689     assert( i<nMaxCells );
54690     subtotal += szCell[i] + 2;
54691     if( subtotal > usableSpace ){
54692       szNew[k] = subtotal - szCell[i];
54693       cntNew[k] = i;
54694       if( leafData ){ i--; }
54695       subtotal = 0;
54696       k++;
54697       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
54698     }
54699   }
54700   szNew[k] = subtotal;
54701   cntNew[k] = nCell;
54702   k++;
54703
54704   /*
54705   ** The packing computed by the previous block is biased toward the siblings
54706   ** on the left side.  The left siblings are always nearly full, while the
54707   ** right-most sibling might be nearly empty.  This block of code attempts
54708   ** to adjust the packing of siblings to get a better balance.
54709   **
54710   ** This adjustment is more than an optimization.  The packing above might
54711   ** be so out of balance as to be illegal.  For example, the right-most
54712   ** sibling might be completely empty.  This adjustment is not optional.
54713   */
54714   for(i=k-1; i>0; i--){
54715     int szRight = szNew[i];  /* Size of sibling on the right */
54716     int szLeft = szNew[i-1]; /* Size of sibling on the left */
54717     int r;              /* Index of right-most cell in left sibling */
54718     int d;              /* Index of first cell to the left of right sibling */
54719
54720     r = cntNew[i-1] - 1;
54721     d = r + 1 - leafData;
54722     assert( d<nMaxCells );
54723     assert( r<nMaxCells );
54724     while( szRight==0 
54725        || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2)) 
54726     ){
54727       szRight += szCell[d] + 2;
54728       szLeft -= szCell[r] + 2;
54729       cntNew[i-1]--;
54730       r = cntNew[i-1] - 1;
54731       d = r + 1 - leafData;
54732     }
54733     szNew[i] = szRight;
54734     szNew[i-1] = szLeft;
54735   }
54736
54737   /* Either we found one or more cells (cntnew[0])>0) or pPage is
54738   ** a virtual root page.  A virtual root page is when the real root
54739   ** page is page 1 and we are the only child of that page.
54740   **
54741   ** UPDATE:  The assert() below is not necessarily true if the database
54742   ** file is corrupt.  The corruption will be detected and reported later
54743   ** in this procedure so there is no need to act upon it now.
54744   */
54745 #if 0
54746   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
54747 #endif
54748
54749   TRACE(("BALANCE: old: %d %d %d  ",
54750     apOld[0]->pgno, 
54751     nOld>=2 ? apOld[1]->pgno : 0,
54752     nOld>=3 ? apOld[2]->pgno : 0
54753   ));
54754
54755   /*
54756   ** Allocate k new pages.  Reuse old pages where possible.
54757   */
54758   if( apOld[0]->pgno<=1 ){
54759     rc = SQLITE_CORRUPT_BKPT;
54760     goto balance_cleanup;
54761   }
54762   pageFlags = apOld[0]->aData[0];
54763   for(i=0; i<k; i++){
54764     MemPage *pNew;
54765     if( i<nOld ){
54766       pNew = apNew[i] = apOld[i];
54767       apOld[i] = 0;
54768       rc = sqlite3PagerWrite(pNew->pDbPage);
54769       nNew++;
54770       if( rc ) goto balance_cleanup;
54771     }else{
54772       assert( i>0 );
54773       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
54774       if( rc ) goto balance_cleanup;
54775       apNew[i] = pNew;
54776       nNew++;
54777
54778       /* Set the pointer-map entry for the new sibling page. */
54779       if( ISAUTOVACUUM ){
54780         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
54781         if( rc!=SQLITE_OK ){
54782           goto balance_cleanup;
54783         }
54784       }
54785     }
54786   }
54787
54788   /* Free any old pages that were not reused as new pages.
54789   */
54790   while( i<nOld ){
54791     freePage(apOld[i], &rc);
54792     if( rc ) goto balance_cleanup;
54793     releasePage(apOld[i]);
54794     apOld[i] = 0;
54795     i++;
54796   }
54797
54798   /*
54799   ** Put the new pages in accending order.  This helps to
54800   ** keep entries in the disk file in order so that a scan
54801   ** of the table is a linear scan through the file.  That
54802   ** in turn helps the operating system to deliver pages
54803   ** from the disk more rapidly.
54804   **
54805   ** An O(n^2) insertion sort algorithm is used, but since
54806   ** n is never more than NB (a small constant), that should
54807   ** not be a problem.
54808   **
54809   ** When NB==3, this one optimization makes the database
54810   ** about 25% faster for large insertions and deletions.
54811   */
54812   for(i=0; i<k-1; i++){
54813     int minV = apNew[i]->pgno;
54814     int minI = i;
54815     for(j=i+1; j<k; j++){
54816       if( apNew[j]->pgno<(unsigned)minV ){
54817         minI = j;
54818         minV = apNew[j]->pgno;
54819       }
54820     }
54821     if( minI>i ){
54822       MemPage *pT;
54823       pT = apNew[i];
54824       apNew[i] = apNew[minI];
54825       apNew[minI] = pT;
54826     }
54827   }
54828   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
54829     apNew[0]->pgno, szNew[0],
54830     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
54831     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
54832     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
54833     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
54834
54835   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54836   put4byte(pRight, apNew[nNew-1]->pgno);
54837
54838   /*
54839   ** Evenly distribute the data in apCell[] across the new pages.
54840   ** Insert divider cells into pParent as necessary.
54841   */
54842   j = 0;
54843   for(i=0; i<nNew; i++){
54844     /* Assemble the new sibling page. */
54845     MemPage *pNew = apNew[i];
54846     assert( j<nMaxCells );
54847     zeroPage(pNew, pageFlags);
54848     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
54849     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
54850     assert( pNew->nOverflow==0 );
54851
54852     j = cntNew[i];
54853
54854     /* If the sibling page assembled above was not the right-most sibling,
54855     ** insert a divider cell into the parent page.
54856     */
54857     assert( i<nNew-1 || j==nCell );
54858     if( j<nCell ){
54859       u8 *pCell;
54860       u8 *pTemp;
54861       int sz;
54862
54863       assert( j<nMaxCells );
54864       pCell = apCell[j];
54865       sz = szCell[j] + leafCorrection;
54866       pTemp = &aOvflSpace[iOvflSpace];
54867       if( !pNew->leaf ){
54868         memcpy(&pNew->aData[8], pCell, 4);
54869       }else if( leafData ){
54870         /* If the tree is a leaf-data tree, and the siblings are leaves, 
54871         ** then there is no divider cell in apCell[]. Instead, the divider 
54872         ** cell consists of the integer key for the right-most cell of 
54873         ** the sibling-page assembled above only.
54874         */
54875         CellInfo info;
54876         j--;
54877         btreeParseCellPtr(pNew, apCell[j], &info);
54878         pCell = pTemp;
54879         sz = 4 + putVarint(&pCell[4], info.nKey);
54880         pTemp = 0;
54881       }else{
54882         pCell -= 4;
54883         /* Obscure case for non-leaf-data trees: If the cell at pCell was
54884         ** previously stored on a leaf node, and its reported size was 4
54885         ** bytes, then it may actually be smaller than this 
54886         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
54887         ** any cell). But it is important to pass the correct size to 
54888         ** insertCell(), so reparse the cell now.
54889         **
54890         ** Note that this can never happen in an SQLite data file, as all
54891         ** cells are at least 4 bytes. It only happens in b-trees used
54892         ** to evaluate "IN (SELECT ...)" and similar clauses.
54893         */
54894         if( szCell[j]==4 ){
54895           assert(leafCorrection==4);
54896           sz = cellSizePtr(pParent, pCell);
54897         }
54898       }
54899       iOvflSpace += sz;
54900       assert( sz<=pBt->maxLocal+23 );
54901       assert( iOvflSpace <= (int)pBt->pageSize );
54902       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
54903       if( rc!=SQLITE_OK ) goto balance_cleanup;
54904       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54905
54906       j++;
54907       nxDiv++;
54908     }
54909   }
54910   assert( j==nCell );
54911   assert( nOld>0 );
54912   assert( nNew>0 );
54913   if( (pageFlags & PTF_LEAF)==0 ){
54914     u8 *zChild = &apCopy[nOld-1]->aData[8];
54915     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
54916   }
54917
54918   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
54919     /* The root page of the b-tree now contains no cells. The only sibling
54920     ** page is the right-child of the parent. Copy the contents of the
54921     ** child page into the parent, decreasing the overall height of the
54922     ** b-tree structure by one. This is described as the "balance-shallower"
54923     ** sub-algorithm in some documentation.
54924     **
54925     ** If this is an auto-vacuum database, the call to copyNodeContent() 
54926     ** sets all pointer-map entries corresponding to database image pages 
54927     ** for which the pointer is stored within the content being copied.
54928     **
54929     ** The second assert below verifies that the child page is defragmented
54930     ** (it must be, as it was just reconstructed using assemblePage()). This
54931     ** is important if the parent page happens to be page 1 of the database
54932     ** image.  */
54933     assert( nNew==1 );
54934     assert( apNew[0]->nFree == 
54935         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
54936     );
54937     copyNodeContent(apNew[0], pParent, &rc);
54938     freePage(apNew[0], &rc);
54939   }else if( ISAUTOVACUUM ){
54940     /* Fix the pointer-map entries for all the cells that were shifted around. 
54941     ** There are several different types of pointer-map entries that need to
54942     ** be dealt with by this routine. Some of these have been set already, but
54943     ** many have not. The following is a summary:
54944     **
54945     **   1) The entries associated with new sibling pages that were not
54946     **      siblings when this function was called. These have already
54947     **      been set. We don't need to worry about old siblings that were
54948     **      moved to the free-list - the freePage() code has taken care
54949     **      of those.
54950     **
54951     **   2) The pointer-map entries associated with the first overflow
54952     **      page in any overflow chains used by new divider cells. These 
54953     **      have also already been taken care of by the insertCell() code.
54954     **
54955     **   3) If the sibling pages are not leaves, then the child pages of
54956     **      cells stored on the sibling pages may need to be updated.
54957     **
54958     **   4) If the sibling pages are not internal intkey nodes, then any
54959     **      overflow pages used by these cells may need to be updated
54960     **      (internal intkey nodes never contain pointers to overflow pages).
54961     **
54962     **   5) If the sibling pages are not leaves, then the pointer-map
54963     **      entries for the right-child pages of each sibling may need
54964     **      to be updated.
54965     **
54966     ** Cases 1 and 2 are dealt with above by other code. The next
54967     ** block deals with cases 3 and 4 and the one after that, case 5. Since
54968     ** setting a pointer map entry is a relatively expensive operation, this
54969     ** code only sets pointer map entries for child or overflow pages that have
54970     ** actually moved between pages.  */
54971     MemPage *pNew = apNew[0];
54972     MemPage *pOld = apCopy[0];
54973     int nOverflow = pOld->nOverflow;
54974     int iNextOld = pOld->nCell + nOverflow;
54975     int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
54976     j = 0;                             /* Current 'old' sibling page */
54977     k = 0;                             /* Current 'new' sibling page */
54978     for(i=0; i<nCell; i++){
54979       int isDivider = 0;
54980       while( i==iNextOld ){
54981         /* Cell i is the cell immediately following the last cell on old
54982         ** sibling page j. If the siblings are not leaf pages of an
54983         ** intkey b-tree, then cell i was a divider cell. */
54984         assert( j+1 < ArraySize(apCopy) );
54985         assert( j+1 < nOld );
54986         pOld = apCopy[++j];
54987         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
54988         if( pOld->nOverflow ){
54989           nOverflow = pOld->nOverflow;
54990           iOverflow = i + !leafData + pOld->aiOvfl[0];
54991         }
54992         isDivider = !leafData;  
54993       }
54994
54995       assert(nOverflow>0 || iOverflow<i );
54996       assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
54997       assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
54998       if( i==iOverflow ){
54999         isDivider = 1;
55000         if( (--nOverflow)>0 ){
55001           iOverflow++;
55002         }
55003       }
55004
55005       if( i==cntNew[k] ){
55006         /* Cell i is the cell immediately following the last cell on new
55007         ** sibling page k. If the siblings are not leaf pages of an
55008         ** intkey b-tree, then cell i is a divider cell.  */
55009         pNew = apNew[++k];
55010         if( !leafData ) continue;
55011       }
55012       assert( j<nOld );
55013       assert( k<nNew );
55014
55015       /* If the cell was originally divider cell (and is not now) or
55016       ** an overflow cell, or if the cell was located on a different sibling
55017       ** page before the balancing, then the pointer map entries associated
55018       ** with any child or overflow pages need to be updated.  */
55019       if( isDivider || pOld->pgno!=pNew->pgno ){
55020         if( !leafCorrection ){
55021           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
55022         }
55023         if( szCell[i]>pNew->minLocal ){
55024           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
55025         }
55026       }
55027     }
55028
55029     if( !leafCorrection ){
55030       for(i=0; i<nNew; i++){
55031         u32 key = get4byte(&apNew[i]->aData[8]);
55032         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
55033       }
55034     }
55035
55036 #if 0
55037     /* The ptrmapCheckPages() contains assert() statements that verify that
55038     ** all pointer map pages are set correctly. This is helpful while 
55039     ** debugging. This is usually disabled because a corrupt database may
55040     ** cause an assert() statement to fail.  */
55041     ptrmapCheckPages(apNew, nNew);
55042     ptrmapCheckPages(&pParent, 1);
55043 #endif
55044   }
55045
55046   assert( pParent->isInit );
55047   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
55048           nOld, nNew, nCell));
55049
55050   /*
55051   ** Cleanup before returning.
55052   */
55053 balance_cleanup:
55054   sqlite3ScratchFree(apCell);
55055   for(i=0; i<nOld; i++){
55056     releasePage(apOld[i]);
55057   }
55058   for(i=0; i<nNew; i++){
55059     releasePage(apNew[i]);
55060   }
55061
55062   return rc;
55063 }
55064 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
55065 #pragma optimize("", on)
55066 #endif
55067
55068
55069 /*
55070 ** This function is called when the root page of a b-tree structure is
55071 ** overfull (has one or more overflow pages).
55072 **
55073 ** A new child page is allocated and the contents of the current root
55074 ** page, including overflow cells, are copied into the child. The root
55075 ** page is then overwritten to make it an empty page with the right-child 
55076 ** pointer pointing to the new page.
55077 **
55078 ** Before returning, all pointer-map entries corresponding to pages 
55079 ** that the new child-page now contains pointers to are updated. The
55080 ** entry corresponding to the new right-child pointer of the root
55081 ** page is also updated.
55082 **
55083 ** If successful, *ppChild is set to contain a reference to the child 
55084 ** page and SQLITE_OK is returned. In this case the caller is required
55085 ** to call releasePage() on *ppChild exactly once. If an error occurs,
55086 ** an error code is returned and *ppChild is set to 0.
55087 */
55088 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
55089   int rc;                        /* Return value from subprocedures */
55090   MemPage *pChild = 0;           /* Pointer to a new child page */
55091   Pgno pgnoChild = 0;            /* Page number of the new child page */
55092   BtShared *pBt = pRoot->pBt;    /* The BTree */
55093
55094   assert( pRoot->nOverflow>0 );
55095   assert( sqlite3_mutex_held(pBt->mutex) );
55096
55097   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
55098   ** page that will become the new right-child of pPage. Copy the contents
55099   ** of the node stored on pRoot into the new child page.
55100   */
55101   rc = sqlite3PagerWrite(pRoot->pDbPage);
55102   if( rc==SQLITE_OK ){
55103     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
55104     copyNodeContent(pRoot, pChild, &rc);
55105     if( ISAUTOVACUUM ){
55106       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
55107     }
55108   }
55109   if( rc ){
55110     *ppChild = 0;
55111     releasePage(pChild);
55112     return rc;
55113   }
55114   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
55115   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
55116   assert( pChild->nCell==pRoot->nCell );
55117
55118   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
55119
55120   /* Copy the overflow cells from pRoot to pChild */
55121   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
55122          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
55123   memcpy(pChild->apOvfl, pRoot->apOvfl,
55124          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
55125   pChild->nOverflow = pRoot->nOverflow;
55126
55127   /* Zero the contents of pRoot. Then install pChild as the right-child. */
55128   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
55129   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
55130
55131   *ppChild = pChild;
55132   return SQLITE_OK;
55133 }
55134
55135 /*
55136 ** The page that pCur currently points to has just been modified in
55137 ** some way. This function figures out if this modification means the
55138 ** tree needs to be balanced, and if so calls the appropriate balancing 
55139 ** routine. Balancing routines are:
55140 **
55141 **   balance_quick()
55142 **   balance_deeper()
55143 **   balance_nonroot()
55144 */
55145 static int balance(BtCursor *pCur){
55146   int rc = SQLITE_OK;
55147   const int nMin = pCur->pBt->usableSize * 2 / 3;
55148   u8 aBalanceQuickSpace[13];
55149   u8 *pFree = 0;
55150
55151   TESTONLY( int balance_quick_called = 0 );
55152   TESTONLY( int balance_deeper_called = 0 );
55153
55154   do {
55155     int iPage = pCur->iPage;
55156     MemPage *pPage = pCur->apPage[iPage];
55157
55158     if( iPage==0 ){
55159       if( pPage->nOverflow ){
55160         /* The root page of the b-tree is overfull. In this case call the
55161         ** balance_deeper() function to create a new child for the root-page
55162         ** and copy the current contents of the root-page to it. The
55163         ** next iteration of the do-loop will balance the child page.
55164         */ 
55165         assert( (balance_deeper_called++)==0 );
55166         rc = balance_deeper(pPage, &pCur->apPage[1]);
55167         if( rc==SQLITE_OK ){
55168           pCur->iPage = 1;
55169           pCur->aiIdx[0] = 0;
55170           pCur->aiIdx[1] = 0;
55171           assert( pCur->apPage[1]->nOverflow );
55172         }
55173       }else{
55174         break;
55175       }
55176     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
55177       break;
55178     }else{
55179       MemPage * const pParent = pCur->apPage[iPage-1];
55180       int const iIdx = pCur->aiIdx[iPage-1];
55181
55182       rc = sqlite3PagerWrite(pParent->pDbPage);
55183       if( rc==SQLITE_OK ){
55184 #ifndef SQLITE_OMIT_QUICKBALANCE
55185         if( pPage->hasData
55186          && pPage->nOverflow==1
55187          && pPage->aiOvfl[0]==pPage->nCell
55188          && pParent->pgno!=1
55189          && pParent->nCell==iIdx
55190         ){
55191           /* Call balance_quick() to create a new sibling of pPage on which
55192           ** to store the overflow cell. balance_quick() inserts a new cell
55193           ** into pParent, which may cause pParent overflow. If this
55194           ** happens, the next interation of the do-loop will balance pParent 
55195           ** use either balance_nonroot() or balance_deeper(). Until this
55196           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
55197           ** buffer. 
55198           **
55199           ** The purpose of the following assert() is to check that only a
55200           ** single call to balance_quick() is made for each call to this
55201           ** function. If this were not verified, a subtle bug involving reuse
55202           ** of the aBalanceQuickSpace[] might sneak in.
55203           */
55204           assert( (balance_quick_called++)==0 );
55205           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
55206         }else
55207 #endif
55208         {
55209           /* In this case, call balance_nonroot() to redistribute cells
55210           ** between pPage and up to 2 of its sibling pages. This involves
55211           ** modifying the contents of pParent, which may cause pParent to
55212           ** become overfull or underfull. The next iteration of the do-loop
55213           ** will balance the parent page to correct this.
55214           ** 
55215           ** If the parent page becomes overfull, the overflow cell or cells
55216           ** are stored in the pSpace buffer allocated immediately below. 
55217           ** A subsequent iteration of the do-loop will deal with this by
55218           ** calling balance_nonroot() (balance_deeper() may be called first,
55219           ** but it doesn't deal with overflow cells - just moves them to a
55220           ** different page). Once this subsequent call to balance_nonroot() 
55221           ** has completed, it is safe to release the pSpace buffer used by
55222           ** the previous call, as the overflow cell data will have been 
55223           ** copied either into the body of a database page or into the new
55224           ** pSpace buffer passed to the latter call to balance_nonroot().
55225           */
55226           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
55227           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
55228           if( pFree ){
55229             /* If pFree is not NULL, it points to the pSpace buffer used 
55230             ** by a previous call to balance_nonroot(). Its contents are
55231             ** now stored either on real database pages or within the 
55232             ** new pSpace buffer, so it may be safely freed here. */
55233             sqlite3PageFree(pFree);
55234           }
55235
55236           /* The pSpace buffer will be freed after the next call to
55237           ** balance_nonroot(), or just before this function returns, whichever
55238           ** comes first. */
55239           pFree = pSpace;
55240         }
55241       }
55242
55243       pPage->nOverflow = 0;
55244
55245       /* The next iteration of the do-loop balances the parent page. */
55246       releasePage(pPage);
55247       pCur->iPage--;
55248     }
55249   }while( rc==SQLITE_OK );
55250
55251   if( pFree ){
55252     sqlite3PageFree(pFree);
55253   }
55254   return rc;
55255 }
55256
55257
55258 /*
55259 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
55260 ** and the data is given by (pData,nData).  The cursor is used only to
55261 ** define what table the record should be inserted into.  The cursor
55262 ** is left pointing at a random location.
55263 **
55264 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
55265 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
55266 **
55267 ** If the seekResult parameter is non-zero, then a successful call to
55268 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
55269 ** been performed. seekResult is the search result returned (a negative
55270 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
55271 ** a positive value if pCur points at an etry that is larger than 
55272 ** (pKey, nKey)). 
55273 **
55274 ** If the seekResult parameter is non-zero, then the caller guarantees that
55275 ** cursor pCur is pointing at the existing copy of a row that is to be
55276 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
55277 ** point to any entry or to no entry at all and so this function has to seek
55278 ** the cursor before the new key can be inserted.
55279 */
55280 SQLITE_PRIVATE int sqlite3BtreeInsert(
55281   BtCursor *pCur,                /* Insert data into the table of this cursor */
55282   const void *pKey, i64 nKey,    /* The key of the new record */
55283   const void *pData, int nData,  /* The data of the new record */
55284   int nZero,                     /* Number of extra 0 bytes to append to data */
55285   int appendBias,                /* True if this is likely an append */
55286   int seekResult                 /* Result of prior MovetoUnpacked() call */
55287 ){
55288   int rc;
55289   int loc = seekResult;          /* -1: before desired location  +1: after */
55290   int szNew = 0;
55291   int idx;
55292   MemPage *pPage;
55293   Btree *p = pCur->pBtree;
55294   BtShared *pBt = p->pBt;
55295   unsigned char *oldCell;
55296   unsigned char *newCell = 0;
55297
55298   if( pCur->eState==CURSOR_FAULT ){
55299     assert( pCur->skipNext!=SQLITE_OK );
55300     return pCur->skipNext;
55301   }
55302
55303   assert( cursorHoldsMutex(pCur) );
55304   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
55305               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
55306   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
55307
55308   /* Assert that the caller has been consistent. If this cursor was opened
55309   ** expecting an index b-tree, then the caller should be inserting blob
55310   ** keys with no associated data. If the cursor was opened expecting an
55311   ** intkey table, the caller should be inserting integer keys with a
55312   ** blob of associated data.  */
55313   assert( (pKey==0)==(pCur->pKeyInfo==0) );
55314
55315   /* Save the positions of any other cursors open on this table.
55316   **
55317   ** In some cases, the call to btreeMoveto() below is a no-op. For
55318   ** example, when inserting data into a table with auto-generated integer
55319   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
55320   ** integer key to use. It then calls this function to actually insert the 
55321   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
55322   ** that the cursor is already where it needs to be and returns without
55323   ** doing any work. To avoid thwarting these optimizations, it is important
55324   ** not to clear the cursor here.
55325   */
55326   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
55327   if( rc ) return rc;
55328
55329   /* If this is an insert into a table b-tree, invalidate any incrblob 
55330   ** cursors open on the row being replaced (assuming this is a replace
55331   ** operation - if it is not, the following is a no-op).  */
55332   if( pCur->pKeyInfo==0 ){
55333     invalidateIncrblobCursors(p, nKey, 0);
55334   }
55335
55336   if( !loc ){
55337     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
55338     if( rc ) return rc;
55339   }
55340   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
55341
55342   pPage = pCur->apPage[pCur->iPage];
55343   assert( pPage->intKey || nKey>=0 );
55344   assert( pPage->leaf || !pPage->intKey );
55345
55346   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
55347           pCur->pgnoRoot, nKey, nData, pPage->pgno,
55348           loc==0 ? "overwrite" : "new entry"));
55349   assert( pPage->isInit );
55350   allocateTempSpace(pBt);
55351   newCell = pBt->pTmpSpace;
55352   if( newCell==0 ) return SQLITE_NOMEM;
55353   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
55354   if( rc ) goto end_insert;
55355   assert( szNew==cellSizePtr(pPage, newCell) );
55356   assert( szNew <= MX_CELL_SIZE(pBt) );
55357   idx = pCur->aiIdx[pCur->iPage];
55358   if( loc==0 ){
55359     u16 szOld;
55360     assert( idx<pPage->nCell );
55361     rc = sqlite3PagerWrite(pPage->pDbPage);
55362     if( rc ){
55363       goto end_insert;
55364     }
55365     oldCell = findCell(pPage, idx);
55366     if( !pPage->leaf ){
55367       memcpy(newCell, oldCell, 4);
55368     }
55369     szOld = cellSizePtr(pPage, oldCell);
55370     rc = clearCell(pPage, oldCell);
55371     dropCell(pPage, idx, szOld, &rc);
55372     if( rc ) goto end_insert;
55373   }else if( loc<0 && pPage->nCell>0 ){
55374     assert( pPage->leaf );
55375     idx = ++pCur->aiIdx[pCur->iPage];
55376   }else{
55377     assert( pPage->leaf );
55378   }
55379   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
55380   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
55381
55382   /* If no error has occurred and pPage has an overflow cell, call balance() 
55383   ** to redistribute the cells within the tree. Since balance() may move
55384   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
55385   ** variables.
55386   **
55387   ** Previous versions of SQLite called moveToRoot() to move the cursor
55388   ** back to the root page as balance() used to invalidate the contents
55389   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
55390   ** set the cursor state to "invalid". This makes common insert operations
55391   ** slightly faster.
55392   **
55393   ** There is a subtle but important optimization here too. When inserting
55394   ** multiple records into an intkey b-tree using a single cursor (as can
55395   ** happen while processing an "INSERT INTO ... SELECT" statement), it
55396   ** is advantageous to leave the cursor pointing to the last entry in
55397   ** the b-tree if possible. If the cursor is left pointing to the last
55398   ** entry in the table, and the next row inserted has an integer key
55399   ** larger than the largest existing key, it is possible to insert the
55400   ** row without seeking the cursor. This can be a big performance boost.
55401   */
55402   pCur->info.nSize = 0;
55403   pCur->validNKey = 0;
55404   if( rc==SQLITE_OK && pPage->nOverflow ){
55405     rc = balance(pCur);
55406
55407     /* Must make sure nOverflow is reset to zero even if the balance()
55408     ** fails. Internal data structure corruption will result otherwise. 
55409     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
55410     ** from trying to save the current position of the cursor.  */
55411     pCur->apPage[pCur->iPage]->nOverflow = 0;
55412     pCur->eState = CURSOR_INVALID;
55413   }
55414   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
55415
55416 end_insert:
55417   return rc;
55418 }
55419
55420 /*
55421 ** Delete the entry that the cursor is pointing to.  The cursor
55422 ** is left pointing at a arbitrary location.
55423 */
55424 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
55425   Btree *p = pCur->pBtree;
55426   BtShared *pBt = p->pBt;              
55427   int rc;                              /* Return code */
55428   MemPage *pPage;                      /* Page to delete cell from */
55429   unsigned char *pCell;                /* Pointer to cell to delete */
55430   int iCellIdx;                        /* Index of cell to delete */
55431   int iCellDepth;                      /* Depth of node containing pCell */ 
55432
55433   assert( cursorHoldsMutex(pCur) );
55434   assert( pBt->inTransaction==TRANS_WRITE );
55435   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
55436   assert( pCur->wrFlag );
55437   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
55438   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
55439
55440   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
55441    || NEVER(pCur->eState!=CURSOR_VALID)
55442   ){
55443     return SQLITE_ERROR;  /* Something has gone awry. */
55444   }
55445
55446   iCellDepth = pCur->iPage;
55447   iCellIdx = pCur->aiIdx[iCellDepth];
55448   pPage = pCur->apPage[iCellDepth];
55449   pCell = findCell(pPage, iCellIdx);
55450
55451   /* If the page containing the entry to delete is not a leaf page, move
55452   ** the cursor to the largest entry in the tree that is smaller than
55453   ** the entry being deleted. This cell will replace the cell being deleted
55454   ** from the internal node. The 'previous' entry is used for this instead
55455   ** of the 'next' entry, as the previous entry is always a part of the
55456   ** sub-tree headed by the child page of the cell being deleted. This makes
55457   ** balancing the tree following the delete operation easier.  */
55458   if( !pPage->leaf ){
55459     int notUsed;
55460     rc = sqlite3BtreePrevious(pCur, &notUsed);
55461     if( rc ) return rc;
55462   }
55463
55464   /* Save the positions of any other cursors open on this table before
55465   ** making any modifications. Make the page containing the entry to be 
55466   ** deleted writable. Then free any overflow pages associated with the 
55467   ** entry and finally remove the cell itself from within the page.  
55468   */
55469   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
55470   if( rc ) return rc;
55471
55472   /* If this is a delete operation to remove a row from a table b-tree,
55473   ** invalidate any incrblob cursors open on the row being deleted.  */
55474   if( pCur->pKeyInfo==0 ){
55475     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
55476   }
55477
55478   rc = sqlite3PagerWrite(pPage->pDbPage);
55479   if( rc ) return rc;
55480   rc = clearCell(pPage, pCell);
55481   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
55482   if( rc ) return rc;
55483
55484   /* If the cell deleted was not located on a leaf page, then the cursor
55485   ** is currently pointing to the largest entry in the sub-tree headed
55486   ** by the child-page of the cell that was just deleted from an internal
55487   ** node. The cell from the leaf node needs to be moved to the internal
55488   ** node to replace the deleted cell.  */
55489   if( !pPage->leaf ){
55490     MemPage *pLeaf = pCur->apPage[pCur->iPage];
55491     int nCell;
55492     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
55493     unsigned char *pTmp;
55494
55495     pCell = findCell(pLeaf, pLeaf->nCell-1);
55496     nCell = cellSizePtr(pLeaf, pCell);
55497     assert( MX_CELL_SIZE(pBt) >= nCell );
55498
55499     allocateTempSpace(pBt);
55500     pTmp = pBt->pTmpSpace;
55501
55502     rc = sqlite3PagerWrite(pLeaf->pDbPage);
55503     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
55504     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
55505     if( rc ) return rc;
55506   }
55507
55508   /* Balance the tree. If the entry deleted was located on a leaf page,
55509   ** then the cursor still points to that page. In this case the first
55510   ** call to balance() repairs the tree, and the if(...) condition is
55511   ** never true.
55512   **
55513   ** Otherwise, if the entry deleted was on an internal node page, then
55514   ** pCur is pointing to the leaf page from which a cell was removed to
55515   ** replace the cell deleted from the internal node. This is slightly
55516   ** tricky as the leaf node may be underfull, and the internal node may
55517   ** be either under or overfull. In this case run the balancing algorithm
55518   ** on the leaf node first. If the balance proceeds far enough up the
55519   ** tree that we can be sure that any problem in the internal node has
55520   ** been corrected, so be it. Otherwise, after balancing the leaf node,
55521   ** walk the cursor up the tree to the internal node and balance it as 
55522   ** well.  */
55523   rc = balance(pCur);
55524   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
55525     while( pCur->iPage>iCellDepth ){
55526       releasePage(pCur->apPage[pCur->iPage--]);
55527     }
55528     rc = balance(pCur);
55529   }
55530
55531   if( rc==SQLITE_OK ){
55532     moveToRoot(pCur);
55533   }
55534   return rc;
55535 }
55536
55537 /*
55538 ** Create a new BTree table.  Write into *piTable the page
55539 ** number for the root page of the new table.
55540 **
55541 ** The type of type is determined by the flags parameter.  Only the
55542 ** following values of flags are currently in use.  Other values for
55543 ** flags might not work:
55544 **
55545 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
55546 **     BTREE_ZERODATA                  Used for SQL indices
55547 */
55548 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
55549   BtShared *pBt = p->pBt;
55550   MemPage *pRoot;
55551   Pgno pgnoRoot;
55552   int rc;
55553   int ptfFlags;          /* Page-type flage for the root page of new table */
55554
55555   assert( sqlite3BtreeHoldsMutex(p) );
55556   assert( pBt->inTransaction==TRANS_WRITE );
55557   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
55558
55559 #ifdef SQLITE_OMIT_AUTOVACUUM
55560   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
55561   if( rc ){
55562     return rc;
55563   }
55564 #else
55565   if( pBt->autoVacuum ){
55566     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
55567     MemPage *pPageMove; /* The page to move to. */
55568
55569     /* Creating a new table may probably require moving an existing database
55570     ** to make room for the new tables root page. In case this page turns
55571     ** out to be an overflow page, delete all overflow page-map caches
55572     ** held by open cursors.
55573     */
55574     invalidateAllOverflowCache(pBt);
55575
55576     /* Read the value of meta[3] from the database to determine where the
55577     ** root page of the new table should go. meta[3] is the largest root-page
55578     ** created so far, so the new root-page is (meta[3]+1).
55579     */
55580     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
55581     pgnoRoot++;
55582
55583     /* The new root-page may not be allocated on a pointer-map page, or the
55584     ** PENDING_BYTE page.
55585     */
55586     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
55587         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
55588       pgnoRoot++;
55589     }
55590     assert( pgnoRoot>=3 );
55591
55592     /* Allocate a page. The page that currently resides at pgnoRoot will
55593     ** be moved to the allocated page (unless the allocated page happens
55594     ** to reside at pgnoRoot).
55595     */
55596     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
55597     if( rc!=SQLITE_OK ){
55598       return rc;
55599     }
55600
55601     if( pgnoMove!=pgnoRoot ){
55602       /* pgnoRoot is the page that will be used for the root-page of
55603       ** the new table (assuming an error did not occur). But we were
55604       ** allocated pgnoMove. If required (i.e. if it was not allocated
55605       ** by extending the file), the current page at position pgnoMove
55606       ** is already journaled.
55607       */
55608       u8 eType = 0;
55609       Pgno iPtrPage = 0;
55610
55611       releasePage(pPageMove);
55612
55613       /* Move the page currently at pgnoRoot to pgnoMove. */
55614       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
55615       if( rc!=SQLITE_OK ){
55616         return rc;
55617       }
55618       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
55619       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
55620         rc = SQLITE_CORRUPT_BKPT;
55621       }
55622       if( rc!=SQLITE_OK ){
55623         releasePage(pRoot);
55624         return rc;
55625       }
55626       assert( eType!=PTRMAP_ROOTPAGE );
55627       assert( eType!=PTRMAP_FREEPAGE );
55628       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
55629       releasePage(pRoot);
55630
55631       /* Obtain the page at pgnoRoot */
55632       if( rc!=SQLITE_OK ){
55633         return rc;
55634       }
55635       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
55636       if( rc!=SQLITE_OK ){
55637         return rc;
55638       }
55639       rc = sqlite3PagerWrite(pRoot->pDbPage);
55640       if( rc!=SQLITE_OK ){
55641         releasePage(pRoot);
55642         return rc;
55643       }
55644     }else{
55645       pRoot = pPageMove;
55646     } 
55647
55648     /* Update the pointer-map and meta-data with the new root-page number. */
55649     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
55650     if( rc ){
55651       releasePage(pRoot);
55652       return rc;
55653     }
55654
55655     /* When the new root page was allocated, page 1 was made writable in
55656     ** order either to increase the database filesize, or to decrement the
55657     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
55658     */
55659     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
55660     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
55661     if( NEVER(rc) ){
55662       releasePage(pRoot);
55663       return rc;
55664     }
55665
55666   }else{
55667     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
55668     if( rc ) return rc;
55669   }
55670 #endif
55671   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
55672   if( createTabFlags & BTREE_INTKEY ){
55673     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
55674   }else{
55675     ptfFlags = PTF_ZERODATA | PTF_LEAF;
55676   }
55677   zeroPage(pRoot, ptfFlags);
55678   sqlite3PagerUnref(pRoot->pDbPage);
55679   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
55680   *piTable = (int)pgnoRoot;
55681   return SQLITE_OK;
55682 }
55683 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
55684   int rc;
55685   sqlite3BtreeEnter(p);
55686   rc = btreeCreateTable(p, piTable, flags);
55687   sqlite3BtreeLeave(p);
55688   return rc;
55689 }
55690
55691 /*
55692 ** Erase the given database page and all its children.  Return
55693 ** the page to the freelist.
55694 */
55695 static int clearDatabasePage(
55696   BtShared *pBt,           /* The BTree that contains the table */
55697   Pgno pgno,               /* Page number to clear */
55698   int freePageFlag,        /* Deallocate page if true */
55699   int *pnChange            /* Add number of Cells freed to this counter */
55700 ){
55701   MemPage *pPage;
55702   int rc;
55703   unsigned char *pCell;
55704   int i;
55705
55706   assert( sqlite3_mutex_held(pBt->mutex) );
55707   if( pgno>btreePagecount(pBt) ){
55708     return SQLITE_CORRUPT_BKPT;
55709   }
55710
55711   rc = getAndInitPage(pBt, pgno, &pPage);
55712   if( rc ) return rc;
55713   for(i=0; i<pPage->nCell; i++){
55714     pCell = findCell(pPage, i);
55715     if( !pPage->leaf ){
55716       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
55717       if( rc ) goto cleardatabasepage_out;
55718     }
55719     rc = clearCell(pPage, pCell);
55720     if( rc ) goto cleardatabasepage_out;
55721   }
55722   if( !pPage->leaf ){
55723     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
55724     if( rc ) goto cleardatabasepage_out;
55725   }else if( pnChange ){
55726     assert( pPage->intKey );
55727     *pnChange += pPage->nCell;
55728   }
55729   if( freePageFlag ){
55730     freePage(pPage, &rc);
55731   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
55732     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
55733   }
55734
55735 cleardatabasepage_out:
55736   releasePage(pPage);
55737   return rc;
55738 }
55739
55740 /*
55741 ** Delete all information from a single table in the database.  iTable is
55742 ** the page number of the root of the table.  After this routine returns,
55743 ** the root page is empty, but still exists.
55744 **
55745 ** This routine will fail with SQLITE_LOCKED if there are any open
55746 ** read cursors on the table.  Open write cursors are moved to the
55747 ** root of the table.
55748 **
55749 ** If pnChange is not NULL, then table iTable must be an intkey table. The
55750 ** integer value pointed to by pnChange is incremented by the number of
55751 ** entries in the table.
55752 */
55753 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
55754   int rc;
55755   BtShared *pBt = p->pBt;
55756   sqlite3BtreeEnter(p);
55757   assert( p->inTrans==TRANS_WRITE );
55758
55759   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
55760
55761   if( SQLITE_OK==rc ){
55762     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
55763     ** is the root of a table b-tree - if it is not, the following call is
55764     ** a no-op).  */
55765     invalidateIncrblobCursors(p, 0, 1);
55766     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
55767   }
55768   sqlite3BtreeLeave(p);
55769   return rc;
55770 }
55771
55772 /*
55773 ** Erase all information in a table and add the root of the table to
55774 ** the freelist.  Except, the root of the principle table (the one on
55775 ** page 1) is never added to the freelist.
55776 **
55777 ** This routine will fail with SQLITE_LOCKED if there are any open
55778 ** cursors on the table.
55779 **
55780 ** If AUTOVACUUM is enabled and the page at iTable is not the last
55781 ** root page in the database file, then the last root page 
55782 ** in the database file is moved into the slot formerly occupied by
55783 ** iTable and that last slot formerly occupied by the last root page
55784 ** is added to the freelist instead of iTable.  In this say, all
55785 ** root pages are kept at the beginning of the database file, which
55786 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
55787 ** page number that used to be the last root page in the file before
55788 ** the move.  If no page gets moved, *piMoved is set to 0.
55789 ** The last root page is recorded in meta[3] and the value of
55790 ** meta[3] is updated by this procedure.
55791 */
55792 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
55793   int rc;
55794   MemPage *pPage = 0;
55795   BtShared *pBt = p->pBt;
55796
55797   assert( sqlite3BtreeHoldsMutex(p) );
55798   assert( p->inTrans==TRANS_WRITE );
55799
55800   /* It is illegal to drop a table if any cursors are open on the
55801   ** database. This is because in auto-vacuum mode the backend may
55802   ** need to move another root-page to fill a gap left by the deleted
55803   ** root page. If an open cursor was using this page a problem would 
55804   ** occur.
55805   **
55806   ** This error is caught long before control reaches this point.
55807   */
55808   if( NEVER(pBt->pCursor) ){
55809     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
55810     return SQLITE_LOCKED_SHAREDCACHE;
55811   }
55812
55813   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
55814   if( rc ) return rc;
55815   rc = sqlite3BtreeClearTable(p, iTable, 0);
55816   if( rc ){
55817     releasePage(pPage);
55818     return rc;
55819   }
55820
55821   *piMoved = 0;
55822
55823   if( iTable>1 ){
55824 #ifdef SQLITE_OMIT_AUTOVACUUM
55825     freePage(pPage, &rc);
55826     releasePage(pPage);
55827 #else
55828     if( pBt->autoVacuum ){
55829       Pgno maxRootPgno;
55830       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
55831
55832       if( iTable==maxRootPgno ){
55833         /* If the table being dropped is the table with the largest root-page
55834         ** number in the database, put the root page on the free list. 
55835         */
55836         freePage(pPage, &rc);
55837         releasePage(pPage);
55838         if( rc!=SQLITE_OK ){
55839           return rc;
55840         }
55841       }else{
55842         /* The table being dropped does not have the largest root-page
55843         ** number in the database. So move the page that does into the 
55844         ** gap left by the deleted root-page.
55845         */
55846         MemPage *pMove;
55847         releasePage(pPage);
55848         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
55849         if( rc!=SQLITE_OK ){
55850           return rc;
55851         }
55852         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
55853         releasePage(pMove);
55854         if( rc!=SQLITE_OK ){
55855           return rc;
55856         }
55857         pMove = 0;
55858         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
55859         freePage(pMove, &rc);
55860         releasePage(pMove);
55861         if( rc!=SQLITE_OK ){
55862           return rc;
55863         }
55864         *piMoved = maxRootPgno;
55865       }
55866
55867       /* Set the new 'max-root-page' value in the database header. This
55868       ** is the old value less one, less one more if that happens to
55869       ** be a root-page number, less one again if that is the
55870       ** PENDING_BYTE_PAGE.
55871       */
55872       maxRootPgno--;
55873       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
55874              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
55875         maxRootPgno--;
55876       }
55877       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
55878
55879       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
55880     }else{
55881       freePage(pPage, &rc);
55882       releasePage(pPage);
55883     }
55884 #endif
55885   }else{
55886     /* If sqlite3BtreeDropTable was called on page 1.
55887     ** This really never should happen except in a corrupt
55888     ** database. 
55889     */
55890     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
55891     releasePage(pPage);
55892   }
55893   return rc;  
55894 }
55895 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
55896   int rc;
55897   sqlite3BtreeEnter(p);
55898   rc = btreeDropTable(p, iTable, piMoved);
55899   sqlite3BtreeLeave(p);
55900   return rc;
55901 }
55902
55903
55904 /*
55905 ** This function may only be called if the b-tree connection already
55906 ** has a read or write transaction open on the database.
55907 **
55908 ** Read the meta-information out of a database file.  Meta[0]
55909 ** is the number of free pages currently in the database.  Meta[1]
55910 ** through meta[15] are available for use by higher layers.  Meta[0]
55911 ** is read-only, the others are read/write.
55912 ** 
55913 ** The schema layer numbers meta values differently.  At the schema
55914 ** layer (and the SetCookie and ReadCookie opcodes) the number of
55915 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
55916 */
55917 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
55918   BtShared *pBt = p->pBt;
55919
55920   sqlite3BtreeEnter(p);
55921   assert( p->inTrans>TRANS_NONE );
55922   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
55923   assert( pBt->pPage1 );
55924   assert( idx>=0 && idx<=15 );
55925
55926   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
55927
55928   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
55929   ** database, mark the database as read-only.  */
55930 #ifdef SQLITE_OMIT_AUTOVACUUM
55931   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
55932     pBt->btsFlags |= BTS_READ_ONLY;
55933   }
55934 #endif
55935
55936   sqlite3BtreeLeave(p);
55937 }
55938
55939 /*
55940 ** Write meta-information back into the database.  Meta[0] is
55941 ** read-only and may not be written.
55942 */
55943 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
55944   BtShared *pBt = p->pBt;
55945   unsigned char *pP1;
55946   int rc;
55947   assert( idx>=1 && idx<=15 );
55948   sqlite3BtreeEnter(p);
55949   assert( p->inTrans==TRANS_WRITE );
55950   assert( pBt->pPage1!=0 );
55951   pP1 = pBt->pPage1->aData;
55952   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55953   if( rc==SQLITE_OK ){
55954     put4byte(&pP1[36 + idx*4], iMeta);
55955 #ifndef SQLITE_OMIT_AUTOVACUUM
55956     if( idx==BTREE_INCR_VACUUM ){
55957       assert( pBt->autoVacuum || iMeta==0 );
55958       assert( iMeta==0 || iMeta==1 );
55959       pBt->incrVacuum = (u8)iMeta;
55960     }
55961 #endif
55962   }
55963   sqlite3BtreeLeave(p);
55964   return rc;
55965 }
55966
55967 #ifndef SQLITE_OMIT_BTREECOUNT
55968 /*
55969 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
55970 ** number of entries in the b-tree and write the result to *pnEntry.
55971 **
55972 ** SQLITE_OK is returned if the operation is successfully executed. 
55973 ** Otherwise, if an error is encountered (i.e. an IO error or database
55974 ** corruption) an SQLite error code is returned.
55975 */
55976 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
55977   i64 nEntry = 0;                      /* Value to return in *pnEntry */
55978   int rc;                              /* Return code */
55979
55980   if( pCur->pgnoRoot==0 ){
55981     *pnEntry = 0;
55982     return SQLITE_OK;
55983   }
55984   rc = moveToRoot(pCur);
55985
55986   /* Unless an error occurs, the following loop runs one iteration for each
55987   ** page in the B-Tree structure (not including overflow pages). 
55988   */
55989   while( rc==SQLITE_OK ){
55990     int iIdx;                          /* Index of child node in parent */
55991     MemPage *pPage;                    /* Current page of the b-tree */
55992
55993     /* If this is a leaf page or the tree is not an int-key tree, then 
55994     ** this page contains countable entries. Increment the entry counter
55995     ** accordingly.
55996     */
55997     pPage = pCur->apPage[pCur->iPage];
55998     if( pPage->leaf || !pPage->intKey ){
55999       nEntry += pPage->nCell;
56000     }
56001
56002     /* pPage is a leaf node. This loop navigates the cursor so that it 
56003     ** points to the first interior cell that it points to the parent of
56004     ** the next page in the tree that has not yet been visited. The
56005     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
56006     ** of the page, or to the number of cells in the page if the next page
56007     ** to visit is the right-child of its parent.
56008     **
56009     ** If all pages in the tree have been visited, return SQLITE_OK to the
56010     ** caller.
56011     */
56012     if( pPage->leaf ){
56013       do {
56014         if( pCur->iPage==0 ){
56015           /* All pages of the b-tree have been visited. Return successfully. */
56016           *pnEntry = nEntry;
56017           return SQLITE_OK;
56018         }
56019         moveToParent(pCur);
56020       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
56021
56022       pCur->aiIdx[pCur->iPage]++;
56023       pPage = pCur->apPage[pCur->iPage];
56024     }
56025
56026     /* Descend to the child node of the cell that the cursor currently 
56027     ** points at. This is the right-child if (iIdx==pPage->nCell).
56028     */
56029     iIdx = pCur->aiIdx[pCur->iPage];
56030     if( iIdx==pPage->nCell ){
56031       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
56032     }else{
56033       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
56034     }
56035   }
56036
56037   /* An error has occurred. Return an error code. */
56038   return rc;
56039 }
56040 #endif
56041
56042 /*
56043 ** Return the pager associated with a BTree.  This routine is used for
56044 ** testing and debugging only.
56045 */
56046 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
56047   return p->pBt->pPager;
56048 }
56049
56050 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
56051 /*
56052 ** Append a message to the error message string.
56053 */
56054 static void checkAppendMsg(
56055   IntegrityCk *pCheck,
56056   char *zMsg1,
56057   const char *zFormat,
56058   ...
56059 ){
56060   va_list ap;
56061   if( !pCheck->mxErr ) return;
56062   pCheck->mxErr--;
56063   pCheck->nErr++;
56064   va_start(ap, zFormat);
56065   if( pCheck->errMsg.nChar ){
56066     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
56067   }
56068   if( zMsg1 ){
56069     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
56070   }
56071   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
56072   va_end(ap);
56073   if( pCheck->errMsg.mallocFailed ){
56074     pCheck->mallocFailed = 1;
56075   }
56076 }
56077 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56078
56079 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
56080
56081 /*
56082 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
56083 ** corresponds to page iPg is already set.
56084 */
56085 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
56086   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
56087   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
56088 }
56089
56090 /*
56091 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
56092 */
56093 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
56094   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
56095   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
56096 }
56097
56098
56099 /*
56100 ** Add 1 to the reference count for page iPage.  If this is the second
56101 ** reference to the page, add an error message to pCheck->zErrMsg.
56102 ** Return 1 if there are 2 ore more references to the page and 0 if
56103 ** if this is the first reference to the page.
56104 **
56105 ** Also check that the page number is in bounds.
56106 */
56107 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
56108   if( iPage==0 ) return 1;
56109   if( iPage>pCheck->nPage ){
56110     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
56111     return 1;
56112   }
56113   if( getPageReferenced(pCheck, iPage) ){
56114     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
56115     return 1;
56116   }
56117   setPageReferenced(pCheck, iPage);
56118   return 0;
56119 }
56120
56121 #ifndef SQLITE_OMIT_AUTOVACUUM
56122 /*
56123 ** Check that the entry in the pointer-map for page iChild maps to 
56124 ** page iParent, pointer type ptrType. If not, append an error message
56125 ** to pCheck.
56126 */
56127 static void checkPtrmap(
56128   IntegrityCk *pCheck,   /* Integrity check context */
56129   Pgno iChild,           /* Child page number */
56130   u8 eType,              /* Expected pointer map type */
56131   Pgno iParent,          /* Expected pointer map parent page number */
56132   char *zContext         /* Context description (used for error msg) */
56133 ){
56134   int rc;
56135   u8 ePtrmapType;
56136   Pgno iPtrmapParent;
56137
56138   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
56139   if( rc!=SQLITE_OK ){
56140     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
56141     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
56142     return;
56143   }
56144
56145   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
56146     checkAppendMsg(pCheck, zContext, 
56147       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
56148       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
56149   }
56150 }
56151 #endif
56152
56153 /*
56154 ** Check the integrity of the freelist or of an overflow page list.
56155 ** Verify that the number of pages on the list is N.
56156 */
56157 static void checkList(
56158   IntegrityCk *pCheck,  /* Integrity checking context */
56159   int isFreeList,       /* True for a freelist.  False for overflow page list */
56160   int iPage,            /* Page number for first page in the list */
56161   int N,                /* Expected number of pages in the list */
56162   char *zContext        /* Context for error messages */
56163 ){
56164   int i;
56165   int expected = N;
56166   int iFirst = iPage;
56167   while( N-- > 0 && pCheck->mxErr ){
56168     DbPage *pOvflPage;
56169     unsigned char *pOvflData;
56170     if( iPage<1 ){
56171       checkAppendMsg(pCheck, zContext,
56172          "%d of %d pages missing from overflow list starting at %d",
56173           N+1, expected, iFirst);
56174       break;
56175     }
56176     if( checkRef(pCheck, iPage, zContext) ) break;
56177     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
56178       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
56179       break;
56180     }
56181     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
56182     if( isFreeList ){
56183       int n = get4byte(&pOvflData[4]);
56184 #ifndef SQLITE_OMIT_AUTOVACUUM
56185       if( pCheck->pBt->autoVacuum ){
56186         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
56187       }
56188 #endif
56189       if( n>(int)pCheck->pBt->usableSize/4-2 ){
56190         checkAppendMsg(pCheck, zContext,
56191            "freelist leaf count too big on page %d", iPage);
56192         N--;
56193       }else{
56194         for(i=0; i<n; i++){
56195           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
56196 #ifndef SQLITE_OMIT_AUTOVACUUM
56197           if( pCheck->pBt->autoVacuum ){
56198             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
56199           }
56200 #endif
56201           checkRef(pCheck, iFreePage, zContext);
56202         }
56203         N -= n;
56204       }
56205     }
56206 #ifndef SQLITE_OMIT_AUTOVACUUM
56207     else{
56208       /* If this database supports auto-vacuum and iPage is not the last
56209       ** page in this overflow list, check that the pointer-map entry for
56210       ** the following page matches iPage.
56211       */
56212       if( pCheck->pBt->autoVacuum && N>0 ){
56213         i = get4byte(pOvflData);
56214         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
56215       }
56216     }
56217 #endif
56218     iPage = get4byte(pOvflData);
56219     sqlite3PagerUnref(pOvflPage);
56220   }
56221 }
56222 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56223
56224 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
56225 /*
56226 ** Do various sanity checks on a single page of a tree.  Return
56227 ** the tree depth.  Root pages return 0.  Parents of root pages
56228 ** return 1, and so forth.
56229 ** 
56230 ** These checks are done:
56231 **
56232 **      1.  Make sure that cells and freeblocks do not overlap
56233 **          but combine to completely cover the page.
56234 **  NO  2.  Make sure cell keys are in order.
56235 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
56236 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
56237 **      5.  Check the integrity of overflow pages.
56238 **      6.  Recursively call checkTreePage on all children.
56239 **      7.  Verify that the depth of all children is the same.
56240 **      8.  Make sure this page is at least 33% full or else it is
56241 **          the root of the tree.
56242 */
56243 static int checkTreePage(
56244   IntegrityCk *pCheck,  /* Context for the sanity check */
56245   int iPage,            /* Page number of the page to check */
56246   char *zParentContext, /* Parent context */
56247   i64 *pnParentMinKey, 
56248   i64 *pnParentMaxKey
56249 ){
56250   MemPage *pPage;
56251   int i, rc, depth, d2, pgno, cnt;
56252   int hdr, cellStart;
56253   int nCell;
56254   u8 *data;
56255   BtShared *pBt;
56256   int usableSize;
56257   char zContext[100];
56258   char *hit = 0;
56259   i64 nMinKey = 0;
56260   i64 nMaxKey = 0;
56261
56262   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
56263
56264   /* Check that the page exists
56265   */
56266   pBt = pCheck->pBt;
56267   usableSize = pBt->usableSize;
56268   if( iPage==0 ) return 0;
56269   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
56270   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
56271     checkAppendMsg(pCheck, zContext,
56272        "unable to get the page. error code=%d", rc);
56273     return 0;
56274   }
56275
56276   /* Clear MemPage.isInit to make sure the corruption detection code in
56277   ** btreeInitPage() is executed.  */
56278   pPage->isInit = 0;
56279   if( (rc = btreeInitPage(pPage))!=0 ){
56280     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
56281     checkAppendMsg(pCheck, zContext, 
56282                    "btreeInitPage() returns error code %d", rc);
56283     releasePage(pPage);
56284     return 0;
56285   }
56286
56287   /* Check out all the cells.
56288   */
56289   depth = 0;
56290   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
56291     u8 *pCell;
56292     u32 sz;
56293     CellInfo info;
56294
56295     /* Check payload overflow pages
56296     */
56297     sqlite3_snprintf(sizeof(zContext), zContext,
56298              "On tree page %d cell %d: ", iPage, i);
56299     pCell = findCell(pPage,i);
56300     btreeParseCellPtr(pPage, pCell, &info);
56301     sz = info.nData;
56302     if( !pPage->intKey ) sz += (int)info.nKey;
56303     /* For intKey pages, check that the keys are in order.
56304     */
56305     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
56306     else{
56307       if( info.nKey <= nMaxKey ){
56308         checkAppendMsg(pCheck, zContext, 
56309             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
56310       }
56311       nMaxKey = info.nKey;
56312     }
56313     assert( sz==info.nPayload );
56314     if( (sz>info.nLocal) 
56315      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
56316     ){
56317       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
56318       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
56319 #ifndef SQLITE_OMIT_AUTOVACUUM
56320       if( pBt->autoVacuum ){
56321         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
56322       }
56323 #endif
56324       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
56325     }
56326
56327     /* Check sanity of left child page.
56328     */
56329     if( !pPage->leaf ){
56330       pgno = get4byte(pCell);
56331 #ifndef SQLITE_OMIT_AUTOVACUUM
56332       if( pBt->autoVacuum ){
56333         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
56334       }
56335 #endif
56336       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
56337       if( i>0 && d2!=depth ){
56338         checkAppendMsg(pCheck, zContext, "Child page depth differs");
56339       }
56340       depth = d2;
56341     }
56342   }
56343
56344   if( !pPage->leaf ){
56345     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
56346     sqlite3_snprintf(sizeof(zContext), zContext, 
56347                      "On page %d at right child: ", iPage);
56348 #ifndef SQLITE_OMIT_AUTOVACUUM
56349     if( pBt->autoVacuum ){
56350       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
56351     }
56352 #endif
56353     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
56354   }
56355  
56356   /* For intKey leaf pages, check that the min/max keys are in order
56357   ** with any left/parent/right pages.
56358   */
56359   if( pPage->leaf && pPage->intKey ){
56360     /* if we are a left child page */
56361     if( pnParentMinKey ){
56362       /* if we are the left most child page */
56363       if( !pnParentMaxKey ){
56364         if( nMaxKey > *pnParentMinKey ){
56365           checkAppendMsg(pCheck, zContext, 
56366               "Rowid %lld out of order (max larger than parent min of %lld)",
56367               nMaxKey, *pnParentMinKey);
56368         }
56369       }else{
56370         if( nMinKey <= *pnParentMinKey ){
56371           checkAppendMsg(pCheck, zContext, 
56372               "Rowid %lld out of order (min less than parent min of %lld)",
56373               nMinKey, *pnParentMinKey);
56374         }
56375         if( nMaxKey > *pnParentMaxKey ){
56376           checkAppendMsg(pCheck, zContext, 
56377               "Rowid %lld out of order (max larger than parent max of %lld)",
56378               nMaxKey, *pnParentMaxKey);
56379         }
56380         *pnParentMinKey = nMaxKey;
56381       }
56382     /* else if we're a right child page */
56383     } else if( pnParentMaxKey ){
56384       if( nMinKey <= *pnParentMaxKey ){
56385         checkAppendMsg(pCheck, zContext, 
56386             "Rowid %lld out of order (min less than parent max of %lld)",
56387             nMinKey, *pnParentMaxKey);
56388       }
56389     }
56390   }
56391
56392   /* Check for complete coverage of the page
56393   */
56394   data = pPage->aData;
56395   hdr = pPage->hdrOffset;
56396   hit = sqlite3PageMalloc( pBt->pageSize );
56397   if( hit==0 ){
56398     pCheck->mallocFailed = 1;
56399   }else{
56400     int contentOffset = get2byteNotZero(&data[hdr+5]);
56401     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
56402     memset(hit+contentOffset, 0, usableSize-contentOffset);
56403     memset(hit, 1, contentOffset);
56404     nCell = get2byte(&data[hdr+3]);
56405     cellStart = hdr + 12 - 4*pPage->leaf;
56406     for(i=0; i<nCell; i++){
56407       int pc = get2byte(&data[cellStart+i*2]);
56408       u32 size = 65536;
56409       int j;
56410       if( pc<=usableSize-4 ){
56411         size = cellSizePtr(pPage, &data[pc]);
56412       }
56413       if( (int)(pc+size-1)>=usableSize ){
56414         checkAppendMsg(pCheck, 0, 
56415             "Corruption detected in cell %d on page %d",i,iPage);
56416       }else{
56417         for(j=pc+size-1; j>=pc; j--) hit[j]++;
56418       }
56419     }
56420     i = get2byte(&data[hdr+1]);
56421     while( i>0 ){
56422       int size, j;
56423       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
56424       size = get2byte(&data[i+2]);
56425       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
56426       for(j=i+size-1; j>=i; j--) hit[j]++;
56427       j = get2byte(&data[i]);
56428       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
56429       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
56430       i = j;
56431     }
56432     for(i=cnt=0; i<usableSize; i++){
56433       if( hit[i]==0 ){
56434         cnt++;
56435       }else if( hit[i]>1 ){
56436         checkAppendMsg(pCheck, 0,
56437           "Multiple uses for byte %d of page %d", i, iPage);
56438         break;
56439       }
56440     }
56441     if( cnt!=data[hdr+7] ){
56442       checkAppendMsg(pCheck, 0, 
56443           "Fragmentation of %d bytes reported as %d on page %d",
56444           cnt, data[hdr+7], iPage);
56445     }
56446   }
56447   sqlite3PageFree(hit);
56448   releasePage(pPage);
56449   return depth+1;
56450 }
56451 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56452
56453 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
56454 /*
56455 ** This routine does a complete check of the given BTree file.  aRoot[] is
56456 ** an array of pages numbers were each page number is the root page of
56457 ** a table.  nRoot is the number of entries in aRoot.
56458 **
56459 ** A read-only or read-write transaction must be opened before calling
56460 ** this function.
56461 **
56462 ** Write the number of error seen in *pnErr.  Except for some memory
56463 ** allocation errors,  an error message held in memory obtained from
56464 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
56465 ** returned.  If a memory allocation error occurs, NULL is returned.
56466 */
56467 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
56468   Btree *p,     /* The btree to be checked */
56469   int *aRoot,   /* An array of root pages numbers for individual trees */
56470   int nRoot,    /* Number of entries in aRoot[] */
56471   int mxErr,    /* Stop reporting errors after this many */
56472   int *pnErr    /* Write number of errors seen to this variable */
56473 ){
56474   Pgno i;
56475   int nRef;
56476   IntegrityCk sCheck;
56477   BtShared *pBt = p->pBt;
56478   char zErr[100];
56479
56480   sqlite3BtreeEnter(p);
56481   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
56482   nRef = sqlite3PagerRefcount(pBt->pPager);
56483   sCheck.pBt = pBt;
56484   sCheck.pPager = pBt->pPager;
56485   sCheck.nPage = btreePagecount(sCheck.pBt);
56486   sCheck.mxErr = mxErr;
56487   sCheck.nErr = 0;
56488   sCheck.mallocFailed = 0;
56489   *pnErr = 0;
56490   if( sCheck.nPage==0 ){
56491     sqlite3BtreeLeave(p);
56492     return 0;
56493   }
56494
56495   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
56496   if( !sCheck.aPgRef ){
56497     *pnErr = 1;
56498     sqlite3BtreeLeave(p);
56499     return 0;
56500   }
56501   i = PENDING_BYTE_PAGE(pBt);
56502   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
56503   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
56504   sCheck.errMsg.useMalloc = 2;
56505
56506   /* Check the integrity of the freelist
56507   */
56508   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
56509             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
56510
56511   /* Check all the tables.
56512   */
56513   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
56514     if( aRoot[i]==0 ) continue;
56515 #ifndef SQLITE_OMIT_AUTOVACUUM
56516     if( pBt->autoVacuum && aRoot[i]>1 ){
56517       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
56518     }
56519 #endif
56520     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
56521   }
56522
56523   /* Make sure every page in the file is referenced
56524   */
56525   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
56526 #ifdef SQLITE_OMIT_AUTOVACUUM
56527     if( getPageReferenced(&sCheck, i)==0 ){
56528       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
56529     }
56530 #else
56531     /* If the database supports auto-vacuum, make sure no tables contain
56532     ** references to pointer-map pages.
56533     */
56534     if( getPageReferenced(&sCheck, i)==0 && 
56535        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
56536       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
56537     }
56538     if( getPageReferenced(&sCheck, i)!=0 && 
56539        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
56540       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
56541     }
56542 #endif
56543   }
56544
56545   /* Make sure this analysis did not leave any unref() pages.
56546   ** This is an internal consistency check; an integrity check
56547   ** of the integrity check.
56548   */
56549   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
56550     checkAppendMsg(&sCheck, 0, 
56551       "Outstanding page count goes from %d to %d during this analysis",
56552       nRef, sqlite3PagerRefcount(pBt->pPager)
56553     );
56554   }
56555
56556   /* Clean  up and report errors.
56557   */
56558   sqlite3BtreeLeave(p);
56559   sqlite3_free(sCheck.aPgRef);
56560   if( sCheck.mallocFailed ){
56561     sqlite3StrAccumReset(&sCheck.errMsg);
56562     *pnErr = sCheck.nErr+1;
56563     return 0;
56564   }
56565   *pnErr = sCheck.nErr;
56566   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
56567   return sqlite3StrAccumFinish(&sCheck.errMsg);
56568 }
56569 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56570
56571 /*
56572 ** Return the full pathname of the underlying database file.  Return
56573 ** an empty string if the database is in-memory or a TEMP database.
56574 **
56575 ** The pager filename is invariant as long as the pager is
56576 ** open so it is safe to access without the BtShared mutex.
56577 */
56578 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
56579   assert( p->pBt->pPager!=0 );
56580   return sqlite3PagerFilename(p->pBt->pPager, 1);
56581 }
56582
56583 /*
56584 ** Return the pathname of the journal file for this database. The return
56585 ** value of this routine is the same regardless of whether the journal file
56586 ** has been created or not.
56587 **
56588 ** The pager journal filename is invariant as long as the pager is
56589 ** open so it is safe to access without the BtShared mutex.
56590 */
56591 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
56592   assert( p->pBt->pPager!=0 );
56593   return sqlite3PagerJournalname(p->pBt->pPager);
56594 }
56595
56596 /*
56597 ** Return non-zero if a transaction is active.
56598 */
56599 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
56600   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
56601   return (p && (p->inTrans==TRANS_WRITE));
56602 }
56603
56604 #ifndef SQLITE_OMIT_WAL
56605 /*
56606 ** Run a checkpoint on the Btree passed as the first argument.
56607 **
56608 ** Return SQLITE_LOCKED if this or any other connection has an open 
56609 ** transaction on the shared-cache the argument Btree is connected to.
56610 **
56611 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
56612 */
56613 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
56614   int rc = SQLITE_OK;
56615   if( p ){
56616     BtShared *pBt = p->pBt;
56617     sqlite3BtreeEnter(p);
56618     if( pBt->inTransaction!=TRANS_NONE ){
56619       rc = SQLITE_LOCKED;
56620     }else{
56621       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
56622     }
56623     sqlite3BtreeLeave(p);
56624   }
56625   return rc;
56626 }
56627 #endif
56628
56629 /*
56630 ** Return non-zero if a read (or write) transaction is active.
56631 */
56632 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
56633   assert( p );
56634   assert( sqlite3_mutex_held(p->db->mutex) );
56635   return p->inTrans!=TRANS_NONE;
56636 }
56637
56638 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
56639   assert( p );
56640   assert( sqlite3_mutex_held(p->db->mutex) );
56641   return p->nBackup!=0;
56642 }
56643
56644 /*
56645 ** This function returns a pointer to a blob of memory associated with
56646 ** a single shared-btree. The memory is used by client code for its own
56647 ** purposes (for example, to store a high-level schema associated with 
56648 ** the shared-btree). The btree layer manages reference counting issues.
56649 **
56650 ** The first time this is called on a shared-btree, nBytes bytes of memory
56651 ** are allocated, zeroed, and returned to the caller. For each subsequent 
56652 ** call the nBytes parameter is ignored and a pointer to the same blob
56653 ** of memory returned. 
56654 **
56655 ** If the nBytes parameter is 0 and the blob of memory has not yet been
56656 ** allocated, a null pointer is returned. If the blob has already been
56657 ** allocated, it is returned as normal.
56658 **
56659 ** Just before the shared-btree is closed, the function passed as the 
56660 ** xFree argument when the memory allocation was made is invoked on the 
56661 ** blob of allocated memory. The xFree function should not call sqlite3_free()
56662 ** on the memory, the btree layer does that.
56663 */
56664 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
56665   BtShared *pBt = p->pBt;
56666   sqlite3BtreeEnter(p);
56667   if( !pBt->pSchema && nBytes ){
56668     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
56669     pBt->xFreeSchema = xFree;
56670   }
56671   sqlite3BtreeLeave(p);
56672   return pBt->pSchema;
56673 }
56674
56675 /*
56676 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
56677 ** btree as the argument handle holds an exclusive lock on the 
56678 ** sqlite_master table. Otherwise SQLITE_OK.
56679 */
56680 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
56681   int rc;
56682   assert( sqlite3_mutex_held(p->db->mutex) );
56683   sqlite3BtreeEnter(p);
56684   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
56685   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
56686   sqlite3BtreeLeave(p);
56687   return rc;
56688 }
56689
56690
56691 #ifndef SQLITE_OMIT_SHARED_CACHE
56692 /*
56693 ** Obtain a lock on the table whose root page is iTab.  The
56694 ** lock is a write lock if isWritelock is true or a read lock
56695 ** if it is false.
56696 */
56697 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
56698   int rc = SQLITE_OK;
56699   assert( p->inTrans!=TRANS_NONE );
56700   if( p->sharable ){
56701     u8 lockType = READ_LOCK + isWriteLock;
56702     assert( READ_LOCK+1==WRITE_LOCK );
56703     assert( isWriteLock==0 || isWriteLock==1 );
56704
56705     sqlite3BtreeEnter(p);
56706     rc = querySharedCacheTableLock(p, iTab, lockType);
56707     if( rc==SQLITE_OK ){
56708       rc = setSharedCacheTableLock(p, iTab, lockType);
56709     }
56710     sqlite3BtreeLeave(p);
56711   }
56712   return rc;
56713 }
56714 #endif
56715
56716 #ifndef SQLITE_OMIT_INCRBLOB
56717 /*
56718 ** Argument pCsr must be a cursor opened for writing on an 
56719 ** INTKEY table currently pointing at a valid table entry. 
56720 ** This function modifies the data stored as part of that entry.
56721 **
56722 ** Only the data content may only be modified, it is not possible to 
56723 ** change the length of the data stored. If this function is called with
56724 ** parameters that attempt to write past the end of the existing data,
56725 ** no modifications are made and SQLITE_CORRUPT is returned.
56726 */
56727 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
56728   int rc;
56729   assert( cursorHoldsMutex(pCsr) );
56730   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
56731   assert( pCsr->isIncrblobHandle );
56732
56733   rc = restoreCursorPosition(pCsr);
56734   if( rc!=SQLITE_OK ){
56735     return rc;
56736   }
56737   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
56738   if( pCsr->eState!=CURSOR_VALID ){
56739     return SQLITE_ABORT;
56740   }
56741
56742   /* Check some assumptions: 
56743   **   (a) the cursor is open for writing,
56744   **   (b) there is a read/write transaction open,
56745   **   (c) the connection holds a write-lock on the table (if required),
56746   **   (d) there are no conflicting read-locks, and
56747   **   (e) the cursor points at a valid row of an intKey table.
56748   */
56749   if( !pCsr->wrFlag ){
56750     return SQLITE_READONLY;
56751   }
56752   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
56753               && pCsr->pBt->inTransaction==TRANS_WRITE );
56754   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
56755   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
56756   assert( pCsr->apPage[pCsr->iPage]->intKey );
56757
56758   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
56759 }
56760
56761 /* 
56762 ** Set a flag on this cursor to cache the locations of pages from the 
56763 ** overflow list for the current row. This is used by cursors opened
56764 ** for incremental blob IO only.
56765 **
56766 ** This function sets a flag only. The actual page location cache
56767 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
56768 ** accessPayload() (the worker function for sqlite3BtreeData() and
56769 ** sqlite3BtreePutData()).
56770 */
56771 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
56772   assert( cursorHoldsMutex(pCur) );
56773   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56774   invalidateOverflowCache(pCur);
56775   pCur->isIncrblobHandle = 1;
56776 }
56777 #endif
56778
56779 /*
56780 ** Set both the "read version" (single byte at byte offset 18) and 
56781 ** "write version" (single byte at byte offset 19) fields in the database
56782 ** header to iVersion.
56783 */
56784 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
56785   BtShared *pBt = pBtree->pBt;
56786   int rc;                         /* Return code */
56787  
56788   assert( iVersion==1 || iVersion==2 );
56789
56790   /* If setting the version fields to 1, do not automatically open the
56791   ** WAL connection, even if the version fields are currently set to 2.
56792   */
56793   pBt->btsFlags &= ~BTS_NO_WAL;
56794   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
56795
56796   rc = sqlite3BtreeBeginTrans(pBtree, 0);
56797   if( rc==SQLITE_OK ){
56798     u8 *aData = pBt->pPage1->aData;
56799     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
56800       rc = sqlite3BtreeBeginTrans(pBtree, 2);
56801       if( rc==SQLITE_OK ){
56802         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56803         if( rc==SQLITE_OK ){
56804           aData[18] = (u8)iVersion;
56805           aData[19] = (u8)iVersion;
56806         }
56807       }
56808     }
56809   }
56810
56811   pBt->btsFlags &= ~BTS_NO_WAL;
56812   return rc;
56813 }
56814
56815 /*
56816 ** set the mask of hint flags for cursor pCsr. Currently the only valid
56817 ** values are 0 and BTREE_BULKLOAD.
56818 */
56819 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
56820   assert( mask==BTREE_BULKLOAD || mask==0 );
56821   pCsr->hints = mask;
56822 }
56823
56824 /************** End of btree.c ***********************************************/
56825 /************** Begin file backup.c ******************************************/
56826 /*
56827 ** 2009 January 28
56828 **
56829 ** The author disclaims copyright to this source code.  In place of
56830 ** a legal notice, here is a blessing:
56831 **
56832 **    May you do good and not evil.
56833 **    May you find forgiveness for yourself and forgive others.
56834 **    May you share freely, never taking more than you give.
56835 **
56836 *************************************************************************
56837 ** This file contains the implementation of the sqlite3_backup_XXX() 
56838 ** API functions and the related features.
56839 */
56840
56841 /* Macro to find the minimum of two numeric values.
56842 */
56843 #ifndef MIN
56844 # define MIN(x,y) ((x)<(y)?(x):(y))
56845 #endif
56846
56847 /*
56848 ** Structure allocated for each backup operation.
56849 */
56850 struct sqlite3_backup {
56851   sqlite3* pDestDb;        /* Destination database handle */
56852   Btree *pDest;            /* Destination b-tree file */
56853   u32 iDestSchema;         /* Original schema cookie in destination */
56854   int bDestLocked;         /* True once a write-transaction is open on pDest */
56855
56856   Pgno iNext;              /* Page number of the next source page to copy */
56857   sqlite3* pSrcDb;         /* Source database handle */
56858   Btree *pSrc;             /* Source b-tree file */
56859
56860   int rc;                  /* Backup process error code */
56861
56862   /* These two variables are set by every call to backup_step(). They are
56863   ** read by calls to backup_remaining() and backup_pagecount().
56864   */
56865   Pgno nRemaining;         /* Number of pages left to copy */
56866   Pgno nPagecount;         /* Total number of pages to copy */
56867
56868   int isAttached;          /* True once backup has been registered with pager */
56869   sqlite3_backup *pNext;   /* Next backup associated with source pager */
56870 };
56871
56872 /*
56873 ** THREAD SAFETY NOTES:
56874 **
56875 **   Once it has been created using backup_init(), a single sqlite3_backup
56876 **   structure may be accessed via two groups of thread-safe entry points:
56877 **
56878 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
56879 **       backup_finish(). Both these functions obtain the source database
56880 **       handle mutex and the mutex associated with the source BtShared 
56881 **       structure, in that order.
56882 **
56883 **     * Via the BackupUpdate() and BackupRestart() functions, which are
56884 **       invoked by the pager layer to report various state changes in
56885 **       the page cache associated with the source database. The mutex
56886 **       associated with the source database BtShared structure will always 
56887 **       be held when either of these functions are invoked.
56888 **
56889 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
56890 **   backup_pagecount() are not thread-safe functions. If they are called
56891 **   while some other thread is calling backup_step() or backup_finish(),
56892 **   the values returned may be invalid. There is no way for a call to
56893 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
56894 **   or backup_pagecount().
56895 **
56896 **   Depending on the SQLite configuration, the database handles and/or
56897 **   the Btree objects may have their own mutexes that require locking.
56898 **   Non-sharable Btrees (in-memory databases for example), do not have
56899 **   associated mutexes.
56900 */
56901
56902 /*
56903 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
56904 ** in connection handle pDb. If such a database cannot be found, return
56905 ** a NULL pointer and write an error message to pErrorDb.
56906 **
56907 ** If the "temp" database is requested, it may need to be opened by this 
56908 ** function. If an error occurs while doing so, return 0 and write an 
56909 ** error message to pErrorDb.
56910 */
56911 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
56912   int i = sqlite3FindDbName(pDb, zDb);
56913
56914   if( i==1 ){
56915     Parse *pParse;
56916     int rc = 0;
56917     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
56918     if( pParse==0 ){
56919       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
56920       rc = SQLITE_NOMEM;
56921     }else{
56922       pParse->db = pDb;
56923       if( sqlite3OpenTempDatabase(pParse) ){
56924         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
56925         rc = SQLITE_ERROR;
56926       }
56927       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
56928       sqlite3StackFree(pErrorDb, pParse);
56929     }
56930     if( rc ){
56931       return 0;
56932     }
56933   }
56934
56935   if( i<0 ){
56936     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
56937     return 0;
56938   }
56939
56940   return pDb->aDb[i].pBt;
56941 }
56942
56943 /*
56944 ** Attempt to set the page size of the destination to match the page size
56945 ** of the source.
56946 */
56947 static int setDestPgsz(sqlite3_backup *p){
56948   int rc;
56949   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
56950   return rc;
56951 }
56952
56953 /*
56954 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
56955 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
56956 ** a pointer to the new sqlite3_backup object.
56957 **
56958 ** If an error occurs, NULL is returned and an error code and error message
56959 ** stored in database handle pDestDb.
56960 */
56961 SQLITE_API sqlite3_backup *sqlite3_backup_init(
56962   sqlite3* pDestDb,                     /* Database to write to */
56963   const char *zDestDb,                  /* Name of database within pDestDb */
56964   sqlite3* pSrcDb,                      /* Database connection to read from */
56965   const char *zSrcDb                    /* Name of database within pSrcDb */
56966 ){
56967   sqlite3_backup *p;                    /* Value to return */
56968
56969   /* Lock the source database handle. The destination database
56970   ** handle is not locked in this routine, but it is locked in
56971   ** sqlite3_backup_step(). The user is required to ensure that no
56972   ** other thread accesses the destination handle for the duration
56973   ** of the backup operation.  Any attempt to use the destination
56974   ** database connection while a backup is in progress may cause
56975   ** a malfunction or a deadlock.
56976   */
56977   sqlite3_mutex_enter(pSrcDb->mutex);
56978   sqlite3_mutex_enter(pDestDb->mutex);
56979
56980   if( pSrcDb==pDestDb ){
56981     sqlite3Error(
56982         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
56983     );
56984     p = 0;
56985   }else {
56986     /* Allocate space for a new sqlite3_backup object...
56987     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
56988     ** call to sqlite3_backup_init() and is destroyed by a call to
56989     ** sqlite3_backup_finish(). */
56990     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
56991     if( !p ){
56992       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
56993     }
56994   }
56995
56996   /* If the allocation succeeded, populate the new object. */
56997   if( p ){
56998     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
56999     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
57000     p->pDestDb = pDestDb;
57001     p->pSrcDb = pSrcDb;
57002     p->iNext = 1;
57003     p->isAttached = 0;
57004
57005     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
57006       /* One (or both) of the named databases did not exist or an OOM
57007       ** error was hit.  The error has already been written into the
57008       ** pDestDb handle.  All that is left to do here is free the
57009       ** sqlite3_backup structure.
57010       */
57011       sqlite3_free(p);
57012       p = 0;
57013     }
57014   }
57015   if( p ){
57016     p->pSrc->nBackup++;
57017   }
57018
57019   sqlite3_mutex_leave(pDestDb->mutex);
57020   sqlite3_mutex_leave(pSrcDb->mutex);
57021   return p;
57022 }
57023
57024 /*
57025 ** Argument rc is an SQLite error code. Return true if this error is 
57026 ** considered fatal if encountered during a backup operation. All errors
57027 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
57028 */
57029 static int isFatalError(int rc){
57030   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
57031 }
57032
57033 /*
57034 ** Parameter zSrcData points to a buffer containing the data for 
57035 ** page iSrcPg from the source database. Copy this data into the 
57036 ** destination database.
57037 */
57038 static int backupOnePage(
57039   sqlite3_backup *p,              /* Backup handle */
57040   Pgno iSrcPg,                    /* Source database page to backup */
57041   const u8 *zSrcData,             /* Source database page data */
57042   int bUpdate                     /* True for an update, false otherwise */
57043 ){
57044   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
57045   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
57046   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
57047   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
57048   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
57049 #ifdef SQLITE_HAS_CODEC
57050   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
57051   ** guaranteed that the shared-mutex is held by this thread, handle
57052   ** p->pSrc may not actually be the owner.  */
57053   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
57054   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
57055 #endif
57056   int rc = SQLITE_OK;
57057   i64 iOff;
57058
57059   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
57060   assert( p->bDestLocked );
57061   assert( !isFatalError(p->rc) );
57062   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
57063   assert( zSrcData );
57064
57065   /* Catch the case where the destination is an in-memory database and the
57066   ** page sizes of the source and destination differ. 
57067   */
57068   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
57069     rc = SQLITE_READONLY;
57070   }
57071
57072 #ifdef SQLITE_HAS_CODEC
57073   /* Backup is not possible if the page size of the destination is changing
57074   ** and a codec is in use.
57075   */
57076   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
57077     rc = SQLITE_READONLY;
57078   }
57079
57080   /* Backup is not possible if the number of bytes of reserve space differ
57081   ** between source and destination.  If there is a difference, try to
57082   ** fix the destination to agree with the source.  If that is not possible,
57083   ** then the backup cannot proceed.
57084   */
57085   if( nSrcReserve!=nDestReserve ){
57086     u32 newPgsz = nSrcPgsz;
57087     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
57088     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
57089   }
57090 #endif
57091
57092   /* This loop runs once for each destination page spanned by the source 
57093   ** page. For each iteration, variable iOff is set to the byte offset
57094   ** of the destination page.
57095   */
57096   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
57097     DbPage *pDestPg = 0;
57098     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
57099     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
57100     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
57101      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
57102     ){
57103       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
57104       u8 *zDestData = sqlite3PagerGetData(pDestPg);
57105       u8 *zOut = &zDestData[iOff%nDestPgsz];
57106
57107       /* Copy the data from the source page into the destination page.
57108       ** Then clear the Btree layer MemPage.isInit flag. Both this module
57109       ** and the pager code use this trick (clearing the first byte
57110       ** of the page 'extra' space to invalidate the Btree layers
57111       ** cached parse of the page). MemPage.isInit is marked 
57112       ** "MUST BE FIRST" for this purpose.
57113       */
57114       memcpy(zOut, zIn, nCopy);
57115       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
57116       if( iOff==0 && bUpdate==0 ){
57117         sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
57118       }
57119     }
57120     sqlite3PagerUnref(pDestPg);
57121   }
57122
57123   return rc;
57124 }
57125
57126 /*
57127 ** If pFile is currently larger than iSize bytes, then truncate it to
57128 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
57129 ** this function is a no-op.
57130 **
57131 ** Return SQLITE_OK if everything is successful, or an SQLite error 
57132 ** code if an error occurs.
57133 */
57134 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
57135   i64 iCurrent;
57136   int rc = sqlite3OsFileSize(pFile, &iCurrent);
57137   if( rc==SQLITE_OK && iCurrent>iSize ){
57138     rc = sqlite3OsTruncate(pFile, iSize);
57139   }
57140   return rc;
57141 }
57142
57143 /*
57144 ** Register this backup object with the associated source pager for
57145 ** callbacks when pages are changed or the cache invalidated.
57146 */
57147 static void attachBackupObject(sqlite3_backup *p){
57148   sqlite3_backup **pp;
57149   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
57150   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
57151   p->pNext = *pp;
57152   *pp = p;
57153   p->isAttached = 1;
57154 }
57155
57156 /*
57157 ** Copy nPage pages from the source b-tree to the destination.
57158 */
57159 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
57160   int rc;
57161   int destMode;       /* Destination journal mode */
57162   int pgszSrc = 0;    /* Source page size */
57163   int pgszDest = 0;   /* Destination page size */
57164
57165   sqlite3_mutex_enter(p->pSrcDb->mutex);
57166   sqlite3BtreeEnter(p->pSrc);
57167   if( p->pDestDb ){
57168     sqlite3_mutex_enter(p->pDestDb->mutex);
57169   }
57170
57171   rc = p->rc;
57172   if( !isFatalError(rc) ){
57173     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
57174     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
57175     int ii;                            /* Iterator variable */
57176     int nSrcPage = -1;                 /* Size of source db in pages */
57177     int bCloseTrans = 0;               /* True if src db requires unlocking */
57178
57179     /* If the source pager is currently in a write-transaction, return
57180     ** SQLITE_BUSY immediately.
57181     */
57182     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
57183       rc = SQLITE_BUSY;
57184     }else{
57185       rc = SQLITE_OK;
57186     }
57187
57188     /* Lock the destination database, if it is not locked already. */
57189     if( SQLITE_OK==rc && p->bDestLocked==0
57190      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
57191     ){
57192       p->bDestLocked = 1;
57193       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
57194     }
57195
57196     /* If there is no open read-transaction on the source database, open
57197     ** one now. If a transaction is opened here, then it will be closed
57198     ** before this function exits.
57199     */
57200     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
57201       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
57202       bCloseTrans = 1;
57203     }
57204
57205     /* Do not allow backup if the destination database is in WAL mode
57206     ** and the page sizes are different between source and destination */
57207     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
57208     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
57209     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
57210     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
57211       rc = SQLITE_READONLY;
57212     }
57213   
57214     /* Now that there is a read-lock on the source database, query the
57215     ** source pager for the number of pages in the database.
57216     */
57217     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
57218     assert( nSrcPage>=0 );
57219     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
57220       const Pgno iSrcPg = p->iNext;                 /* Source page number */
57221       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
57222         DbPage *pSrcPg;                             /* Source page object */
57223         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
57224         if( rc==SQLITE_OK ){
57225           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
57226           sqlite3PagerUnref(pSrcPg);
57227         }
57228       }
57229       p->iNext++;
57230     }
57231     if( rc==SQLITE_OK ){
57232       p->nPagecount = nSrcPage;
57233       p->nRemaining = nSrcPage+1-p->iNext;
57234       if( p->iNext>(Pgno)nSrcPage ){
57235         rc = SQLITE_DONE;
57236       }else if( !p->isAttached ){
57237         attachBackupObject(p);
57238       }
57239     }
57240   
57241     /* Update the schema version field in the destination database. This
57242     ** is to make sure that the schema-version really does change in
57243     ** the case where the source and destination databases have the
57244     ** same schema version.
57245     */
57246     if( rc==SQLITE_DONE ){
57247       if( nSrcPage==0 ){
57248         rc = sqlite3BtreeNewDb(p->pDest);
57249         nSrcPage = 1;
57250       }
57251       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
57252         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
57253       }
57254       if( rc==SQLITE_OK ){
57255         if( p->pDestDb ){
57256           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
57257         }
57258         if( destMode==PAGER_JOURNALMODE_WAL ){
57259           rc = sqlite3BtreeSetVersion(p->pDest, 2);
57260         }
57261       }
57262       if( rc==SQLITE_OK ){
57263         int nDestTruncate;
57264         /* Set nDestTruncate to the final number of pages in the destination
57265         ** database. The complication here is that the destination page
57266         ** size may be different to the source page size. 
57267         **
57268         ** If the source page size is smaller than the destination page size, 
57269         ** round up. In this case the call to sqlite3OsTruncate() below will
57270         ** fix the size of the file. However it is important to call
57271         ** sqlite3PagerTruncateImage() here so that any pages in the 
57272         ** destination file that lie beyond the nDestTruncate page mark are
57273         ** journalled by PagerCommitPhaseOne() before they are destroyed
57274         ** by the file truncation.
57275         */
57276         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
57277         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
57278         if( pgszSrc<pgszDest ){
57279           int ratio = pgszDest/pgszSrc;
57280           nDestTruncate = (nSrcPage+ratio-1)/ratio;
57281           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
57282             nDestTruncate--;
57283           }
57284         }else{
57285           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
57286         }
57287         assert( nDestTruncate>0 );
57288
57289         if( pgszSrc<pgszDest ){
57290           /* If the source page-size is smaller than the destination page-size,
57291           ** two extra things may need to happen:
57292           **
57293           **   * The destination may need to be truncated, and
57294           **
57295           **   * Data stored on the pages immediately following the 
57296           **     pending-byte page in the source database may need to be
57297           **     copied into the destination database.
57298           */
57299           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
57300           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
57301           Pgno iPg;
57302           int nDstPage;
57303           i64 iOff;
57304           i64 iEnd;
57305
57306           assert( pFile );
57307           assert( nDestTruncate==0 
57308               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
57309                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
57310              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
57311           ));
57312
57313           /* This block ensures that all data required to recreate the original
57314           ** database has been stored in the journal for pDestPager and the
57315           ** journal synced to disk. So at this point we may safely modify
57316           ** the database file in any way, knowing that if a power failure
57317           ** occurs, the original database will be reconstructed from the 
57318           ** journal file.  */
57319           sqlite3PagerPagecount(pDestPager, &nDstPage);
57320           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
57321             if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
57322               DbPage *pPg;
57323               rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
57324               if( rc==SQLITE_OK ){
57325                 rc = sqlite3PagerWrite(pPg);
57326                 sqlite3PagerUnref(pPg);
57327               }
57328             }
57329           }
57330           if( rc==SQLITE_OK ){
57331             rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
57332           }
57333
57334           /* Write the extra pages and truncate the database file as required */
57335           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
57336           for(
57337             iOff=PENDING_BYTE+pgszSrc; 
57338             rc==SQLITE_OK && iOff<iEnd; 
57339             iOff+=pgszSrc
57340           ){
57341             PgHdr *pSrcPg = 0;
57342             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
57343             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
57344             if( rc==SQLITE_OK ){
57345               u8 *zData = sqlite3PagerGetData(pSrcPg);
57346               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
57347             }
57348             sqlite3PagerUnref(pSrcPg);
57349           }
57350           if( rc==SQLITE_OK ){
57351             rc = backupTruncateFile(pFile, iSize);
57352           }
57353
57354           /* Sync the database file to disk. */
57355           if( rc==SQLITE_OK ){
57356             rc = sqlite3PagerSync(pDestPager);
57357           }
57358         }else{
57359           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
57360           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
57361         }
57362     
57363         /* Finish committing the transaction to the destination database. */
57364         if( SQLITE_OK==rc
57365          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
57366         ){
57367           rc = SQLITE_DONE;
57368         }
57369       }
57370     }
57371   
57372     /* If bCloseTrans is true, then this function opened a read transaction
57373     ** on the source database. Close the read transaction here. There is
57374     ** no need to check the return values of the btree methods here, as
57375     ** "committing" a read-only transaction cannot fail.
57376     */
57377     if( bCloseTrans ){
57378       TESTONLY( int rc2 );
57379       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
57380       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
57381       assert( rc2==SQLITE_OK );
57382     }
57383   
57384     if( rc==SQLITE_IOERR_NOMEM ){
57385       rc = SQLITE_NOMEM;
57386     }
57387     p->rc = rc;
57388   }
57389   if( p->pDestDb ){
57390     sqlite3_mutex_leave(p->pDestDb->mutex);
57391   }
57392   sqlite3BtreeLeave(p->pSrc);
57393   sqlite3_mutex_leave(p->pSrcDb->mutex);
57394   return rc;
57395 }
57396
57397 /*
57398 ** Release all resources associated with an sqlite3_backup* handle.
57399 */
57400 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
57401   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
57402   sqlite3 *pSrcDb;                     /* Source database connection */
57403   int rc;                              /* Value to return */
57404
57405   /* Enter the mutexes */
57406   if( p==0 ) return SQLITE_OK;
57407   pSrcDb = p->pSrcDb;
57408   sqlite3_mutex_enter(pSrcDb->mutex);
57409   sqlite3BtreeEnter(p->pSrc);
57410   if( p->pDestDb ){
57411     sqlite3_mutex_enter(p->pDestDb->mutex);
57412   }
57413
57414   /* Detach this backup from the source pager. */
57415   if( p->pDestDb ){
57416     p->pSrc->nBackup--;
57417   }
57418   if( p->isAttached ){
57419     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
57420     while( *pp!=p ){
57421       pp = &(*pp)->pNext;
57422     }
57423     *pp = p->pNext;
57424   }
57425
57426   /* If a transaction is still open on the Btree, roll it back. */
57427   sqlite3BtreeRollback(p->pDest, SQLITE_OK);
57428
57429   /* Set the error code of the destination database handle. */
57430   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
57431   sqlite3Error(p->pDestDb, rc, 0);
57432
57433   /* Exit the mutexes and free the backup context structure. */
57434   if( p->pDestDb ){
57435     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
57436   }
57437   sqlite3BtreeLeave(p->pSrc);
57438   if( p->pDestDb ){
57439     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
57440     ** call to sqlite3_backup_init() and is destroyed by a call to
57441     ** sqlite3_backup_finish(). */
57442     sqlite3_free(p);
57443   }
57444   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
57445   return rc;
57446 }
57447
57448 /*
57449 ** Return the number of pages still to be backed up as of the most recent
57450 ** call to sqlite3_backup_step().
57451 */
57452 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
57453   return p->nRemaining;
57454 }
57455
57456 /*
57457 ** Return the total number of pages in the source database as of the most 
57458 ** recent call to sqlite3_backup_step().
57459 */
57460 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
57461   return p->nPagecount;
57462 }
57463
57464 /*
57465 ** This function is called after the contents of page iPage of the
57466 ** source database have been modified. If page iPage has already been 
57467 ** copied into the destination database, then the data written to the
57468 ** destination is now invalidated. The destination copy of iPage needs
57469 ** to be updated with the new data before the backup operation is
57470 ** complete.
57471 **
57472 ** It is assumed that the mutex associated with the BtShared object
57473 ** corresponding to the source database is held when this function is
57474 ** called.
57475 */
57476 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
57477   sqlite3_backup *p;                   /* Iterator variable */
57478   for(p=pBackup; p; p=p->pNext){
57479     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
57480     if( !isFatalError(p->rc) && iPage<p->iNext ){
57481       /* The backup process p has already copied page iPage. But now it
57482       ** has been modified by a transaction on the source pager. Copy
57483       ** the new data into the backup.
57484       */
57485       int rc;
57486       assert( p->pDestDb );
57487       sqlite3_mutex_enter(p->pDestDb->mutex);
57488       rc = backupOnePage(p, iPage, aData, 1);
57489       sqlite3_mutex_leave(p->pDestDb->mutex);
57490       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
57491       if( rc!=SQLITE_OK ){
57492         p->rc = rc;
57493       }
57494     }
57495   }
57496 }
57497
57498 /*
57499 ** Restart the backup process. This is called when the pager layer
57500 ** detects that the database has been modified by an external database
57501 ** connection. In this case there is no way of knowing which of the
57502 ** pages that have been copied into the destination database are still 
57503 ** valid and which are not, so the entire process needs to be restarted.
57504 **
57505 ** It is assumed that the mutex associated with the BtShared object
57506 ** corresponding to the source database is held when this function is
57507 ** called.
57508 */
57509 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
57510   sqlite3_backup *p;                   /* Iterator variable */
57511   for(p=pBackup; p; p=p->pNext){
57512     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
57513     p->iNext = 1;
57514   }
57515 }
57516
57517 #ifndef SQLITE_OMIT_VACUUM
57518 /*
57519 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
57520 ** must be active for both files.
57521 **
57522 ** The size of file pTo may be reduced by this operation. If anything 
57523 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
57524 ** transaction is committed before returning.
57525 */
57526 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
57527   int rc;
57528   sqlite3_file *pFd;              /* File descriptor for database pTo */
57529   sqlite3_backup b;
57530   sqlite3BtreeEnter(pTo);
57531   sqlite3BtreeEnter(pFrom);
57532
57533   assert( sqlite3BtreeIsInTrans(pTo) );
57534   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
57535   if( pFd->pMethods ){
57536     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
57537     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
57538     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
57539     if( rc ) goto copy_finished;
57540   }
57541
57542   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
57543   ** to 0. This is used by the implementations of sqlite3_backup_step()
57544   ** and sqlite3_backup_finish() to detect that they are being called
57545   ** from this function, not directly by the user.
57546   */
57547   memset(&b, 0, sizeof(b));
57548   b.pSrcDb = pFrom->db;
57549   b.pSrc = pFrom;
57550   b.pDest = pTo;
57551   b.iNext = 1;
57552
57553   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
57554   ** file. By passing this as the number of pages to copy to
57555   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
57556   ** within a single call (unless an error occurs). The assert() statement
57557   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
57558   ** or an error code.
57559   */
57560   sqlite3_backup_step(&b, 0x7FFFFFFF);
57561   assert( b.rc!=SQLITE_OK );
57562   rc = sqlite3_backup_finish(&b);
57563   if( rc==SQLITE_OK ){
57564     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
57565   }else{
57566     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
57567   }
57568
57569   assert( sqlite3BtreeIsInTrans(pTo)==0 );
57570 copy_finished:
57571   sqlite3BtreeLeave(pFrom);
57572   sqlite3BtreeLeave(pTo);
57573   return rc;
57574 }
57575 #endif /* SQLITE_OMIT_VACUUM */
57576
57577 /************** End of backup.c **********************************************/
57578 /************** Begin file vdbemem.c *****************************************/
57579 /*
57580 ** 2004 May 26
57581 **
57582 ** The author disclaims copyright to this source code.  In place of
57583 ** a legal notice, here is a blessing:
57584 **
57585 **    May you do good and not evil.
57586 **    May you find forgiveness for yourself and forgive others.
57587 **    May you share freely, never taking more than you give.
57588 **
57589 *************************************************************************
57590 **
57591 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
57592 ** stores a single value in the VDBE.  Mem is an opaque structure visible
57593 ** only within the VDBE.  Interface routines refer to a Mem using the
57594 ** name sqlite_value
57595 */
57596
57597 /*
57598 ** If pMem is an object with a valid string representation, this routine
57599 ** ensures the internal encoding for the string representation is
57600 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
57601 **
57602 ** If pMem is not a string object, or the encoding of the string
57603 ** representation is already stored using the requested encoding, then this
57604 ** routine is a no-op.
57605 **
57606 ** SQLITE_OK is returned if the conversion is successful (or not required).
57607 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
57608 ** between formats.
57609 */
57610 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
57611 #ifndef SQLITE_OMIT_UTF16
57612   int rc;
57613 #endif
57614   assert( (pMem->flags&MEM_RowSet)==0 );
57615   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
57616            || desiredEnc==SQLITE_UTF16BE );
57617   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
57618     return SQLITE_OK;
57619   }
57620   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57621 #ifdef SQLITE_OMIT_UTF16
57622   return SQLITE_ERROR;
57623 #else
57624
57625   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
57626   ** then the encoding of the value may not have changed.
57627   */
57628   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
57629   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
57630   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
57631   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
57632   return rc;
57633 #endif
57634 }
57635
57636 /*
57637 ** Make sure pMem->z points to a writable allocation of at least 
57638 ** n bytes.
57639 **
57640 ** If the third argument passed to this function is true, then memory
57641 ** cell pMem must contain a string or blob. In this case the content is
57642 ** preserved. Otherwise, if the third parameter to this function is false,
57643 ** any current string or blob value may be discarded.
57644 **
57645 ** This function sets the MEM_Dyn flag and clears any xDel callback.
57646 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
57647 ** not set, Mem.n is zeroed.
57648 */
57649 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
57650   assert( 1 >=
57651     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
57652     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
57653     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
57654     ((pMem->flags&MEM_Static) ? 1 : 0)
57655   );
57656   assert( (pMem->flags&MEM_RowSet)==0 );
57657
57658   /* If the preserve flag is set to true, then the memory cell must already
57659   ** contain a valid string or blob value.  */
57660   assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
57661
57662   if( n<32 ) n = 32;
57663   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
57664     if( preserve && pMem->z==pMem->zMalloc ){
57665       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
57666       preserve = 0;
57667     }else{
57668       sqlite3DbFree(pMem->db, pMem->zMalloc);
57669       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
57670     }
57671   }
57672
57673   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
57674     memcpy(pMem->zMalloc, pMem->z, pMem->n);
57675   }
57676   if( pMem->flags&MEM_Dyn && pMem->xDel ){
57677     assert( pMem->xDel!=SQLITE_DYNAMIC );
57678     pMem->xDel((void *)(pMem->z));
57679   }
57680
57681   pMem->z = pMem->zMalloc;
57682   if( pMem->z==0 ){
57683     pMem->flags = MEM_Null;
57684   }else{
57685     pMem->flags &= ~(MEM_Ephem|MEM_Static);
57686   }
57687   pMem->xDel = 0;
57688   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
57689 }
57690
57691 /*
57692 ** Make the given Mem object MEM_Dyn.  In other words, make it so
57693 ** that any TEXT or BLOB content is stored in memory obtained from
57694 ** malloc().  In this way, we know that the memory is safe to be
57695 ** overwritten or altered.
57696 **
57697 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
57698 */
57699 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
57700   int f;
57701   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57702   assert( (pMem->flags&MEM_RowSet)==0 );
57703   ExpandBlob(pMem);
57704   f = pMem->flags;
57705   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
57706     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
57707       return SQLITE_NOMEM;
57708     }
57709     pMem->z[pMem->n] = 0;
57710     pMem->z[pMem->n+1] = 0;
57711     pMem->flags |= MEM_Term;
57712 #ifdef SQLITE_DEBUG
57713     pMem->pScopyFrom = 0;
57714 #endif
57715   }
57716
57717   return SQLITE_OK;
57718 }
57719
57720 /*
57721 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
57722 ** blob stored in dynamically allocated space.
57723 */
57724 #ifndef SQLITE_OMIT_INCRBLOB
57725 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
57726   if( pMem->flags & MEM_Zero ){
57727     int nByte;
57728     assert( pMem->flags&MEM_Blob );
57729     assert( (pMem->flags&MEM_RowSet)==0 );
57730     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57731
57732     /* Set nByte to the number of bytes required to store the expanded blob. */
57733     nByte = pMem->n + pMem->u.nZero;
57734     if( nByte<=0 ){
57735       nByte = 1;
57736     }
57737     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
57738       return SQLITE_NOMEM;
57739     }
57740
57741     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
57742     pMem->n += pMem->u.nZero;
57743     pMem->flags &= ~(MEM_Zero|MEM_Term);
57744   }
57745   return SQLITE_OK;
57746 }
57747 #endif
57748
57749
57750 /*
57751 ** Make sure the given Mem is \u0000 terminated.
57752 */
57753 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
57754   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57755   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
57756     return SQLITE_OK;   /* Nothing to do */
57757   }
57758   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
57759     return SQLITE_NOMEM;
57760   }
57761   pMem->z[pMem->n] = 0;
57762   pMem->z[pMem->n+1] = 0;
57763   pMem->flags |= MEM_Term;
57764   return SQLITE_OK;
57765 }
57766
57767 /*
57768 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
57769 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
57770 ** is a no-op.
57771 **
57772 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
57773 **
57774 ** A MEM_Null value will never be passed to this function. This function is
57775 ** used for converting values to text for returning to the user (i.e. via
57776 ** sqlite3_value_text()), or for ensuring that values to be used as btree
57777 ** keys are strings. In the former case a NULL pointer is returned the
57778 ** user and the later is an internal programming error.
57779 */
57780 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
57781   int rc = SQLITE_OK;
57782   int fg = pMem->flags;
57783   const int nByte = 32;
57784
57785   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57786   assert( !(fg&MEM_Zero) );
57787   assert( !(fg&(MEM_Str|MEM_Blob)) );
57788   assert( fg&(MEM_Int|MEM_Real) );
57789   assert( (pMem->flags&MEM_RowSet)==0 );
57790   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57791
57792
57793   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
57794     return SQLITE_NOMEM;
57795   }
57796
57797   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
57798   ** string representation of the value. Then, if the required encoding
57799   ** is UTF-16le or UTF-16be do a translation.
57800   ** 
57801   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
57802   */
57803   if( fg & MEM_Int ){
57804     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
57805   }else{
57806     assert( fg & MEM_Real );
57807     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
57808   }
57809   pMem->n = sqlite3Strlen30(pMem->z);
57810   pMem->enc = SQLITE_UTF8;
57811   pMem->flags |= MEM_Str|MEM_Term;
57812   sqlite3VdbeChangeEncoding(pMem, enc);
57813   return rc;
57814 }
57815
57816 /*
57817 ** Memory cell pMem contains the context of an aggregate function.
57818 ** This routine calls the finalize method for that function.  The
57819 ** result of the aggregate is stored back into pMem.
57820 **
57821 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
57822 ** otherwise.
57823 */
57824 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
57825   int rc = SQLITE_OK;
57826   if( ALWAYS(pFunc && pFunc->xFinalize) ){
57827     sqlite3_context ctx;
57828     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
57829     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57830     memset(&ctx, 0, sizeof(ctx));
57831     ctx.s.flags = MEM_Null;
57832     ctx.s.db = pMem->db;
57833     ctx.pMem = pMem;
57834     ctx.pFunc = pFunc;
57835     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
57836     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
57837     sqlite3DbFree(pMem->db, pMem->zMalloc);
57838     memcpy(pMem, &ctx.s, sizeof(ctx.s));
57839     rc = ctx.isError;
57840   }
57841   return rc;
57842 }
57843
57844 /*
57845 ** If the memory cell contains a string value that must be freed by
57846 ** invoking an external callback, free it now. Calling this function
57847 ** does not free any Mem.zMalloc buffer.
57848 */
57849 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
57850   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
57851   if( p->flags&MEM_Agg ){
57852     sqlite3VdbeMemFinalize(p, p->u.pDef);
57853     assert( (p->flags & MEM_Agg)==0 );
57854     sqlite3VdbeMemRelease(p);
57855   }else if( p->flags&MEM_Dyn && p->xDel ){
57856     assert( (p->flags&MEM_RowSet)==0 );
57857     assert( p->xDel!=SQLITE_DYNAMIC );
57858     p->xDel((void *)p->z);
57859     p->xDel = 0;
57860   }else if( p->flags&MEM_RowSet ){
57861     sqlite3RowSetClear(p->u.pRowSet);
57862   }else if( p->flags&MEM_Frame ){
57863     sqlite3VdbeMemSetNull(p);
57864   }
57865 }
57866
57867 /*
57868 ** Release any memory held by the Mem. This may leave the Mem in an
57869 ** inconsistent state, for example with (Mem.z==0) and
57870 ** (Mem.type==SQLITE_TEXT).
57871 */
57872 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
57873   VdbeMemRelease(p);
57874   sqlite3DbFree(p->db, p->zMalloc);
57875   p->z = 0;
57876   p->zMalloc = 0;
57877   p->xDel = 0;
57878 }
57879
57880 /*
57881 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
57882 ** If the double is too large, return 0x8000000000000000.
57883 **
57884 ** Most systems appear to do this simply by assigning
57885 ** variables and without the extra range tests.  But
57886 ** there are reports that windows throws an expection
57887 ** if the floating point value is out of range. (See ticket #2880.)
57888 ** Because we do not completely understand the problem, we will
57889 ** take the conservative approach and always do range tests
57890 ** before attempting the conversion.
57891 */
57892 static i64 doubleToInt64(double r){
57893 #ifdef SQLITE_OMIT_FLOATING_POINT
57894   /* When floating-point is omitted, double and int64 are the same thing */
57895   return r;
57896 #else
57897   /*
57898   ** Many compilers we encounter do not define constants for the
57899   ** minimum and maximum 64-bit integers, or they define them
57900   ** inconsistently.  And many do not understand the "LL" notation.
57901   ** So we define our own static constants here using nothing
57902   ** larger than a 32-bit integer constant.
57903   */
57904   static const i64 maxInt = LARGEST_INT64;
57905   static const i64 minInt = SMALLEST_INT64;
57906
57907   if( r<(double)minInt ){
57908     return minInt;
57909   }else if( r>(double)maxInt ){
57910     /* minInt is correct here - not maxInt.  It turns out that assigning
57911     ** a very large positive number to an integer results in a very large
57912     ** negative integer.  This makes no sense, but it is what x86 hardware
57913     ** does so for compatibility we will do the same in software. */
57914     return minInt;
57915   }else{
57916     return (i64)r;
57917   }
57918 #endif
57919 }
57920
57921 /*
57922 ** Return some kind of integer value which is the best we can do
57923 ** at representing the value that *pMem describes as an integer.
57924 ** If pMem is an integer, then the value is exact.  If pMem is
57925 ** a floating-point then the value returned is the integer part.
57926 ** If pMem is a string or blob, then we make an attempt to convert
57927 ** it into a integer and return that.  If pMem represents an
57928 ** an SQL-NULL value, return 0.
57929 **
57930 ** If pMem represents a string value, its encoding might be changed.
57931 */
57932 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
57933   int flags;
57934   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57935   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57936   flags = pMem->flags;
57937   if( flags & MEM_Int ){
57938     return pMem->u.i;
57939   }else if( flags & MEM_Real ){
57940     return doubleToInt64(pMem->r);
57941   }else if( flags & (MEM_Str|MEM_Blob) ){
57942     i64 value = 0;
57943     assert( pMem->z || pMem->n==0 );
57944     testcase( pMem->z==0 );
57945     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
57946     return value;
57947   }else{
57948     return 0;
57949   }
57950 }
57951
57952 /*
57953 ** Return the best representation of pMem that we can get into a
57954 ** double.  If pMem is already a double or an integer, return its
57955 ** value.  If it is a string or blob, try to convert it to a double.
57956 ** If it is a NULL, return 0.0.
57957 */
57958 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
57959   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57960   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57961   if( pMem->flags & MEM_Real ){
57962     return pMem->r;
57963   }else if( pMem->flags & MEM_Int ){
57964     return (double)pMem->u.i;
57965   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
57966     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
57967     double val = (double)0;
57968     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
57969     return val;
57970   }else{
57971     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
57972     return (double)0;
57973   }
57974 }
57975
57976 /*
57977 ** The MEM structure is already a MEM_Real.  Try to also make it a
57978 ** MEM_Int if we can.
57979 */
57980 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
57981   assert( pMem->flags & MEM_Real );
57982   assert( (pMem->flags & MEM_RowSet)==0 );
57983   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57984   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57985
57986   pMem->u.i = doubleToInt64(pMem->r);
57987
57988   /* Only mark the value as an integer if
57989   **
57990   **    (1) the round-trip conversion real->int->real is a no-op, and
57991   **    (2) The integer is neither the largest nor the smallest
57992   **        possible integer (ticket #3922)
57993   **
57994   ** The second and third terms in the following conditional enforces
57995   ** the second condition under the assumption that addition overflow causes
57996   ** values to wrap around.  On x86 hardware, the third term is always
57997   ** true and could be omitted.  But we leave it in because other
57998   ** architectures might behave differently.
57999   */
58000   if( pMem->r==(double)pMem->u.i
58001    && pMem->u.i>SMALLEST_INT64
58002 #if defined(__i486__) || defined(__x86_64__)
58003    && ALWAYS(pMem->u.i<LARGEST_INT64)
58004 #else
58005    && pMem->u.i<LARGEST_INT64
58006 #endif
58007   ){
58008     pMem->flags |= MEM_Int;
58009   }
58010 }
58011
58012 /*
58013 ** Convert pMem to type integer.  Invalidate any prior representations.
58014 */
58015 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
58016   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58017   assert( (pMem->flags & MEM_RowSet)==0 );
58018   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58019
58020   pMem->u.i = sqlite3VdbeIntValue(pMem);
58021   MemSetTypeFlag(pMem, MEM_Int);
58022   return SQLITE_OK;
58023 }
58024
58025 /*
58026 ** Convert pMem so that it is of type MEM_Real.
58027 ** Invalidate any prior representations.
58028 */
58029 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
58030   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58031   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58032
58033   pMem->r = sqlite3VdbeRealValue(pMem);
58034   MemSetTypeFlag(pMem, MEM_Real);
58035   return SQLITE_OK;
58036 }
58037
58038 /*
58039 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
58040 ** Invalidate any prior representations.
58041 **
58042 ** Every effort is made to force the conversion, even if the input
58043 ** is a string that does not look completely like a number.  Convert
58044 ** as much of the string as we can and ignore the rest.
58045 */
58046 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
58047   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
58048     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
58049     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58050     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
58051       MemSetTypeFlag(pMem, MEM_Int);
58052     }else{
58053       pMem->r = sqlite3VdbeRealValue(pMem);
58054       MemSetTypeFlag(pMem, MEM_Real);
58055       sqlite3VdbeIntegerAffinity(pMem);
58056     }
58057   }
58058   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
58059   pMem->flags &= ~(MEM_Str|MEM_Blob);
58060   return SQLITE_OK;
58061 }
58062
58063 /*
58064 ** Delete any previous value and set the value stored in *pMem to NULL.
58065 */
58066 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
58067   if( pMem->flags & MEM_Frame ){
58068     VdbeFrame *pFrame = pMem->u.pFrame;
58069     pFrame->pParent = pFrame->v->pDelFrame;
58070     pFrame->v->pDelFrame = pFrame;
58071   }
58072   if( pMem->flags & MEM_RowSet ){
58073     sqlite3RowSetClear(pMem->u.pRowSet);
58074   }
58075   MemSetTypeFlag(pMem, MEM_Null);
58076   pMem->type = SQLITE_NULL;
58077 }
58078
58079 /*
58080 ** Delete any previous value and set the value to be a BLOB of length
58081 ** n containing all zeros.
58082 */
58083 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
58084   sqlite3VdbeMemRelease(pMem);
58085   pMem->flags = MEM_Blob|MEM_Zero;
58086   pMem->type = SQLITE_BLOB;
58087   pMem->n = 0;
58088   if( n<0 ) n = 0;
58089   pMem->u.nZero = n;
58090   pMem->enc = SQLITE_UTF8;
58091
58092 #ifdef SQLITE_OMIT_INCRBLOB
58093   sqlite3VdbeMemGrow(pMem, n, 0);
58094   if( pMem->z ){
58095     pMem->n = n;
58096     memset(pMem->z, 0, n);
58097   }
58098 #endif
58099 }
58100
58101 /*
58102 ** Delete any previous value and set the value stored in *pMem to val,
58103 ** manifest type INTEGER.
58104 */
58105 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
58106   sqlite3VdbeMemRelease(pMem);
58107   pMem->u.i = val;
58108   pMem->flags = MEM_Int;
58109   pMem->type = SQLITE_INTEGER;
58110 }
58111
58112 #ifndef SQLITE_OMIT_FLOATING_POINT
58113 /*
58114 ** Delete any previous value and set the value stored in *pMem to val,
58115 ** manifest type REAL.
58116 */
58117 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
58118   if( sqlite3IsNaN(val) ){
58119     sqlite3VdbeMemSetNull(pMem);
58120   }else{
58121     sqlite3VdbeMemRelease(pMem);
58122     pMem->r = val;
58123     pMem->flags = MEM_Real;
58124     pMem->type = SQLITE_FLOAT;
58125   }
58126 }
58127 #endif
58128
58129 /*
58130 ** Delete any previous value and set the value of pMem to be an
58131 ** empty boolean index.
58132 */
58133 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
58134   sqlite3 *db = pMem->db;
58135   assert( db!=0 );
58136   assert( (pMem->flags & MEM_RowSet)==0 );
58137   sqlite3VdbeMemRelease(pMem);
58138   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
58139   if( db->mallocFailed ){
58140     pMem->flags = MEM_Null;
58141   }else{
58142     assert( pMem->zMalloc );
58143     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
58144                                        sqlite3DbMallocSize(db, pMem->zMalloc));
58145     assert( pMem->u.pRowSet!=0 );
58146     pMem->flags = MEM_RowSet;
58147   }
58148 }
58149
58150 /*
58151 ** Return true if the Mem object contains a TEXT or BLOB that is
58152 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
58153 */
58154 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
58155   assert( p->db!=0 );
58156   if( p->flags & (MEM_Str|MEM_Blob) ){
58157     int n = p->n;
58158     if( p->flags & MEM_Zero ){
58159       n += p->u.nZero;
58160     }
58161     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
58162   }
58163   return 0; 
58164 }
58165
58166 #ifdef SQLITE_DEBUG
58167 /*
58168 ** This routine prepares a memory cell for modication by breaking
58169 ** its link to a shallow copy and by marking any current shallow
58170 ** copies of this cell as invalid.
58171 **
58172 ** This is used for testing and debugging only - to make sure shallow
58173 ** copies are not misused.
58174 */
58175 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
58176   int i;
58177   Mem *pX;
58178   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
58179     if( pX->pScopyFrom==pMem ){
58180       pX->flags |= MEM_Invalid;
58181       pX->pScopyFrom = 0;
58182     }
58183   }
58184   pMem->pScopyFrom = 0;
58185 }
58186 #endif /* SQLITE_DEBUG */
58187
58188 /*
58189 ** Size of struct Mem not including the Mem.zMalloc member.
58190 */
58191 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
58192
58193 /*
58194 ** Make an shallow copy of pFrom into pTo.  Prior contents of
58195 ** pTo are freed.  The pFrom->z field is not duplicated.  If
58196 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
58197 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
58198 */
58199 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
58200   assert( (pFrom->flags & MEM_RowSet)==0 );
58201   VdbeMemRelease(pTo);
58202   memcpy(pTo, pFrom, MEMCELLSIZE);
58203   pTo->xDel = 0;
58204   if( (pFrom->flags&MEM_Static)==0 ){
58205     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
58206     assert( srcType==MEM_Ephem || srcType==MEM_Static );
58207     pTo->flags |= srcType;
58208   }
58209 }
58210
58211 /*
58212 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
58213 ** freed before the copy is made.
58214 */
58215 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
58216   int rc = SQLITE_OK;
58217
58218   assert( (pFrom->flags & MEM_RowSet)==0 );
58219   VdbeMemRelease(pTo);
58220   memcpy(pTo, pFrom, MEMCELLSIZE);
58221   pTo->flags &= ~MEM_Dyn;
58222
58223   if( pTo->flags&(MEM_Str|MEM_Blob) ){
58224     if( 0==(pFrom->flags&MEM_Static) ){
58225       pTo->flags |= MEM_Ephem;
58226       rc = sqlite3VdbeMemMakeWriteable(pTo);
58227     }
58228   }
58229
58230   return rc;
58231 }
58232
58233 /*
58234 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
58235 ** freed. If pFrom contains ephemeral data, a copy is made.
58236 **
58237 ** pFrom contains an SQL NULL when this routine returns.
58238 */
58239 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
58240   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
58241   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
58242   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
58243
58244   sqlite3VdbeMemRelease(pTo);
58245   memcpy(pTo, pFrom, sizeof(Mem));
58246   pFrom->flags = MEM_Null;
58247   pFrom->xDel = 0;
58248   pFrom->zMalloc = 0;
58249 }
58250
58251 /*
58252 ** Change the value of a Mem to be a string or a BLOB.
58253 **
58254 ** The memory management strategy depends on the value of the xDel
58255 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
58256 ** string is copied into a (possibly existing) buffer managed by the 
58257 ** Mem structure. Otherwise, any existing buffer is freed and the
58258 ** pointer copied.
58259 **
58260 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
58261 ** size limit) then no memory allocation occurs.  If the string can be
58262 ** stored without allocating memory, then it is.  If a memory allocation
58263 ** is required to store the string, then value of pMem is unchanged.  In
58264 ** either case, SQLITE_TOOBIG is returned.
58265 */
58266 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
58267   Mem *pMem,          /* Memory cell to set to string value */
58268   const char *z,      /* String pointer */
58269   int n,              /* Bytes in string, or negative */
58270   u8 enc,             /* Encoding of z.  0 for BLOBs */
58271   void (*xDel)(void*) /* Destructor function */
58272 ){
58273   int nByte = n;      /* New value for pMem->n */
58274   int iLimit;         /* Maximum allowed string or blob size */
58275   u16 flags = 0;      /* New value for pMem->flags */
58276
58277   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58278   assert( (pMem->flags & MEM_RowSet)==0 );
58279
58280   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
58281   if( !z ){
58282     sqlite3VdbeMemSetNull(pMem);
58283     return SQLITE_OK;
58284   }
58285
58286   if( pMem->db ){
58287     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
58288   }else{
58289     iLimit = SQLITE_MAX_LENGTH;
58290   }
58291   flags = (enc==0?MEM_Blob:MEM_Str);
58292   if( nByte<0 ){
58293     assert( enc!=0 );
58294     if( enc==SQLITE_UTF8 ){
58295       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
58296     }else{
58297       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
58298     }
58299     flags |= MEM_Term;
58300   }
58301
58302   /* The following block sets the new values of Mem.z and Mem.xDel. It
58303   ** also sets a flag in local variable "flags" to indicate the memory
58304   ** management (one of MEM_Dyn or MEM_Static).
58305   */
58306   if( xDel==SQLITE_TRANSIENT ){
58307     int nAlloc = nByte;
58308     if( flags&MEM_Term ){
58309       nAlloc += (enc==SQLITE_UTF8?1:2);
58310     }
58311     if( nByte>iLimit ){
58312       return SQLITE_TOOBIG;
58313     }
58314     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
58315       return SQLITE_NOMEM;
58316     }
58317     memcpy(pMem->z, z, nAlloc);
58318   }else if( xDel==SQLITE_DYNAMIC ){
58319     sqlite3VdbeMemRelease(pMem);
58320     pMem->zMalloc = pMem->z = (char *)z;
58321     pMem->xDel = 0;
58322   }else{
58323     sqlite3VdbeMemRelease(pMem);
58324     pMem->z = (char *)z;
58325     pMem->xDel = xDel;
58326     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
58327   }
58328
58329   pMem->n = nByte;
58330   pMem->flags = flags;
58331   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
58332   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
58333
58334 #ifndef SQLITE_OMIT_UTF16
58335   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
58336     return SQLITE_NOMEM;
58337   }
58338 #endif
58339
58340   if( nByte>iLimit ){
58341     return SQLITE_TOOBIG;
58342   }
58343
58344   return SQLITE_OK;
58345 }
58346
58347 /*
58348 ** Compare the values contained by the two memory cells, returning
58349 ** negative, zero or positive if pMem1 is less than, equal to, or greater
58350 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
58351 ** and reals) sorted numerically, followed by text ordered by the collating
58352 ** sequence pColl and finally blob's ordered by memcmp().
58353 **
58354 ** Two NULL values are considered equal by this function.
58355 */
58356 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
58357   int rc;
58358   int f1, f2;
58359   int combined_flags;
58360
58361   f1 = pMem1->flags;
58362   f2 = pMem2->flags;
58363   combined_flags = f1|f2;
58364   assert( (combined_flags & MEM_RowSet)==0 );
58365  
58366   /* If one value is NULL, it is less than the other. If both values
58367   ** are NULL, return 0.
58368   */
58369   if( combined_flags&MEM_Null ){
58370     return (f2&MEM_Null) - (f1&MEM_Null);
58371   }
58372
58373   /* If one value is a number and the other is not, the number is less.
58374   ** If both are numbers, compare as reals if one is a real, or as integers
58375   ** if both values are integers.
58376   */
58377   if( combined_flags&(MEM_Int|MEM_Real) ){
58378     if( !(f1&(MEM_Int|MEM_Real)) ){
58379       return 1;
58380     }
58381     if( !(f2&(MEM_Int|MEM_Real)) ){
58382       return -1;
58383     }
58384     if( (f1 & f2 & MEM_Int)==0 ){
58385       double r1, r2;
58386       if( (f1&MEM_Real)==0 ){
58387         r1 = (double)pMem1->u.i;
58388       }else{
58389         r1 = pMem1->r;
58390       }
58391       if( (f2&MEM_Real)==0 ){
58392         r2 = (double)pMem2->u.i;
58393       }else{
58394         r2 = pMem2->r;
58395       }
58396       if( r1<r2 ) return -1;
58397       if( r1>r2 ) return 1;
58398       return 0;
58399     }else{
58400       assert( f1&MEM_Int );
58401       assert( f2&MEM_Int );
58402       if( pMem1->u.i < pMem2->u.i ) return -1;
58403       if( pMem1->u.i > pMem2->u.i ) return 1;
58404       return 0;
58405     }
58406   }
58407
58408   /* If one value is a string and the other is a blob, the string is less.
58409   ** If both are strings, compare using the collating functions.
58410   */
58411   if( combined_flags&MEM_Str ){
58412     if( (f1 & MEM_Str)==0 ){
58413       return 1;
58414     }
58415     if( (f2 & MEM_Str)==0 ){
58416       return -1;
58417     }
58418
58419     assert( pMem1->enc==pMem2->enc );
58420     assert( pMem1->enc==SQLITE_UTF8 || 
58421             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
58422
58423     /* The collation sequence must be defined at this point, even if
58424     ** the user deletes the collation sequence after the vdbe program is
58425     ** compiled (this was not always the case).
58426     */
58427     assert( !pColl || pColl->xCmp );
58428
58429     if( pColl ){
58430       if( pMem1->enc==pColl->enc ){
58431         /* The strings are already in the correct encoding.  Call the
58432         ** comparison function directly */
58433         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
58434       }else{
58435         const void *v1, *v2;
58436         int n1, n2;
58437         Mem c1;
58438         Mem c2;
58439         memset(&c1, 0, sizeof(c1));
58440         memset(&c2, 0, sizeof(c2));
58441         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
58442         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
58443         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
58444         n1 = v1==0 ? 0 : c1.n;
58445         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
58446         n2 = v2==0 ? 0 : c2.n;
58447         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
58448         sqlite3VdbeMemRelease(&c1);
58449         sqlite3VdbeMemRelease(&c2);
58450         return rc;
58451       }
58452     }
58453     /* If a NULL pointer was passed as the collate function, fall through
58454     ** to the blob case and use memcmp().  */
58455   }
58456  
58457   /* Both values must be blobs.  Compare using memcmp().  */
58458   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
58459   if( rc==0 ){
58460     rc = pMem1->n - pMem2->n;
58461   }
58462   return rc;
58463 }
58464
58465 /*
58466 ** Move data out of a btree key or data field and into a Mem structure.
58467 ** The data or key is taken from the entry that pCur is currently pointing
58468 ** to.  offset and amt determine what portion of the data or key to retrieve.
58469 ** key is true to get the key or false to get data.  The result is written
58470 ** into the pMem element.
58471 **
58472 ** The pMem structure is assumed to be uninitialized.  Any prior content
58473 ** is overwritten without being freed.
58474 **
58475 ** If this routine fails for any reason (malloc returns NULL or unable
58476 ** to read from the disk) then the pMem is left in an inconsistent state.
58477 */
58478 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
58479   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
58480   int offset,       /* Offset from the start of data to return bytes from. */
58481   int amt,          /* Number of bytes to return. */
58482   int key,          /* If true, retrieve from the btree key, not data. */
58483   Mem *pMem         /* OUT: Return data in this Mem structure. */
58484 ){
58485   char *zData;        /* Data from the btree layer */
58486   int available = 0;  /* Number of bytes available on the local btree page */
58487   int rc = SQLITE_OK; /* Return code */
58488
58489   assert( sqlite3BtreeCursorIsValid(pCur) );
58490
58491   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
58492   ** that both the BtShared and database handle mutexes are held. */
58493   assert( (pMem->flags & MEM_RowSet)==0 );
58494   if( key ){
58495     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
58496   }else{
58497     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
58498   }
58499   assert( zData!=0 );
58500
58501   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
58502     sqlite3VdbeMemRelease(pMem);
58503     pMem->z = &zData[offset];
58504     pMem->flags = MEM_Blob|MEM_Ephem;
58505   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
58506     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
58507     pMem->enc = 0;
58508     pMem->type = SQLITE_BLOB;
58509     if( key ){
58510       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
58511     }else{
58512       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
58513     }
58514     pMem->z[amt] = 0;
58515     pMem->z[amt+1] = 0;
58516     if( rc!=SQLITE_OK ){
58517       sqlite3VdbeMemRelease(pMem);
58518     }
58519   }
58520   pMem->n = amt;
58521
58522   return rc;
58523 }
58524
58525 /* This function is only available internally, it is not part of the
58526 ** external API. It works in a similar way to sqlite3_value_text(),
58527 ** except the data returned is in the encoding specified by the second
58528 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
58529 ** SQLITE_UTF8.
58530 **
58531 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
58532 ** If that is the case, then the result must be aligned on an even byte
58533 ** boundary.
58534 */
58535 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
58536   if( !pVal ) return 0;
58537
58538   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
58539   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
58540   assert( (pVal->flags & MEM_RowSet)==0 );
58541
58542   if( pVal->flags&MEM_Null ){
58543     return 0;
58544   }
58545   assert( (MEM_Blob>>3) == MEM_Str );
58546   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
58547   ExpandBlob(pVal);
58548   if( pVal->flags&MEM_Str ){
58549     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
58550     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
58551       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
58552       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
58553         return 0;
58554       }
58555     }
58556     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
58557   }else{
58558     assert( (pVal->flags&MEM_Blob)==0 );
58559     sqlite3VdbeMemStringify(pVal, enc);
58560     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
58561   }
58562   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
58563               || pVal->db->mallocFailed );
58564   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
58565     return pVal->z;
58566   }else{
58567     return 0;
58568   }
58569 }
58570
58571 /*
58572 ** Create a new sqlite3_value object.
58573 */
58574 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
58575   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
58576   if( p ){
58577     p->flags = MEM_Null;
58578     p->type = SQLITE_NULL;
58579     p->db = db;
58580   }
58581   return p;
58582 }
58583
58584 /*
58585 ** Create a new sqlite3_value object, containing the value of pExpr.
58586 **
58587 ** This only works for very simple expressions that consist of one constant
58588 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
58589 ** be converted directly into a value, then the value is allocated and
58590 ** a pointer written to *ppVal. The caller is responsible for deallocating
58591 ** the value by passing it to sqlite3ValueFree() later on. If the expression
58592 ** cannot be converted to a value, then *ppVal is set to NULL.
58593 */
58594 SQLITE_PRIVATE int sqlite3ValueFromExpr(
58595   sqlite3 *db,              /* The database connection */
58596   Expr *pExpr,              /* The expression to evaluate */
58597   u8 enc,                   /* Encoding to use */
58598   u8 affinity,              /* Affinity to use */
58599   sqlite3_value **ppVal     /* Write the new value here */
58600 ){
58601   int op;
58602   char *zVal = 0;
58603   sqlite3_value *pVal = 0;
58604   int negInt = 1;
58605   const char *zNeg = "";
58606
58607   if( !pExpr ){
58608     *ppVal = 0;
58609     return SQLITE_OK;
58610   }
58611   op = pExpr->op;
58612
58613   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
58614   ** The ifdef here is to enable us to achieve 100% branch test coverage even
58615   ** when SQLITE_ENABLE_STAT3 is omitted.
58616   */
58617 #ifdef SQLITE_ENABLE_STAT3
58618   if( op==TK_REGISTER ) op = pExpr->op2;
58619 #else
58620   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
58621 #endif
58622
58623   /* Handle negative integers in a single step.  This is needed in the
58624   ** case when the value is -9223372036854775808.
58625   */
58626   if( op==TK_UMINUS
58627    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
58628     pExpr = pExpr->pLeft;
58629     op = pExpr->op;
58630     negInt = -1;
58631     zNeg = "-";
58632   }
58633
58634   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
58635     pVal = sqlite3ValueNew(db);
58636     if( pVal==0 ) goto no_mem;
58637     if( ExprHasProperty(pExpr, EP_IntValue) ){
58638       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
58639     }else{
58640       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
58641       if( zVal==0 ) goto no_mem;
58642       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
58643       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
58644     }
58645     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
58646       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
58647     }else{
58648       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
58649     }
58650     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
58651     if( enc!=SQLITE_UTF8 ){
58652       sqlite3VdbeChangeEncoding(pVal, enc);
58653     }
58654   }else if( op==TK_UMINUS ) {
58655     /* This branch happens for multiple negative signs.  Ex: -(-5) */
58656     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
58657       sqlite3VdbeMemNumerify(pVal);
58658       if( pVal->u.i==SMALLEST_INT64 ){
58659         pVal->flags &= MEM_Int;
58660         pVal->flags |= MEM_Real;
58661         pVal->r = (double)LARGEST_INT64;
58662       }else{
58663         pVal->u.i = -pVal->u.i;
58664       }
58665       pVal->r = -pVal->r;
58666       sqlite3ValueApplyAffinity(pVal, affinity, enc);
58667     }
58668   }else if( op==TK_NULL ){
58669     pVal = sqlite3ValueNew(db);
58670     if( pVal==0 ) goto no_mem;
58671   }
58672 #ifndef SQLITE_OMIT_BLOB_LITERAL
58673   else if( op==TK_BLOB ){
58674     int nVal;
58675     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
58676     assert( pExpr->u.zToken[1]=='\'' );
58677     pVal = sqlite3ValueNew(db);
58678     if( !pVal ) goto no_mem;
58679     zVal = &pExpr->u.zToken[2];
58680     nVal = sqlite3Strlen30(zVal)-1;
58681     assert( zVal[nVal]=='\'' );
58682     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
58683                          0, SQLITE_DYNAMIC);
58684   }
58685 #endif
58686
58687   if( pVal ){
58688     sqlite3VdbeMemStoreType(pVal);
58689   }
58690   *ppVal = pVal;
58691   return SQLITE_OK;
58692
58693 no_mem:
58694   db->mallocFailed = 1;
58695   sqlite3DbFree(db, zVal);
58696   sqlite3ValueFree(pVal);
58697   *ppVal = 0;
58698   return SQLITE_NOMEM;
58699 }
58700
58701 /*
58702 ** Change the string value of an sqlite3_value object
58703 */
58704 SQLITE_PRIVATE void sqlite3ValueSetStr(
58705   sqlite3_value *v,     /* Value to be set */
58706   int n,                /* Length of string z */
58707   const void *z,        /* Text of the new string */
58708   u8 enc,               /* Encoding to use */
58709   void (*xDel)(void*)   /* Destructor for the string */
58710 ){
58711   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
58712 }
58713
58714 /*
58715 ** Free an sqlite3_value object
58716 */
58717 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
58718   if( !v ) return;
58719   sqlite3VdbeMemRelease((Mem *)v);
58720   sqlite3DbFree(((Mem*)v)->db, v);
58721 }
58722
58723 /*
58724 ** Return the number of bytes in the sqlite3_value object assuming
58725 ** that it uses the encoding "enc"
58726 */
58727 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
58728   Mem *p = (Mem*)pVal;
58729   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
58730     if( p->flags & MEM_Zero ){
58731       return p->n + p->u.nZero;
58732     }else{
58733       return p->n;
58734     }
58735   }
58736   return 0;
58737 }
58738
58739 /************** End of vdbemem.c *********************************************/
58740 /************** Begin file vdbeaux.c *****************************************/
58741 /*
58742 ** 2003 September 6
58743 **
58744 ** The author disclaims copyright to this source code.  In place of
58745 ** a legal notice, here is a blessing:
58746 **
58747 **    May you do good and not evil.
58748 **    May you find forgiveness for yourself and forgive others.
58749 **    May you share freely, never taking more than you give.
58750 **
58751 *************************************************************************
58752 ** This file contains code used for creating, destroying, and populating
58753 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
58754 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
58755 ** But that file was getting too big so this subroutines were split out.
58756 */
58757
58758 /*
58759 ** Create a new virtual database engine.
58760 */
58761 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
58762   Vdbe *p;
58763   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
58764   if( p==0 ) return 0;
58765   p->db = db;
58766   if( db->pVdbe ){
58767     db->pVdbe->pPrev = p;
58768   }
58769   p->pNext = db->pVdbe;
58770   p->pPrev = 0;
58771   db->pVdbe = p;
58772   p->magic = VDBE_MAGIC_INIT;
58773   return p;
58774 }
58775
58776 /*
58777 ** Remember the SQL string for a prepared statement.
58778 */
58779 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
58780   assert( isPrepareV2==1 || isPrepareV2==0 );
58781   if( p==0 ) return;
58782 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
58783   if( !isPrepareV2 ) return;
58784 #endif
58785   assert( p->zSql==0 );
58786   p->zSql = sqlite3DbStrNDup(p->db, z, n);
58787   p->isPrepareV2 = (u8)isPrepareV2;
58788 }
58789
58790 /*
58791 ** Return the SQL associated with a prepared statement
58792 */
58793 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
58794   Vdbe *p = (Vdbe *)pStmt;
58795   return (p && p->isPrepareV2) ? p->zSql : 0;
58796 }
58797
58798 /*
58799 ** Swap all content between two VDBE structures.
58800 */
58801 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
58802   Vdbe tmp, *pTmp;
58803   char *zTmp;
58804   tmp = *pA;
58805   *pA = *pB;
58806   *pB = tmp;
58807   pTmp = pA->pNext;
58808   pA->pNext = pB->pNext;
58809   pB->pNext = pTmp;
58810   pTmp = pA->pPrev;
58811   pA->pPrev = pB->pPrev;
58812   pB->pPrev = pTmp;
58813   zTmp = pA->zSql;
58814   pA->zSql = pB->zSql;
58815   pB->zSql = zTmp;
58816   pB->isPrepareV2 = pA->isPrepareV2;
58817 }
58818
58819 #ifdef SQLITE_DEBUG
58820 /*
58821 ** Turn tracing on or off
58822 */
58823 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
58824   p->trace = trace;
58825 }
58826 #endif
58827
58828 /*
58829 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
58830 ** it was.
58831 **
58832 ** If an out-of-memory error occurs while resizing the array, return
58833 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
58834 ** unchanged (this is so that any opcodes already allocated can be 
58835 ** correctly deallocated along with the rest of the Vdbe).
58836 */
58837 static int growOpArray(Vdbe *p){
58838   VdbeOp *pNew;
58839   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
58840   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
58841   if( pNew ){
58842     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
58843     p->aOp = pNew;
58844   }
58845   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
58846 }
58847
58848 /*
58849 ** Add a new instruction to the list of instructions current in the
58850 ** VDBE.  Return the address of the new instruction.
58851 **
58852 ** Parameters:
58853 **
58854 **    p               Pointer to the VDBE
58855 **
58856 **    op              The opcode for this instruction
58857 **
58858 **    p1, p2, p3      Operands
58859 **
58860 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
58861 ** the sqlite3VdbeChangeP4() function to change the value of the P4
58862 ** operand.
58863 */
58864 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
58865   int i;
58866   VdbeOp *pOp;
58867
58868   i = p->nOp;
58869   assert( p->magic==VDBE_MAGIC_INIT );
58870   assert( op>0 && op<0xff );
58871   if( p->nOpAlloc<=i ){
58872     if( growOpArray(p) ){
58873       return 1;
58874     }
58875   }
58876   p->nOp++;
58877   pOp = &p->aOp[i];
58878   pOp->opcode = (u8)op;
58879   pOp->p5 = 0;
58880   pOp->p1 = p1;
58881   pOp->p2 = p2;
58882   pOp->p3 = p3;
58883   pOp->p4.p = 0;
58884   pOp->p4type = P4_NOTUSED;
58885 #ifdef SQLITE_DEBUG
58886   pOp->zComment = 0;
58887   if( p->db->flags & SQLITE_VdbeAddopTrace ){
58888     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
58889   }
58890 #endif
58891 #ifdef VDBE_PROFILE
58892   pOp->cycles = 0;
58893   pOp->cnt = 0;
58894 #endif
58895   return i;
58896 }
58897 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
58898   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
58899 }
58900 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
58901   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
58902 }
58903 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
58904   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
58905 }
58906
58907
58908 /*
58909 ** Add an opcode that includes the p4 value as a pointer.
58910 */
58911 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
58912   Vdbe *p,            /* Add the opcode to this VM */
58913   int op,             /* The new opcode */
58914   int p1,             /* The P1 operand */
58915   int p2,             /* The P2 operand */
58916   int p3,             /* The P3 operand */
58917   const char *zP4,    /* The P4 operand */
58918   int p4type          /* P4 operand type */
58919 ){
58920   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
58921   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
58922   return addr;
58923 }
58924
58925 /*
58926 ** Add an OP_ParseSchema opcode.  This routine is broken out from
58927 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
58928 ** as having been used.
58929 **
58930 ** The zWhere string must have been obtained from sqlite3_malloc().
58931 ** This routine will take ownership of the allocated memory.
58932 */
58933 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
58934   int j;
58935   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
58936   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
58937   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
58938 }
58939
58940 /*
58941 ** Add an opcode that includes the p4 value as an integer.
58942 */
58943 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
58944   Vdbe *p,            /* Add the opcode to this VM */
58945   int op,             /* The new opcode */
58946   int p1,             /* The P1 operand */
58947   int p2,             /* The P2 operand */
58948   int p3,             /* The P3 operand */
58949   int p4              /* The P4 operand as an integer */
58950 ){
58951   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
58952   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
58953   return addr;
58954 }
58955
58956 /*
58957 ** Create a new symbolic label for an instruction that has yet to be
58958 ** coded.  The symbolic label is really just a negative number.  The
58959 ** label can be used as the P2 value of an operation.  Later, when
58960 ** the label is resolved to a specific address, the VDBE will scan
58961 ** through its operation list and change all values of P2 which match
58962 ** the label into the resolved address.
58963 **
58964 ** The VDBE knows that a P2 value is a label because labels are
58965 ** always negative and P2 values are suppose to be non-negative.
58966 ** Hence, a negative P2 value is a label that has yet to be resolved.
58967 **
58968 ** Zero is returned if a malloc() fails.
58969 */
58970 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
58971   int i = p->nLabel++;
58972   assert( p->magic==VDBE_MAGIC_INIT );
58973   if( (i & (i-1))==0 ){
58974     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, 
58975                                        (i*2+1)*sizeof(p->aLabel[0]));
58976   }
58977   if( p->aLabel ){
58978     p->aLabel[i] = -1;
58979   }
58980   return -1-i;
58981 }
58982
58983 /*
58984 ** Resolve label "x" to be the address of the next instruction to
58985 ** be inserted.  The parameter "x" must have been obtained from
58986 ** a prior call to sqlite3VdbeMakeLabel().
58987 */
58988 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
58989   int j = -1-x;
58990   assert( p->magic==VDBE_MAGIC_INIT );
58991   assert( j>=0 && j<p->nLabel );
58992   if( p->aLabel ){
58993     p->aLabel[j] = p->nOp;
58994   }
58995 }
58996
58997 /*
58998 ** Mark the VDBE as one that can only be run one time.
58999 */
59000 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
59001   p->runOnlyOnce = 1;
59002 }
59003
59004 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
59005
59006 /*
59007 ** The following type and function are used to iterate through all opcodes
59008 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
59009 ** invoke directly or indirectly. It should be used as follows:
59010 **
59011 **   Op *pOp;
59012 **   VdbeOpIter sIter;
59013 **
59014 **   memset(&sIter, 0, sizeof(sIter));
59015 **   sIter.v = v;                            // v is of type Vdbe* 
59016 **   while( (pOp = opIterNext(&sIter)) ){
59017 **     // Do something with pOp
59018 **   }
59019 **   sqlite3DbFree(v->db, sIter.apSub);
59020 ** 
59021 */
59022 typedef struct VdbeOpIter VdbeOpIter;
59023 struct VdbeOpIter {
59024   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
59025   SubProgram **apSub;        /* Array of subprograms */
59026   int nSub;                  /* Number of entries in apSub */
59027   int iAddr;                 /* Address of next instruction to return */
59028   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
59029 };
59030 static Op *opIterNext(VdbeOpIter *p){
59031   Vdbe *v = p->v;
59032   Op *pRet = 0;
59033   Op *aOp;
59034   int nOp;
59035
59036   if( p->iSub<=p->nSub ){
59037
59038     if( p->iSub==0 ){
59039       aOp = v->aOp;
59040       nOp = v->nOp;
59041     }else{
59042       aOp = p->apSub[p->iSub-1]->aOp;
59043       nOp = p->apSub[p->iSub-1]->nOp;
59044     }
59045     assert( p->iAddr<nOp );
59046
59047     pRet = &aOp[p->iAddr];
59048     p->iAddr++;
59049     if( p->iAddr==nOp ){
59050       p->iSub++;
59051       p->iAddr = 0;
59052     }
59053   
59054     if( pRet->p4type==P4_SUBPROGRAM ){
59055       int nByte = (p->nSub+1)*sizeof(SubProgram*);
59056       int j;
59057       for(j=0; j<p->nSub; j++){
59058         if( p->apSub[j]==pRet->p4.pProgram ) break;
59059       }
59060       if( j==p->nSub ){
59061         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
59062         if( !p->apSub ){
59063           pRet = 0;
59064         }else{
59065           p->apSub[p->nSub++] = pRet->p4.pProgram;
59066         }
59067       }
59068     }
59069   }
59070
59071   return pRet;
59072 }
59073
59074 /*
59075 ** Check if the program stored in the VM associated with pParse may
59076 ** throw an ABORT exception (causing the statement, but not entire transaction
59077 ** to be rolled back). This condition is true if the main program or any
59078 ** sub-programs contains any of the following:
59079 **
59080 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
59081 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
59082 **   *  OP_Destroy
59083 **   *  OP_VUpdate
59084 **   *  OP_VRename
59085 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
59086 **
59087 ** Then check that the value of Parse.mayAbort is true if an
59088 ** ABORT may be thrown, or false otherwise. Return true if it does
59089 ** match, or false otherwise. This function is intended to be used as
59090 ** part of an assert statement in the compiler. Similar to:
59091 **
59092 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
59093 */
59094 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
59095   int hasAbort = 0;
59096   Op *pOp;
59097   VdbeOpIter sIter;
59098   memset(&sIter, 0, sizeof(sIter));
59099   sIter.v = v;
59100
59101   while( (pOp = opIterNext(&sIter))!=0 ){
59102     int opcode = pOp->opcode;
59103     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
59104 #ifndef SQLITE_OMIT_FOREIGN_KEY
59105      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
59106 #endif
59107      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
59108       && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
59109     ){
59110       hasAbort = 1;
59111       break;
59112     }
59113   }
59114   sqlite3DbFree(v->db, sIter.apSub);
59115
59116   /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
59117   ** If malloc failed, then the while() loop above may not have iterated
59118   ** through all opcodes and hasAbort may be set incorrectly. Return
59119   ** true for this case to prevent the assert() in the callers frame
59120   ** from failing.  */
59121   return ( v->db->mallocFailed || hasAbort==mayAbort );
59122 }
59123 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
59124
59125 /*
59126 ** Loop through the program looking for P2 values that are negative
59127 ** on jump instructions.  Each such value is a label.  Resolve the
59128 ** label by setting the P2 value to its correct non-zero value.
59129 **
59130 ** This routine is called once after all opcodes have been inserted.
59131 **
59132 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
59133 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
59134 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
59135 **
59136 ** The Op.opflags field is set on all opcodes.
59137 */
59138 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
59139   int i;
59140   int nMaxArgs = *pMaxFuncArgs;
59141   Op *pOp;
59142   int *aLabel = p->aLabel;
59143   p->readOnly = 1;
59144   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
59145     u8 opcode = pOp->opcode;
59146
59147     pOp->opflags = sqlite3OpcodeProperty[opcode];
59148     if( opcode==OP_Function || opcode==OP_AggStep ){
59149       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
59150     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
59151       p->readOnly = 0;
59152 #ifndef SQLITE_OMIT_VIRTUALTABLE
59153     }else if( opcode==OP_VUpdate ){
59154       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
59155     }else if( opcode==OP_VFilter ){
59156       int n;
59157       assert( p->nOp - i >= 3 );
59158       assert( pOp[-1].opcode==OP_Integer );
59159       n = pOp[-1].p1;
59160       if( n>nMaxArgs ) nMaxArgs = n;
59161 #endif
59162     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
59163       pOp->p4.xAdvance = sqlite3BtreeNext;
59164       pOp->p4type = P4_ADVANCE;
59165     }else if( opcode==OP_Prev ){
59166       pOp->p4.xAdvance = sqlite3BtreePrevious;
59167       pOp->p4type = P4_ADVANCE;
59168     }
59169
59170     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
59171       assert( -1-pOp->p2<p->nLabel );
59172       pOp->p2 = aLabel[-1-pOp->p2];
59173     }
59174   }
59175   sqlite3DbFree(p->db, p->aLabel);
59176   p->aLabel = 0;
59177
59178   *pMaxFuncArgs = nMaxArgs;
59179 }
59180
59181 /*
59182 ** Return the address of the next instruction to be inserted.
59183 */
59184 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
59185   assert( p->magic==VDBE_MAGIC_INIT );
59186   return p->nOp;
59187 }
59188
59189 /*
59190 ** This function returns a pointer to the array of opcodes associated with
59191 ** the Vdbe passed as the first argument. It is the callers responsibility
59192 ** to arrange for the returned array to be eventually freed using the 
59193 ** vdbeFreeOpArray() function.
59194 **
59195 ** Before returning, *pnOp is set to the number of entries in the returned
59196 ** array. Also, *pnMaxArg is set to the larger of its current value and 
59197 ** the number of entries in the Vdbe.apArg[] array required to execute the 
59198 ** returned program.
59199 */
59200 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
59201   VdbeOp *aOp = p->aOp;
59202   assert( aOp && !p->db->mallocFailed );
59203
59204   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
59205   assert( p->btreeMask==0 );
59206
59207   resolveP2Values(p, pnMaxArg);
59208   *pnOp = p->nOp;
59209   p->aOp = 0;
59210   return aOp;
59211 }
59212
59213 /*
59214 ** Add a whole list of operations to the operation stack.  Return the
59215 ** address of the first operation added.
59216 */
59217 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
59218   int addr;
59219   assert( p->magic==VDBE_MAGIC_INIT );
59220   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
59221     return 0;
59222   }
59223   addr = p->nOp;
59224   if( ALWAYS(nOp>0) ){
59225     int i;
59226     VdbeOpList const *pIn = aOp;
59227     for(i=0; i<nOp; i++, pIn++){
59228       int p2 = pIn->p2;
59229       VdbeOp *pOut = &p->aOp[i+addr];
59230       pOut->opcode = pIn->opcode;
59231       pOut->p1 = pIn->p1;
59232       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
59233         pOut->p2 = addr + ADDR(p2);
59234       }else{
59235         pOut->p2 = p2;
59236       }
59237       pOut->p3 = pIn->p3;
59238       pOut->p4type = P4_NOTUSED;
59239       pOut->p4.p = 0;
59240       pOut->p5 = 0;
59241 #ifdef SQLITE_DEBUG
59242       pOut->zComment = 0;
59243       if( p->db->flags & SQLITE_VdbeAddopTrace ){
59244         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
59245       }
59246 #endif
59247     }
59248     p->nOp += nOp;
59249   }
59250   return addr;
59251 }
59252
59253 /*
59254 ** Change the value of the P1 operand for a specific instruction.
59255 ** This routine is useful when a large program is loaded from a
59256 ** static array using sqlite3VdbeAddOpList but we want to make a
59257 ** few minor changes to the program.
59258 */
59259 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
59260   assert( p!=0 );
59261   if( ((u32)p->nOp)>addr ){
59262     p->aOp[addr].p1 = val;
59263   }
59264 }
59265
59266 /*
59267 ** Change the value of the P2 operand for a specific instruction.
59268 ** This routine is useful for setting a jump destination.
59269 */
59270 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
59271   assert( p!=0 );
59272   if( ((u32)p->nOp)>addr ){
59273     p->aOp[addr].p2 = val;
59274   }
59275 }
59276
59277 /*
59278 ** Change the value of the P3 operand for a specific instruction.
59279 */
59280 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
59281   assert( p!=0 );
59282   if( ((u32)p->nOp)>addr ){
59283     p->aOp[addr].p3 = val;
59284   }
59285 }
59286
59287 /*
59288 ** Change the value of the P5 operand for the most recently
59289 ** added operation.
59290 */
59291 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
59292   assert( p!=0 );
59293   if( p->aOp ){
59294     assert( p->nOp>0 );
59295     p->aOp[p->nOp-1].p5 = val;
59296   }
59297 }
59298
59299 /*
59300 ** Change the P2 operand of instruction addr so that it points to
59301 ** the address of the next instruction to be coded.
59302 */
59303 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
59304   assert( addr>=0 || p->db->mallocFailed );
59305   if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
59306 }
59307
59308
59309 /*
59310 ** If the input FuncDef structure is ephemeral, then free it.  If
59311 ** the FuncDef is not ephermal, then do nothing.
59312 */
59313 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
59314   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
59315     sqlite3DbFree(db, pDef);
59316   }
59317 }
59318
59319 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
59320
59321 /*
59322 ** Delete a P4 value if necessary.
59323 */
59324 static void freeP4(sqlite3 *db, int p4type, void *p4){
59325   if( p4 ){
59326     assert( db );
59327     switch( p4type ){
59328       case P4_REAL:
59329       case P4_INT64:
59330       case P4_DYNAMIC:
59331       case P4_KEYINFO:
59332       case P4_INTARRAY:
59333       case P4_KEYINFO_HANDOFF: {
59334         sqlite3DbFree(db, p4);
59335         break;
59336       }
59337       case P4_MPRINTF: {
59338         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
59339         break;
59340       }
59341       case P4_VDBEFUNC: {
59342         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
59343         freeEphemeralFunction(db, pVdbeFunc->pFunc);
59344         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
59345         sqlite3DbFree(db, pVdbeFunc);
59346         break;
59347       }
59348       case P4_FUNCDEF: {
59349         freeEphemeralFunction(db, (FuncDef*)p4);
59350         break;
59351       }
59352       case P4_MEM: {
59353         if( db->pnBytesFreed==0 ){
59354           sqlite3ValueFree((sqlite3_value*)p4);
59355         }else{
59356           Mem *p = (Mem*)p4;
59357           sqlite3DbFree(db, p->zMalloc);
59358           sqlite3DbFree(db, p);
59359         }
59360         break;
59361       }
59362       case P4_VTAB : {
59363         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
59364         break;
59365       }
59366     }
59367   }
59368 }
59369
59370 /*
59371 ** Free the space allocated for aOp and any p4 values allocated for the
59372 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
59373 ** nOp entries. 
59374 */
59375 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
59376   if( aOp ){
59377     Op *pOp;
59378     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
59379       freeP4(db, pOp->p4type, pOp->p4.p);
59380 #ifdef SQLITE_DEBUG
59381       sqlite3DbFree(db, pOp->zComment);
59382 #endif     
59383     }
59384   }
59385   sqlite3DbFree(db, aOp);
59386 }
59387
59388 /*
59389 ** Link the SubProgram object passed as the second argument into the linked
59390 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
59391 ** objects when the VM is no longer required.
59392 */
59393 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
59394   p->pNext = pVdbe->pProgram;
59395   pVdbe->pProgram = p;
59396 }
59397
59398 /*
59399 ** Change the opcode at addr into OP_Noop
59400 */
59401 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
59402   if( p->aOp ){
59403     VdbeOp *pOp = &p->aOp[addr];
59404     sqlite3 *db = p->db;
59405     freeP4(db, pOp->p4type, pOp->p4.p);
59406     memset(pOp, 0, sizeof(pOp[0]));
59407     pOp->opcode = OP_Noop;
59408   }
59409 }
59410
59411 /*
59412 ** Change the value of the P4 operand for a specific instruction.
59413 ** This routine is useful when a large program is loaded from a
59414 ** static array using sqlite3VdbeAddOpList but we want to make a
59415 ** few minor changes to the program.
59416 **
59417 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
59418 ** the string is made into memory obtained from sqlite3_malloc().
59419 ** A value of n==0 means copy bytes of zP4 up to and including the
59420 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
59421 **
59422 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
59423 ** A copy is made of the KeyInfo structure into memory obtained from
59424 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
59425 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
59426 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
59427 ** caller should not free the allocation, it will be freed when the Vdbe is
59428 ** finalized.
59429 ** 
59430 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
59431 ** to a string or structure that is guaranteed to exist for the lifetime of
59432 ** the Vdbe. In these cases we can just copy the pointer.
59433 **
59434 ** If addr<0 then change P4 on the most recently inserted instruction.
59435 */
59436 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
59437   Op *pOp;
59438   sqlite3 *db;
59439   assert( p!=0 );
59440   db = p->db;
59441   assert( p->magic==VDBE_MAGIC_INIT );
59442   if( p->aOp==0 || db->mallocFailed ){
59443     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
59444       freeP4(db, n, (void*)*(char**)&zP4);
59445     }
59446     return;
59447   }
59448   assert( p->nOp>0 );
59449   assert( addr<p->nOp );
59450   if( addr<0 ){
59451     addr = p->nOp - 1;
59452   }
59453   pOp = &p->aOp[addr];
59454   assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
59455   freeP4(db, pOp->p4type, pOp->p4.p);
59456   pOp->p4.p = 0;
59457   if( n==P4_INT32 ){
59458     /* Note: this cast is safe, because the origin data point was an int
59459     ** that was cast to a (const char *). */
59460     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
59461     pOp->p4type = P4_INT32;
59462   }else if( zP4==0 ){
59463     pOp->p4.p = 0;
59464     pOp->p4type = P4_NOTUSED;
59465   }else if( n==P4_KEYINFO ){
59466     KeyInfo *pKeyInfo;
59467     int nField, nByte;
59468
59469     nField = ((KeyInfo*)zP4)->nField;
59470     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
59471     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
59472     pOp->p4.pKeyInfo = pKeyInfo;
59473     if( pKeyInfo ){
59474       u8 *aSortOrder;
59475       memcpy((char*)pKeyInfo, zP4, nByte - nField);
59476       aSortOrder = pKeyInfo->aSortOrder;
59477       assert( aSortOrder!=0 );
59478       pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
59479       memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
59480       pOp->p4type = P4_KEYINFO;
59481     }else{
59482       p->db->mallocFailed = 1;
59483       pOp->p4type = P4_NOTUSED;
59484     }
59485   }else if( n==P4_KEYINFO_HANDOFF ){
59486     pOp->p4.p = (void*)zP4;
59487     pOp->p4type = P4_KEYINFO;
59488   }else if( n==P4_VTAB ){
59489     pOp->p4.p = (void*)zP4;
59490     pOp->p4type = P4_VTAB;
59491     sqlite3VtabLock((VTable *)zP4);
59492     assert( ((VTable *)zP4)->db==p->db );
59493   }else if( n<0 ){
59494     pOp->p4.p = (void*)zP4;
59495     pOp->p4type = (signed char)n;
59496   }else{
59497     if( n==0 ) n = sqlite3Strlen30(zP4);
59498     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
59499     pOp->p4type = P4_DYNAMIC;
59500   }
59501 }
59502
59503 #ifndef NDEBUG
59504 /*
59505 ** Change the comment on the most recently coded instruction.  Or
59506 ** insert a No-op and add the comment to that new instruction.  This
59507 ** makes the code easier to read during debugging.  None of this happens
59508 ** in a production build.
59509 */
59510 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
59511   assert( p->nOp>0 || p->aOp==0 );
59512   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
59513   if( p->nOp ){
59514     assert( p->aOp );
59515     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
59516     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
59517   }
59518 }
59519 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
59520   va_list ap;
59521   if( p ){
59522     va_start(ap, zFormat);
59523     vdbeVComment(p, zFormat, ap);
59524     va_end(ap);
59525   }
59526 }
59527 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
59528   va_list ap;
59529   if( p ){
59530     sqlite3VdbeAddOp0(p, OP_Noop);
59531     va_start(ap, zFormat);
59532     vdbeVComment(p, zFormat, ap);
59533     va_end(ap);
59534   }
59535 }
59536 #endif  /* NDEBUG */
59537
59538 /*
59539 ** Return the opcode for a given address.  If the address is -1, then
59540 ** return the most recently inserted opcode.
59541 **
59542 ** If a memory allocation error has occurred prior to the calling of this
59543 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
59544 ** is readable but not writable, though it is cast to a writable value.
59545 ** The return of a dummy opcode allows the call to continue functioning
59546 ** after a OOM fault without having to check to see if the return from 
59547 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
59548 ** dummy will never be written to.  This is verified by code inspection and
59549 ** by running with Valgrind.
59550 **
59551 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
59552 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
59553 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
59554 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
59555 ** having to double-check to make sure that the result is non-negative. But
59556 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
59557 ** check the value of p->nOp-1 before continuing.
59558 */
59559 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
59560   /* C89 specifies that the constant "dummy" will be initialized to all
59561   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
59562   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
59563   assert( p->magic==VDBE_MAGIC_INIT );
59564   if( addr<0 ){
59565 #ifdef SQLITE_OMIT_TRACE
59566     if( p->nOp==0 ) return (VdbeOp*)&dummy;
59567 #endif
59568     addr = p->nOp - 1;
59569   }
59570   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
59571   if( p->db->mallocFailed ){
59572     return (VdbeOp*)&dummy;
59573   }else{
59574     return &p->aOp[addr];
59575   }
59576 }
59577
59578 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
59579      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
59580 /*
59581 ** Compute a string that describes the P4 parameter for an opcode.
59582 ** Use zTemp for any required temporary buffer space.
59583 */
59584 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
59585   char *zP4 = zTemp;
59586   assert( nTemp>=20 );
59587   switch( pOp->p4type ){
59588     case P4_KEYINFO_STATIC:
59589     case P4_KEYINFO: {
59590       int i, j;
59591       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
59592       assert( pKeyInfo->aSortOrder!=0 );
59593       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
59594       i = sqlite3Strlen30(zTemp);
59595       for(j=0; j<pKeyInfo->nField; j++){
59596         CollSeq *pColl = pKeyInfo->aColl[j];
59597         const char *zColl = pColl ? pColl->zName : "nil";
59598         int n = sqlite3Strlen30(zColl);
59599         if( i+n>nTemp-6 ){
59600           memcpy(&zTemp[i],",...",4);
59601           break;
59602         }
59603         zTemp[i++] = ',';
59604         if( pKeyInfo->aSortOrder[j] ){
59605           zTemp[i++] = '-';
59606         }
59607         memcpy(&zTemp[i], zColl, n+1);
59608         i += n;
59609       }
59610       zTemp[i++] = ')';
59611       zTemp[i] = 0;
59612       assert( i<nTemp );
59613       break;
59614     }
59615     case P4_COLLSEQ: {
59616       CollSeq *pColl = pOp->p4.pColl;
59617       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
59618       break;
59619     }
59620     case P4_FUNCDEF: {
59621       FuncDef *pDef = pOp->p4.pFunc;
59622       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
59623       break;
59624     }
59625     case P4_INT64: {
59626       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
59627       break;
59628     }
59629     case P4_INT32: {
59630       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
59631       break;
59632     }
59633     case P4_REAL: {
59634       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
59635       break;
59636     }
59637     case P4_MEM: {
59638       Mem *pMem = pOp->p4.pMem;
59639       if( pMem->flags & MEM_Str ){
59640         zP4 = pMem->z;
59641       }else if( pMem->flags & MEM_Int ){
59642         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
59643       }else if( pMem->flags & MEM_Real ){
59644         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
59645       }else if( pMem->flags & MEM_Null ){
59646         sqlite3_snprintf(nTemp, zTemp, "NULL");
59647       }else{
59648         assert( pMem->flags & MEM_Blob );
59649         zP4 = "(blob)";
59650       }
59651       break;
59652     }
59653 #ifndef SQLITE_OMIT_VIRTUALTABLE
59654     case P4_VTAB: {
59655       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
59656       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
59657       break;
59658     }
59659 #endif
59660     case P4_INTARRAY: {
59661       sqlite3_snprintf(nTemp, zTemp, "intarray");
59662       break;
59663     }
59664     case P4_SUBPROGRAM: {
59665       sqlite3_snprintf(nTemp, zTemp, "program");
59666       break;
59667     }
59668     case P4_ADVANCE: {
59669       zTemp[0] = 0;
59670       break;
59671     }
59672     default: {
59673       zP4 = pOp->p4.z;
59674       if( zP4==0 ){
59675         zP4 = zTemp;
59676         zTemp[0] = 0;
59677       }
59678     }
59679   }
59680   assert( zP4!=0 );
59681   return zP4;
59682 }
59683 #endif
59684
59685 /*
59686 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
59687 **
59688 ** The prepared statements need to know in advance the complete set of
59689 ** attached databases that will be use.  A mask of these databases
59690 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
59691 ** p->btreeMask of databases that will require a lock.
59692 */
59693 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
59694   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
59695   assert( i<(int)sizeof(p->btreeMask)*8 );
59696   p->btreeMask |= ((yDbMask)1)<<i;
59697   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
59698     p->lockMask |= ((yDbMask)1)<<i;
59699   }
59700 }
59701
59702 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
59703 /*
59704 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
59705 ** this routine obtains the mutex associated with each BtShared structure
59706 ** that may be accessed by the VM passed as an argument. In doing so it also
59707 ** sets the BtShared.db member of each of the BtShared structures, ensuring
59708 ** that the correct busy-handler callback is invoked if required.
59709 **
59710 ** If SQLite is not threadsafe but does support shared-cache mode, then
59711 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
59712 ** of all of BtShared structures accessible via the database handle 
59713 ** associated with the VM.
59714 **
59715 ** If SQLite is not threadsafe and does not support shared-cache mode, this
59716 ** function is a no-op.
59717 **
59718 ** The p->btreeMask field is a bitmask of all btrees that the prepared 
59719 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
59720 ** corresponding to btrees that use shared cache.  Then the runtime of
59721 ** this routine is N*N.  But as N is rarely more than 1, this should not
59722 ** be a problem.
59723 */
59724 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
59725   int i;
59726   yDbMask mask;
59727   sqlite3 *db;
59728   Db *aDb;
59729   int nDb;
59730   if( p->lockMask==0 ) return;  /* The common case */
59731   db = p->db;
59732   aDb = db->aDb;
59733   nDb = db->nDb;
59734   for(i=0, mask=1; i<nDb; i++, mask += mask){
59735     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
59736       sqlite3BtreeEnter(aDb[i].pBt);
59737     }
59738   }
59739 }
59740 #endif
59741
59742 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
59743 /*
59744 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
59745 */
59746 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
59747   int i;
59748   yDbMask mask;
59749   sqlite3 *db;
59750   Db *aDb;
59751   int nDb;
59752   if( p->lockMask==0 ) return;  /* The common case */
59753   db = p->db;
59754   aDb = db->aDb;
59755   nDb = db->nDb;
59756   for(i=0, mask=1; i<nDb; i++, mask += mask){
59757     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
59758       sqlite3BtreeLeave(aDb[i].pBt);
59759     }
59760   }
59761 }
59762 #endif
59763
59764 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
59765 /*
59766 ** Print a single opcode.  This routine is used for debugging only.
59767 */
59768 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
59769   char *zP4;
59770   char zPtr[50];
59771   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
59772   if( pOut==0 ) pOut = stdout;
59773   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
59774   fprintf(pOut, zFormat1, pc, 
59775       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
59776 #ifdef SQLITE_DEBUG
59777       pOp->zComment ? pOp->zComment : ""
59778 #else
59779       ""
59780 #endif
59781   );
59782   fflush(pOut);
59783 }
59784 #endif
59785
59786 /*
59787 ** Release an array of N Mem elements
59788 */
59789 static void releaseMemArray(Mem *p, int N){
59790   if( p && N ){
59791     Mem *pEnd;
59792     sqlite3 *db = p->db;
59793     u8 malloc_failed = db->mallocFailed;
59794     if( db->pnBytesFreed ){
59795       for(pEnd=&p[N]; p<pEnd; p++){
59796         sqlite3DbFree(db, p->zMalloc);
59797       }
59798       return;
59799     }
59800     for(pEnd=&p[N]; p<pEnd; p++){
59801       assert( (&p[1])==pEnd || p[0].db==p[1].db );
59802
59803       /* This block is really an inlined version of sqlite3VdbeMemRelease()
59804       ** that takes advantage of the fact that the memory cell value is 
59805       ** being set to NULL after releasing any dynamic resources.
59806       **
59807       ** The justification for duplicating code is that according to 
59808       ** callgrind, this causes a certain test case to hit the CPU 4.7 
59809       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
59810       ** sqlite3MemRelease() were called from here. With -O2, this jumps
59811       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
59812       ** with no indexes using a single prepared INSERT statement, bind() 
59813       ** and reset(). Inserts are grouped into a transaction.
59814       */
59815       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
59816         sqlite3VdbeMemRelease(p);
59817       }else if( p->zMalloc ){
59818         sqlite3DbFree(db, p->zMalloc);
59819         p->zMalloc = 0;
59820       }
59821
59822       p->flags = MEM_Invalid;
59823     }
59824     db->mallocFailed = malloc_failed;
59825   }
59826 }
59827
59828 /*
59829 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
59830 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
59831 */
59832 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
59833   int i;
59834   Mem *aMem = VdbeFrameMem(p);
59835   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
59836   for(i=0; i<p->nChildCsr; i++){
59837     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
59838   }
59839   releaseMemArray(aMem, p->nChildMem);
59840   sqlite3DbFree(p->v->db, p);
59841 }
59842
59843 #ifndef SQLITE_OMIT_EXPLAIN
59844 /*
59845 ** Give a listing of the program in the virtual machine.
59846 **
59847 ** The interface is the same as sqlite3VdbeExec().  But instead of
59848 ** running the code, it invokes the callback once for each instruction.
59849 ** This feature is used to implement "EXPLAIN".
59850 **
59851 ** When p->explain==1, each instruction is listed.  When
59852 ** p->explain==2, only OP_Explain instructions are listed and these
59853 ** are shown in a different format.  p->explain==2 is used to implement
59854 ** EXPLAIN QUERY PLAN.
59855 **
59856 ** When p->explain==1, first the main program is listed, then each of
59857 ** the trigger subprograms are listed one by one.
59858 */
59859 SQLITE_PRIVATE int sqlite3VdbeList(
59860   Vdbe *p                   /* The VDBE */
59861 ){
59862   int nRow;                            /* Stop when row count reaches this */
59863   int nSub = 0;                        /* Number of sub-vdbes seen so far */
59864   SubProgram **apSub = 0;              /* Array of sub-vdbes */
59865   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
59866   sqlite3 *db = p->db;                 /* The database connection */
59867   int i;                               /* Loop counter */
59868   int rc = SQLITE_OK;                  /* Return code */
59869   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
59870
59871   assert( p->explain );
59872   assert( p->magic==VDBE_MAGIC_RUN );
59873   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
59874
59875   /* Even though this opcode does not use dynamic strings for
59876   ** the result, result columns may become dynamic if the user calls
59877   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
59878   */
59879   releaseMemArray(pMem, 8);
59880   p->pResultSet = 0;
59881
59882   if( p->rc==SQLITE_NOMEM ){
59883     /* This happens if a malloc() inside a call to sqlite3_column_text() or
59884     ** sqlite3_column_text16() failed.  */
59885     db->mallocFailed = 1;
59886     return SQLITE_ERROR;
59887   }
59888
59889   /* When the number of output rows reaches nRow, that means the
59890   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
59891   ** nRow is the sum of the number of rows in the main program, plus
59892   ** the sum of the number of rows in all trigger subprograms encountered
59893   ** so far.  The nRow value will increase as new trigger subprograms are
59894   ** encountered, but p->pc will eventually catch up to nRow.
59895   */
59896   nRow = p->nOp;
59897   if( p->explain==1 ){
59898     /* The first 8 memory cells are used for the result set.  So we will
59899     ** commandeer the 9th cell to use as storage for an array of pointers
59900     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
59901     ** cells.  */
59902     assert( p->nMem>9 );
59903     pSub = &p->aMem[9];
59904     if( pSub->flags&MEM_Blob ){
59905       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
59906       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
59907       nSub = pSub->n/sizeof(Vdbe*);
59908       apSub = (SubProgram **)pSub->z;
59909     }
59910     for(i=0; i<nSub; i++){
59911       nRow += apSub[i]->nOp;
59912     }
59913   }
59914
59915   do{
59916     i = p->pc++;
59917   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
59918   if( i>=nRow ){
59919     p->rc = SQLITE_OK;
59920     rc = SQLITE_DONE;
59921   }else if( db->u1.isInterrupted ){
59922     p->rc = SQLITE_INTERRUPT;
59923     rc = SQLITE_ERROR;
59924     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
59925   }else{
59926     char *z;
59927     Op *pOp;
59928     if( i<p->nOp ){
59929       /* The output line number is small enough that we are still in the
59930       ** main program. */
59931       pOp = &p->aOp[i];
59932     }else{
59933       /* We are currently listing subprograms.  Figure out which one and
59934       ** pick up the appropriate opcode. */
59935       int j;
59936       i -= p->nOp;
59937       for(j=0; i>=apSub[j]->nOp; j++){
59938         i -= apSub[j]->nOp;
59939       }
59940       pOp = &apSub[j]->aOp[i];
59941     }
59942     if( p->explain==1 ){
59943       pMem->flags = MEM_Int;
59944       pMem->type = SQLITE_INTEGER;
59945       pMem->u.i = i;                                /* Program counter */
59946       pMem++;
59947   
59948       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
59949       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
59950       assert( pMem->z!=0 );
59951       pMem->n = sqlite3Strlen30(pMem->z);
59952       pMem->type = SQLITE_TEXT;
59953       pMem->enc = SQLITE_UTF8;
59954       pMem++;
59955
59956       /* When an OP_Program opcode is encounter (the only opcode that has
59957       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
59958       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
59959       ** has not already been seen.
59960       */
59961       if( pOp->p4type==P4_SUBPROGRAM ){
59962         int nByte = (nSub+1)*sizeof(SubProgram*);
59963         int j;
59964         for(j=0; j<nSub; j++){
59965           if( apSub[j]==pOp->p4.pProgram ) break;
59966         }
59967         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
59968           apSub = (SubProgram **)pSub->z;
59969           apSub[nSub++] = pOp->p4.pProgram;
59970           pSub->flags |= MEM_Blob;
59971           pSub->n = nSub*sizeof(SubProgram*);
59972         }
59973       }
59974     }
59975
59976     pMem->flags = MEM_Int;
59977     pMem->u.i = pOp->p1;                          /* P1 */
59978     pMem->type = SQLITE_INTEGER;
59979     pMem++;
59980
59981     pMem->flags = MEM_Int;
59982     pMem->u.i = pOp->p2;                          /* P2 */
59983     pMem->type = SQLITE_INTEGER;
59984     pMem++;
59985
59986     pMem->flags = MEM_Int;
59987     pMem->u.i = pOp->p3;                          /* P3 */
59988     pMem->type = SQLITE_INTEGER;
59989     pMem++;
59990
59991     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
59992       assert( p->db->mallocFailed );
59993       return SQLITE_ERROR;
59994     }
59995     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
59996     z = displayP4(pOp, pMem->z, 32);
59997     if( z!=pMem->z ){
59998       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
59999     }else{
60000       assert( pMem->z!=0 );
60001       pMem->n = sqlite3Strlen30(pMem->z);
60002       pMem->enc = SQLITE_UTF8;
60003     }
60004     pMem->type = SQLITE_TEXT;
60005     pMem++;
60006
60007     if( p->explain==1 ){
60008       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
60009         assert( p->db->mallocFailed );
60010         return SQLITE_ERROR;
60011       }
60012       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
60013       pMem->n = 2;
60014       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
60015       pMem->type = SQLITE_TEXT;
60016       pMem->enc = SQLITE_UTF8;
60017       pMem++;
60018   
60019 #ifdef SQLITE_DEBUG
60020       if( pOp->zComment ){
60021         pMem->flags = MEM_Str|MEM_Term;
60022         pMem->z = pOp->zComment;
60023         pMem->n = sqlite3Strlen30(pMem->z);
60024         pMem->enc = SQLITE_UTF8;
60025         pMem->type = SQLITE_TEXT;
60026       }else
60027 #endif
60028       {
60029         pMem->flags = MEM_Null;                       /* Comment */
60030         pMem->type = SQLITE_NULL;
60031       }
60032     }
60033
60034     p->nResColumn = 8 - 4*(p->explain-1);
60035     p->pResultSet = &p->aMem[1];
60036     p->rc = SQLITE_OK;
60037     rc = SQLITE_ROW;
60038   }
60039   return rc;
60040 }
60041 #endif /* SQLITE_OMIT_EXPLAIN */
60042
60043 #ifdef SQLITE_DEBUG
60044 /*
60045 ** Print the SQL that was used to generate a VDBE program.
60046 */
60047 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
60048   int nOp = p->nOp;
60049   VdbeOp *pOp;
60050   if( nOp<1 ) return;
60051   pOp = &p->aOp[0];
60052   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
60053     const char *z = pOp->p4.z;
60054     while( sqlite3Isspace(*z) ) z++;
60055     printf("SQL: [%s]\n", z);
60056   }
60057 }
60058 #endif
60059
60060 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
60061 /*
60062 ** Print an IOTRACE message showing SQL content.
60063 */
60064 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
60065   int nOp = p->nOp;
60066   VdbeOp *pOp;
60067   if( sqlite3IoTrace==0 ) return;
60068   if( nOp<1 ) return;
60069   pOp = &p->aOp[0];
60070   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
60071     int i, j;
60072     char z[1000];
60073     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
60074     for(i=0; sqlite3Isspace(z[i]); i++){}
60075     for(j=0; z[i]; i++){
60076       if( sqlite3Isspace(z[i]) ){
60077         if( z[i-1]!=' ' ){
60078           z[j++] = ' ';
60079         }
60080       }else{
60081         z[j++] = z[i];
60082       }
60083     }
60084     z[j] = 0;
60085     sqlite3IoTrace("SQL %s\n", z);
60086   }
60087 }
60088 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
60089
60090 /*
60091 ** Allocate space from a fixed size buffer and return a pointer to
60092 ** that space.  If insufficient space is available, return NULL.
60093 **
60094 ** The pBuf parameter is the initial value of a pointer which will
60095 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
60096 ** NULL, it means that memory space has already been allocated and that
60097 ** this routine should not allocate any new memory.  When pBuf is not
60098 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
60099 ** is NULL.
60100 **
60101 ** nByte is the number of bytes of space needed.
60102 **
60103 ** *ppFrom points to available space and pEnd points to the end of the
60104 ** available space.  When space is allocated, *ppFrom is advanced past
60105 ** the end of the allocated space.
60106 **
60107 ** *pnByte is a counter of the number of bytes of space that have failed
60108 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
60109 ** request, then increment *pnByte by the amount of the request.
60110 */
60111 static void *allocSpace(
60112   void *pBuf,          /* Where return pointer will be stored */
60113   int nByte,           /* Number of bytes to allocate */
60114   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
60115   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
60116   int *pnByte          /* If allocation cannot be made, increment *pnByte */
60117 ){
60118   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
60119   if( pBuf ) return pBuf;
60120   nByte = ROUND8(nByte);
60121   if( &(*ppFrom)[nByte] <= pEnd ){
60122     pBuf = (void*)*ppFrom;
60123     *ppFrom += nByte;
60124   }else{
60125     *pnByte += nByte;
60126   }
60127   return pBuf;
60128 }
60129
60130 /*
60131 ** Rewind the VDBE back to the beginning in preparation for
60132 ** running it.
60133 */
60134 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
60135 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
60136   int i;
60137 #endif
60138   assert( p!=0 );
60139   assert( p->magic==VDBE_MAGIC_INIT );
60140
60141   /* There should be at least one opcode.
60142   */
60143   assert( p->nOp>0 );
60144
60145   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
60146   p->magic = VDBE_MAGIC_RUN;
60147
60148 #ifdef SQLITE_DEBUG
60149   for(i=1; i<p->nMem; i++){
60150     assert( p->aMem[i].db==p->db );
60151   }
60152 #endif
60153   p->pc = -1;
60154   p->rc = SQLITE_OK;
60155   p->errorAction = OE_Abort;
60156   p->magic = VDBE_MAGIC_RUN;
60157   p->nChange = 0;
60158   p->cacheCtr = 1;
60159   p->minWriteFileFormat = 255;
60160   p->iStatement = 0;
60161   p->nFkConstraint = 0;
60162 #ifdef VDBE_PROFILE
60163   for(i=0; i<p->nOp; i++){
60164     p->aOp[i].cnt = 0;
60165     p->aOp[i].cycles = 0;
60166   }
60167 #endif
60168 }
60169
60170 /*
60171 ** Prepare a virtual machine for execution for the first time after
60172 ** creating the virtual machine.  This involves things such
60173 ** as allocating stack space and initializing the program counter.
60174 ** After the VDBE has be prepped, it can be executed by one or more
60175 ** calls to sqlite3VdbeExec().  
60176 **
60177 ** This function may be called exact once on a each virtual machine.
60178 ** After this routine is called the VM has been "packaged" and is ready
60179 ** to run.  After this routine is called, futher calls to 
60180 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
60181 ** the Vdbe from the Parse object that helped generate it so that the
60182 ** the Vdbe becomes an independent entity and the Parse object can be
60183 ** destroyed.
60184 **
60185 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
60186 ** to its initial state after it has been run.
60187 */
60188 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
60189   Vdbe *p,                       /* The VDBE */
60190   Parse *pParse                  /* Parsing context */
60191 ){
60192   sqlite3 *db;                   /* The database connection */
60193   int nVar;                      /* Number of parameters */
60194   int nMem;                      /* Number of VM memory registers */
60195   int nCursor;                   /* Number of cursors required */
60196   int nArg;                      /* Number of arguments in subprograms */
60197   int nOnce;                     /* Number of OP_Once instructions */
60198   int n;                         /* Loop counter */
60199   u8 *zCsr;                      /* Memory available for allocation */
60200   u8 *zEnd;                      /* First byte past allocated memory */
60201   int nByte;                     /* How much extra memory is needed */
60202
60203   assert( p!=0 );
60204   assert( p->nOp>0 );
60205   assert( pParse!=0 );
60206   assert( p->magic==VDBE_MAGIC_INIT );
60207   db = p->db;
60208   assert( db->mallocFailed==0 );
60209   nVar = pParse->nVar;
60210   nMem = pParse->nMem;
60211   nCursor = pParse->nTab;
60212   nArg = pParse->nMaxArg;
60213   nOnce = pParse->nOnce;
60214   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
60215   
60216   /* For each cursor required, also allocate a memory cell. Memory
60217   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
60218   ** the vdbe program. Instead they are used to allocate space for
60219   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
60220   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
60221   ** stores the blob of memory associated with cursor 1, etc.
60222   **
60223   ** See also: allocateCursor().
60224   */
60225   nMem += nCursor;
60226
60227   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
60228   ** an array to marshal SQL function arguments in.
60229   */
60230   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
60231   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
60232
60233   resolveP2Values(p, &nArg);
60234   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
60235   if( pParse->explain && nMem<10 ){
60236     nMem = 10;
60237   }
60238   memset(zCsr, 0, zEnd-zCsr);
60239   zCsr += (zCsr - (u8*)0)&7;
60240   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
60241   p->expired = 0;
60242
60243   /* Memory for registers, parameters, cursor, etc, is allocated in two
60244   ** passes.  On the first pass, we try to reuse unused space at the 
60245   ** end of the opcode array.  If we are unable to satisfy all memory
60246   ** requirements by reusing the opcode array tail, then the second
60247   ** pass will fill in the rest using a fresh allocation.  
60248   **
60249   ** This two-pass approach that reuses as much memory as possible from
60250   ** the leftover space at the end of the opcode array can significantly
60251   ** reduce the amount of memory held by a prepared statement.
60252   */
60253   do {
60254     nByte = 0;
60255     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
60256     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
60257     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
60258     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
60259     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
60260                           &zCsr, zEnd, &nByte);
60261     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
60262     if( nByte ){
60263       p->pFree = sqlite3DbMallocZero(db, nByte);
60264     }
60265     zCsr = p->pFree;
60266     zEnd = &zCsr[nByte];
60267   }while( nByte && !db->mallocFailed );
60268
60269   p->nCursor = nCursor;
60270   p->nOnceFlag = nOnce;
60271   if( p->aVar ){
60272     p->nVar = (ynVar)nVar;
60273     for(n=0; n<nVar; n++){
60274       p->aVar[n].flags = MEM_Null;
60275       p->aVar[n].db = db;
60276     }
60277   }
60278   if( p->azVar ){
60279     p->nzVar = pParse->nzVar;
60280     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
60281     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
60282   }
60283   if( p->aMem ){
60284     p->aMem--;                      /* aMem[] goes from 1..nMem */
60285     p->nMem = nMem;                 /*       not from 0..nMem-1 */
60286     for(n=1; n<=nMem; n++){
60287       p->aMem[n].flags = MEM_Invalid;
60288       p->aMem[n].db = db;
60289     }
60290   }
60291   p->explain = pParse->explain;
60292   sqlite3VdbeRewind(p);
60293 }
60294
60295 /*
60296 ** Close a VDBE cursor and release all the resources that cursor 
60297 ** happens to hold.
60298 */
60299 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
60300   if( pCx==0 ){
60301     return;
60302   }
60303   sqlite3VdbeSorterClose(p->db, pCx);
60304   if( pCx->pBt ){
60305     sqlite3BtreeClose(pCx->pBt);
60306     /* The pCx->pCursor will be close automatically, if it exists, by
60307     ** the call above. */
60308   }else if( pCx->pCursor ){
60309     sqlite3BtreeCloseCursor(pCx->pCursor);
60310   }
60311 #ifndef SQLITE_OMIT_VIRTUALTABLE
60312   if( pCx->pVtabCursor ){
60313     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
60314     const sqlite3_module *pModule = pCx->pModule;
60315     p->inVtabMethod = 1;
60316     pModule->xClose(pVtabCursor);
60317     p->inVtabMethod = 0;
60318   }
60319 #endif
60320 }
60321
60322 /*
60323 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
60324 ** is used, for example, when a trigger sub-program is halted to restore
60325 ** control to the main program.
60326 */
60327 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
60328   Vdbe *v = pFrame->v;
60329   v->aOnceFlag = pFrame->aOnceFlag;
60330   v->nOnceFlag = pFrame->nOnceFlag;
60331   v->aOp = pFrame->aOp;
60332   v->nOp = pFrame->nOp;
60333   v->aMem = pFrame->aMem;
60334   v->nMem = pFrame->nMem;
60335   v->apCsr = pFrame->apCsr;
60336   v->nCursor = pFrame->nCursor;
60337   v->db->lastRowid = pFrame->lastRowid;
60338   v->nChange = pFrame->nChange;
60339   return pFrame->pc;
60340 }
60341
60342 /*
60343 ** Close all cursors.
60344 **
60345 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
60346 ** cell array. This is necessary as the memory cell array may contain
60347 ** pointers to VdbeFrame objects, which may in turn contain pointers to
60348 ** open cursors.
60349 */
60350 static void closeAllCursors(Vdbe *p){
60351   if( p->pFrame ){
60352     VdbeFrame *pFrame;
60353     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
60354     sqlite3VdbeFrameRestore(pFrame);
60355   }
60356   p->pFrame = 0;
60357   p->nFrame = 0;
60358
60359   if( p->apCsr ){
60360     int i;
60361     for(i=0; i<p->nCursor; i++){
60362       VdbeCursor *pC = p->apCsr[i];
60363       if( pC ){
60364         sqlite3VdbeFreeCursor(p, pC);
60365         p->apCsr[i] = 0;
60366       }
60367     }
60368   }
60369   if( p->aMem ){
60370     releaseMemArray(&p->aMem[1], p->nMem);
60371   }
60372   while( p->pDelFrame ){
60373     VdbeFrame *pDel = p->pDelFrame;
60374     p->pDelFrame = pDel->pParent;
60375     sqlite3VdbeFrameDelete(pDel);
60376   }
60377 }
60378
60379 /*
60380 ** Clean up the VM after execution.
60381 **
60382 ** This routine will automatically close any cursors, lists, and/or
60383 ** sorters that were left open.  It also deletes the values of
60384 ** variables in the aVar[] array.
60385 */
60386 static void Cleanup(Vdbe *p){
60387   sqlite3 *db = p->db;
60388
60389 #ifdef SQLITE_DEBUG
60390   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
60391   ** Vdbe.aMem[] arrays have already been cleaned up.  */
60392   int i;
60393   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
60394   if( p->aMem ){
60395     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
60396   }
60397 #endif
60398
60399   sqlite3DbFree(db, p->zErrMsg);
60400   p->zErrMsg = 0;
60401   p->pResultSet = 0;
60402 }
60403
60404 /*
60405 ** Set the number of result columns that will be returned by this SQL
60406 ** statement. This is now set at compile time, rather than during
60407 ** execution of the vdbe program so that sqlite3_column_count() can
60408 ** be called on an SQL statement before sqlite3_step().
60409 */
60410 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
60411   Mem *pColName;
60412   int n;
60413   sqlite3 *db = p->db;
60414
60415   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
60416   sqlite3DbFree(db, p->aColName);
60417   n = nResColumn*COLNAME_N;
60418   p->nResColumn = (u16)nResColumn;
60419   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
60420   if( p->aColName==0 ) return;
60421   while( n-- > 0 ){
60422     pColName->flags = MEM_Null;
60423     pColName->db = p->db;
60424     pColName++;
60425   }
60426 }
60427
60428 /*
60429 ** Set the name of the idx'th column to be returned by the SQL statement.
60430 ** zName must be a pointer to a nul terminated string.
60431 **
60432 ** This call must be made after a call to sqlite3VdbeSetNumCols().
60433 **
60434 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
60435 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
60436 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
60437 */
60438 SQLITE_PRIVATE int sqlite3VdbeSetColName(
60439   Vdbe *p,                         /* Vdbe being configured */
60440   int idx,                         /* Index of column zName applies to */
60441   int var,                         /* One of the COLNAME_* constants */
60442   const char *zName,               /* Pointer to buffer containing name */
60443   void (*xDel)(void*)              /* Memory management strategy for zName */
60444 ){
60445   int rc;
60446   Mem *pColName;
60447   assert( idx<p->nResColumn );
60448   assert( var<COLNAME_N );
60449   if( p->db->mallocFailed ){
60450     assert( !zName || xDel!=SQLITE_DYNAMIC );
60451     return SQLITE_NOMEM;
60452   }
60453   assert( p->aColName!=0 );
60454   pColName = &(p->aColName[idx+var*p->nResColumn]);
60455   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
60456   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
60457   return rc;
60458 }
60459
60460 /*
60461 ** A read or write transaction may or may not be active on database handle
60462 ** db. If a transaction is active, commit it. If there is a
60463 ** write-transaction spanning more than one database file, this routine
60464 ** takes care of the master journal trickery.
60465 */
60466 static int vdbeCommit(sqlite3 *db, Vdbe *p){
60467   int i;
60468   int nTrans = 0;  /* Number of databases with an active write-transaction */
60469   int rc = SQLITE_OK;
60470   int needXcommit = 0;
60471
60472 #ifdef SQLITE_OMIT_VIRTUALTABLE
60473   /* With this option, sqlite3VtabSync() is defined to be simply 
60474   ** SQLITE_OK so p is not used. 
60475   */
60476   UNUSED_PARAMETER(p);
60477 #endif
60478
60479   /* Before doing anything else, call the xSync() callback for any
60480   ** virtual module tables written in this transaction. This has to
60481   ** be done before determining whether a master journal file is 
60482   ** required, as an xSync() callback may add an attached database
60483   ** to the transaction.
60484   */
60485   rc = sqlite3VtabSync(db, &p->zErrMsg);
60486
60487   /* This loop determines (a) if the commit hook should be invoked and
60488   ** (b) how many database files have open write transactions, not 
60489   ** including the temp database. (b) is important because if more than 
60490   ** one database file has an open write transaction, a master journal
60491   ** file is required for an atomic commit.
60492   */ 
60493   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
60494     Btree *pBt = db->aDb[i].pBt;
60495     if( sqlite3BtreeIsInTrans(pBt) ){
60496       needXcommit = 1;
60497       if( i!=1 ) nTrans++;
60498       sqlite3BtreeEnter(pBt);
60499       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
60500       sqlite3BtreeLeave(pBt);
60501     }
60502   }
60503   if( rc!=SQLITE_OK ){
60504     return rc;
60505   }
60506
60507   /* If there are any write-transactions at all, invoke the commit hook */
60508   if( needXcommit && db->xCommitCallback ){
60509     rc = db->xCommitCallback(db->pCommitArg);
60510     if( rc ){
60511       return SQLITE_CONSTRAINT_COMMITHOOK;
60512     }
60513   }
60514
60515   /* The simple case - no more than one database file (not counting the
60516   ** TEMP database) has a transaction active.   There is no need for the
60517   ** master-journal.
60518   **
60519   ** If the return value of sqlite3BtreeGetFilename() is a zero length
60520   ** string, it means the main database is :memory: or a temp file.  In 
60521   ** that case we do not support atomic multi-file commits, so use the 
60522   ** simple case then too.
60523   */
60524   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
60525    || nTrans<=1
60526   ){
60527     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60528       Btree *pBt = db->aDb[i].pBt;
60529       if( pBt ){
60530         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
60531       }
60532     }
60533
60534     /* Do the commit only if all databases successfully complete phase 1. 
60535     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
60536     ** IO error while deleting or truncating a journal file. It is unlikely,
60537     ** but could happen. In this case abandon processing and return the error.
60538     */
60539     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60540       Btree *pBt = db->aDb[i].pBt;
60541       if( pBt ){
60542         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
60543       }
60544     }
60545     if( rc==SQLITE_OK ){
60546       sqlite3VtabCommit(db);
60547     }
60548   }
60549
60550   /* The complex case - There is a multi-file write-transaction active.
60551   ** This requires a master journal file to ensure the transaction is
60552   ** committed atomicly.
60553   */
60554 #ifndef SQLITE_OMIT_DISKIO
60555   else{
60556     sqlite3_vfs *pVfs = db->pVfs;
60557     int needSync = 0;
60558     char *zMaster = 0;   /* File-name for the master journal */
60559     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
60560     sqlite3_file *pMaster = 0;
60561     i64 offset = 0;
60562     int res;
60563     int retryCount = 0;
60564     int nMainFile;
60565
60566     /* Select a master journal file name */
60567     nMainFile = sqlite3Strlen30(zMainFile);
60568     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
60569     if( zMaster==0 ) return SQLITE_NOMEM;
60570     do {
60571       u32 iRandom;
60572       if( retryCount ){
60573         if( retryCount>100 ){
60574           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
60575           sqlite3OsDelete(pVfs, zMaster, 0);
60576           break;
60577         }else if( retryCount==1 ){
60578           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
60579         }
60580       }
60581       retryCount++;
60582       sqlite3_randomness(sizeof(iRandom), &iRandom);
60583       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
60584                                (iRandom>>8)&0xffffff, iRandom&0xff);
60585       /* The antipenultimate character of the master journal name must
60586       ** be "9" to avoid name collisions when using 8+3 filenames. */
60587       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
60588       sqlite3FileSuffix3(zMainFile, zMaster);
60589       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
60590     }while( rc==SQLITE_OK && res );
60591     if( rc==SQLITE_OK ){
60592       /* Open the master journal. */
60593       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
60594           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
60595           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
60596       );
60597     }
60598     if( rc!=SQLITE_OK ){
60599       sqlite3DbFree(db, zMaster);
60600       return rc;
60601     }
60602  
60603     /* Write the name of each database file in the transaction into the new
60604     ** master journal file. If an error occurs at this point close
60605     ** and delete the master journal file. All the individual journal files
60606     ** still have 'null' as the master journal pointer, so they will roll
60607     ** back independently if a failure occurs.
60608     */
60609     for(i=0; i<db->nDb; i++){
60610       Btree *pBt = db->aDb[i].pBt;
60611       if( sqlite3BtreeIsInTrans(pBt) ){
60612         char const *zFile = sqlite3BtreeGetJournalname(pBt);
60613         if( zFile==0 ){
60614           continue;  /* Ignore TEMP and :memory: databases */
60615         }
60616         assert( zFile[0]!=0 );
60617         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
60618           needSync = 1;
60619         }
60620         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
60621         offset += sqlite3Strlen30(zFile)+1;
60622         if( rc!=SQLITE_OK ){
60623           sqlite3OsCloseFree(pMaster);
60624           sqlite3OsDelete(pVfs, zMaster, 0);
60625           sqlite3DbFree(db, zMaster);
60626           return rc;
60627         }
60628       }
60629     }
60630
60631     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
60632     ** flag is set this is not required.
60633     */
60634     if( needSync 
60635      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
60636      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
60637     ){
60638       sqlite3OsCloseFree(pMaster);
60639       sqlite3OsDelete(pVfs, zMaster, 0);
60640       sqlite3DbFree(db, zMaster);
60641       return rc;
60642     }
60643
60644     /* Sync all the db files involved in the transaction. The same call
60645     ** sets the master journal pointer in each individual journal. If
60646     ** an error occurs here, do not delete the master journal file.
60647     **
60648     ** If the error occurs during the first call to
60649     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
60650     ** master journal file will be orphaned. But we cannot delete it,
60651     ** in case the master journal file name was written into the journal
60652     ** file before the failure occurred.
60653     */
60654     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
60655       Btree *pBt = db->aDb[i].pBt;
60656       if( pBt ){
60657         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
60658       }
60659     }
60660     sqlite3OsCloseFree(pMaster);
60661     assert( rc!=SQLITE_BUSY );
60662     if( rc!=SQLITE_OK ){
60663       sqlite3DbFree(db, zMaster);
60664       return rc;
60665     }
60666
60667     /* Delete the master journal file. This commits the transaction. After
60668     ** doing this the directory is synced again before any individual
60669     ** transaction files are deleted.
60670     */
60671     rc = sqlite3OsDelete(pVfs, zMaster, 1);
60672     sqlite3DbFree(db, zMaster);
60673     zMaster = 0;
60674     if( rc ){
60675       return rc;
60676     }
60677
60678     /* All files and directories have already been synced, so the following
60679     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
60680     ** deleting or truncating journals. If something goes wrong while
60681     ** this is happening we don't really care. The integrity of the
60682     ** transaction is already guaranteed, but some stray 'cold' journals
60683     ** may be lying around. Returning an error code won't help matters.
60684     */
60685     disable_simulated_io_errors();
60686     sqlite3BeginBenignMalloc();
60687     for(i=0; i<db->nDb; i++){ 
60688       Btree *pBt = db->aDb[i].pBt;
60689       if( pBt ){
60690         sqlite3BtreeCommitPhaseTwo(pBt, 1);
60691       }
60692     }
60693     sqlite3EndBenignMalloc();
60694     enable_simulated_io_errors();
60695
60696     sqlite3VtabCommit(db);
60697   }
60698 #endif
60699
60700   return rc;
60701 }
60702
60703 /* 
60704 ** This routine checks that the sqlite3.activeVdbeCnt count variable
60705 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
60706 ** currently active. An assertion fails if the two counts do not match.
60707 ** This is an internal self-check only - it is not an essential processing
60708 ** step.
60709 **
60710 ** This is a no-op if NDEBUG is defined.
60711 */
60712 #ifndef NDEBUG
60713 static void checkActiveVdbeCnt(sqlite3 *db){
60714   Vdbe *p;
60715   int cnt = 0;
60716   int nWrite = 0;
60717   p = db->pVdbe;
60718   while( p ){
60719     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
60720       cnt++;
60721       if( p->readOnly==0 ) nWrite++;
60722     }
60723     p = p->pNext;
60724   }
60725   assert( cnt==db->activeVdbeCnt );
60726   assert( nWrite==db->writeVdbeCnt );
60727 }
60728 #else
60729 #define checkActiveVdbeCnt(x)
60730 #endif
60731
60732 /*
60733 ** If the Vdbe passed as the first argument opened a statement-transaction,
60734 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
60735 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
60736 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
60737 ** statement transaction is commtted.
60738 **
60739 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
60740 ** Otherwise SQLITE_OK.
60741 */
60742 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
60743   sqlite3 *const db = p->db;
60744   int rc = SQLITE_OK;
60745
60746   /* If p->iStatement is greater than zero, then this Vdbe opened a 
60747   ** statement transaction that should be closed here. The only exception
60748   ** is that an IO error may have occurred, causing an emergency rollback.
60749   ** In this case (db->nStatement==0), and there is nothing to do.
60750   */
60751   if( db->nStatement && p->iStatement ){
60752     int i;
60753     const int iSavepoint = p->iStatement-1;
60754
60755     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
60756     assert( db->nStatement>0 );
60757     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
60758
60759     for(i=0; i<db->nDb; i++){ 
60760       int rc2 = SQLITE_OK;
60761       Btree *pBt = db->aDb[i].pBt;
60762       if( pBt ){
60763         if( eOp==SAVEPOINT_ROLLBACK ){
60764           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
60765         }
60766         if( rc2==SQLITE_OK ){
60767           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
60768         }
60769         if( rc==SQLITE_OK ){
60770           rc = rc2;
60771         }
60772       }
60773     }
60774     db->nStatement--;
60775     p->iStatement = 0;
60776
60777     if( rc==SQLITE_OK ){
60778       if( eOp==SAVEPOINT_ROLLBACK ){
60779         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
60780       }
60781       if( rc==SQLITE_OK ){
60782         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
60783       }
60784     }
60785
60786     /* If the statement transaction is being rolled back, also restore the 
60787     ** database handles deferred constraint counter to the value it had when 
60788     ** the statement transaction was opened.  */
60789     if( eOp==SAVEPOINT_ROLLBACK ){
60790       db->nDeferredCons = p->nStmtDefCons;
60791     }
60792   }
60793   return rc;
60794 }
60795
60796 /*
60797 ** This function is called when a transaction opened by the database 
60798 ** handle associated with the VM passed as an argument is about to be 
60799 ** committed. If there are outstanding deferred foreign key constraint
60800 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
60801 **
60802 ** If there are outstanding FK violations and this function returns 
60803 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
60804 ** and write an error message to it. Then return SQLITE_ERROR.
60805 */
60806 #ifndef SQLITE_OMIT_FOREIGN_KEY
60807 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
60808   sqlite3 *db = p->db;
60809   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
60810     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
60811     p->errorAction = OE_Abort;
60812     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
60813     return SQLITE_ERROR;
60814   }
60815   return SQLITE_OK;
60816 }
60817 #endif
60818
60819 /*
60820 ** This routine is called the when a VDBE tries to halt.  If the VDBE
60821 ** has made changes and is in autocommit mode, then commit those
60822 ** changes.  If a rollback is needed, then do the rollback.
60823 **
60824 ** This routine is the only way to move the state of a VM from
60825 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
60826 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
60827 **
60828 ** Return an error code.  If the commit could not complete because of
60829 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
60830 ** means the close did not happen and needs to be repeated.
60831 */
60832 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
60833   int rc;                         /* Used to store transient return codes */
60834   sqlite3 *db = p->db;
60835
60836   /* This function contains the logic that determines if a statement or
60837   ** transaction will be committed or rolled back as a result of the
60838   ** execution of this virtual machine. 
60839   **
60840   ** If any of the following errors occur:
60841   **
60842   **     SQLITE_NOMEM
60843   **     SQLITE_IOERR
60844   **     SQLITE_FULL
60845   **     SQLITE_INTERRUPT
60846   **
60847   ** Then the internal cache might have been left in an inconsistent
60848   ** state.  We need to rollback the statement transaction, if there is
60849   ** one, or the complete transaction if there is no statement transaction.
60850   */
60851
60852   if( p->db->mallocFailed ){
60853     p->rc = SQLITE_NOMEM;
60854   }
60855   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
60856   closeAllCursors(p);
60857   if( p->magic!=VDBE_MAGIC_RUN ){
60858     return SQLITE_OK;
60859   }
60860   checkActiveVdbeCnt(db);
60861
60862   /* No commit or rollback needed if the program never started */
60863   if( p->pc>=0 ){
60864     int mrc;   /* Primary error code from p->rc */
60865     int eStatementOp = 0;
60866     int isSpecialError;            /* Set to true if a 'special' error */
60867
60868     /* Lock all btrees used by the statement */
60869     sqlite3VdbeEnter(p);
60870
60871     /* Check for one of the special errors */
60872     mrc = p->rc & 0xff;
60873     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
60874     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
60875                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
60876     if( isSpecialError ){
60877       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
60878       ** no rollback is necessary. Otherwise, at least a savepoint 
60879       ** transaction must be rolled back to restore the database to a 
60880       ** consistent state.
60881       **
60882       ** Even if the statement is read-only, it is important to perform
60883       ** a statement or transaction rollback operation. If the error 
60884       ** occurred while writing to the journal, sub-journal or database
60885       ** file as part of an effort to free up cache space (see function
60886       ** pagerStress() in pager.c), the rollback is required to restore 
60887       ** the pager to a consistent state.
60888       */
60889       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
60890         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
60891           eStatementOp = SAVEPOINT_ROLLBACK;
60892         }else{
60893           /* We are forced to roll back the active transaction. Before doing
60894           ** so, abort any other statements this handle currently has active.
60895           */
60896           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
60897           sqlite3CloseSavepoints(db);
60898           db->autoCommit = 1;
60899         }
60900       }
60901     }
60902
60903     /* Check for immediate foreign key violations. */
60904     if( p->rc==SQLITE_OK ){
60905       sqlite3VdbeCheckFk(p, 0);
60906     }
60907   
60908     /* If the auto-commit flag is set and this is the only active writer 
60909     ** VM, then we do either a commit or rollback of the current transaction. 
60910     **
60911     ** Note: This block also runs if one of the special errors handled 
60912     ** above has occurred. 
60913     */
60914     if( !sqlite3VtabInSync(db) 
60915      && db->autoCommit 
60916      && db->writeVdbeCnt==(p->readOnly==0) 
60917     ){
60918       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
60919         rc = sqlite3VdbeCheckFk(p, 1);
60920         if( rc!=SQLITE_OK ){
60921           if( NEVER(p->readOnly) ){
60922             sqlite3VdbeLeave(p);
60923             return SQLITE_ERROR;
60924           }
60925           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
60926         }else{ 
60927           /* The auto-commit flag is true, the vdbe program was successful 
60928           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
60929           ** key constraints to hold up the transaction. This means a commit 
60930           ** is required. */
60931           rc = vdbeCommit(db, p);
60932         }
60933         if( rc==SQLITE_BUSY && p->readOnly ){
60934           sqlite3VdbeLeave(p);
60935           return SQLITE_BUSY;
60936         }else if( rc!=SQLITE_OK ){
60937           p->rc = rc;
60938           sqlite3RollbackAll(db, SQLITE_OK);
60939         }else{
60940           db->nDeferredCons = 0;
60941           sqlite3CommitInternalChanges(db);
60942         }
60943       }else{
60944         sqlite3RollbackAll(db, SQLITE_OK);
60945       }
60946       db->nStatement = 0;
60947     }else if( eStatementOp==0 ){
60948       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
60949         eStatementOp = SAVEPOINT_RELEASE;
60950       }else if( p->errorAction==OE_Abort ){
60951         eStatementOp = SAVEPOINT_ROLLBACK;
60952       }else{
60953         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
60954         sqlite3CloseSavepoints(db);
60955         db->autoCommit = 1;
60956       }
60957     }
60958   
60959     /* If eStatementOp is non-zero, then a statement transaction needs to
60960     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
60961     ** do so. If this operation returns an error, and the current statement
60962     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
60963     ** current statement error code.
60964     */
60965     if( eStatementOp ){
60966       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
60967       if( rc ){
60968         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
60969           p->rc = rc;
60970           sqlite3DbFree(db, p->zErrMsg);
60971           p->zErrMsg = 0;
60972         }
60973         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
60974         sqlite3CloseSavepoints(db);
60975         db->autoCommit = 1;
60976       }
60977     }
60978   
60979     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
60980     ** has been rolled back, update the database connection change-counter. 
60981     */
60982     if( p->changeCntOn ){
60983       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
60984         sqlite3VdbeSetChanges(db, p->nChange);
60985       }else{
60986         sqlite3VdbeSetChanges(db, 0);
60987       }
60988       p->nChange = 0;
60989     }
60990
60991     /* Release the locks */
60992     sqlite3VdbeLeave(p);
60993   }
60994
60995   /* We have successfully halted and closed the VM.  Record this fact. */
60996   if( p->pc>=0 ){
60997     db->activeVdbeCnt--;
60998     if( !p->readOnly ){
60999       db->writeVdbeCnt--;
61000     }
61001     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
61002   }
61003   p->magic = VDBE_MAGIC_HALT;
61004   checkActiveVdbeCnt(db);
61005   if( p->db->mallocFailed ){
61006     p->rc = SQLITE_NOMEM;
61007   }
61008
61009   /* If the auto-commit flag is set to true, then any locks that were held
61010   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
61011   ** to invoke any required unlock-notify callbacks.
61012   */
61013   if( db->autoCommit ){
61014     sqlite3ConnectionUnlocked(db);
61015   }
61016
61017   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
61018   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
61019 }
61020
61021
61022 /*
61023 ** Each VDBE holds the result of the most recent sqlite3_step() call
61024 ** in p->rc.  This routine sets that result back to SQLITE_OK.
61025 */
61026 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
61027   p->rc = SQLITE_OK;
61028 }
61029
61030 /*
61031 ** Copy the error code and error message belonging to the VDBE passed
61032 ** as the first argument to its database handle (so that they will be 
61033 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
61034 **
61035 ** This function does not clear the VDBE error code or message, just
61036 ** copies them to the database handle.
61037 */
61038 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
61039   sqlite3 *db = p->db;
61040   int rc = p->rc;
61041   if( p->zErrMsg ){
61042     u8 mallocFailed = db->mallocFailed;
61043     sqlite3BeginBenignMalloc();
61044     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
61045     sqlite3EndBenignMalloc();
61046     db->mallocFailed = mallocFailed;
61047     db->errCode = rc;
61048   }else{
61049     sqlite3Error(db, rc, 0);
61050   }
61051   return rc;
61052 }
61053
61054 #ifdef SQLITE_ENABLE_SQLLOG
61055 /*
61056 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, 
61057 ** invoke it.
61058 */
61059 static void vdbeInvokeSqllog(Vdbe *v){
61060   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
61061     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
61062     assert( v->db->init.busy==0 );
61063     if( zExpanded ){
61064       sqlite3GlobalConfig.xSqllog(
61065           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
61066       );
61067       sqlite3DbFree(v->db, zExpanded);
61068     }
61069   }
61070 }
61071 #else
61072 # define vdbeInvokeSqllog(x)
61073 #endif
61074
61075 /*
61076 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
61077 ** Write any error messages into *pzErrMsg.  Return the result code.
61078 **
61079 ** After this routine is run, the VDBE should be ready to be executed
61080 ** again.
61081 **
61082 ** To look at it another way, this routine resets the state of the
61083 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
61084 ** VDBE_MAGIC_INIT.
61085 */
61086 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
61087   sqlite3 *db;
61088   db = p->db;
61089
61090   /* If the VM did not run to completion or if it encountered an
61091   ** error, then it might not have been halted properly.  So halt
61092   ** it now.
61093   */
61094   sqlite3VdbeHalt(p);
61095
61096   /* If the VDBE has be run even partially, then transfer the error code
61097   ** and error message from the VDBE into the main database structure.  But
61098   ** if the VDBE has just been set to run but has not actually executed any
61099   ** instructions yet, leave the main database error information unchanged.
61100   */
61101   if( p->pc>=0 ){
61102     vdbeInvokeSqllog(p);
61103     sqlite3VdbeTransferError(p);
61104     sqlite3DbFree(db, p->zErrMsg);
61105     p->zErrMsg = 0;
61106     if( p->runOnlyOnce ) p->expired = 1;
61107   }else if( p->rc && p->expired ){
61108     /* The expired flag was set on the VDBE before the first call
61109     ** to sqlite3_step(). For consistency (since sqlite3_step() was
61110     ** called), set the database error in this case as well.
61111     */
61112     sqlite3Error(db, p->rc, 0);
61113     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
61114     sqlite3DbFree(db, p->zErrMsg);
61115     p->zErrMsg = 0;
61116   }
61117
61118   /* Reclaim all memory used by the VDBE
61119   */
61120   Cleanup(p);
61121
61122   /* Save profiling information from this VDBE run.
61123   */
61124 #ifdef VDBE_PROFILE
61125   {
61126     FILE *out = fopen("vdbe_profile.out", "a");
61127     if( out ){
61128       int i;
61129       fprintf(out, "---- ");
61130       for(i=0; i<p->nOp; i++){
61131         fprintf(out, "%02x", p->aOp[i].opcode);
61132       }
61133       fprintf(out, "\n");
61134       for(i=0; i<p->nOp; i++){
61135         fprintf(out, "%6d %10lld %8lld ",
61136            p->aOp[i].cnt,
61137            p->aOp[i].cycles,
61138            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
61139         );
61140         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
61141       }
61142       fclose(out);
61143     }
61144   }
61145 #endif
61146   p->magic = VDBE_MAGIC_INIT;
61147   return p->rc & db->errMask;
61148 }
61149  
61150 /*
61151 ** Clean up and delete a VDBE after execution.  Return an integer which is
61152 ** the result code.  Write any error message text into *pzErrMsg.
61153 */
61154 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
61155   int rc = SQLITE_OK;
61156   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
61157     rc = sqlite3VdbeReset(p);
61158     assert( (rc & p->db->errMask)==rc );
61159   }
61160   sqlite3VdbeDelete(p);
61161   return rc;
61162 }
61163
61164 /*
61165 ** Call the destructor for each auxdata entry in pVdbeFunc for which
61166 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
61167 ** are always destroyed.  To destroy all auxdata entries, call this
61168 ** routine with mask==0.
61169 */
61170 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
61171   int i;
61172   for(i=0; i<pVdbeFunc->nAux; i++){
61173     struct AuxData *pAux = &pVdbeFunc->apAux[i];
61174     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
61175       if( pAux->xDelete ){
61176         pAux->xDelete(pAux->pAux);
61177       }
61178       pAux->pAux = 0;
61179     }
61180   }
61181 }
61182
61183 /*
61184 ** Free all memory associated with the Vdbe passed as the second argument,
61185 ** except for object itself, which is preserved.
61186 **
61187 ** The difference between this function and sqlite3VdbeDelete() is that
61188 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
61189 ** the database connection and frees the object itself.
61190 */
61191 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
61192   SubProgram *pSub, *pNext;
61193   int i;
61194   assert( p->db==0 || p->db==db );
61195   releaseMemArray(p->aVar, p->nVar);
61196   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61197   for(pSub=p->pProgram; pSub; pSub=pNext){
61198     pNext = pSub->pNext;
61199     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
61200     sqlite3DbFree(db, pSub);
61201   }
61202   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
61203   vdbeFreeOpArray(db, p->aOp, p->nOp);
61204   sqlite3DbFree(db, p->aLabel);
61205   sqlite3DbFree(db, p->aColName);
61206   sqlite3DbFree(db, p->zSql);
61207   sqlite3DbFree(db, p->pFree);
61208 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
61209   sqlite3DbFree(db, p->zExplain);
61210   sqlite3DbFree(db, p->pExplain);
61211 #endif
61212 }
61213
61214 /*
61215 ** Delete an entire VDBE.
61216 */
61217 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
61218   sqlite3 *db;
61219
61220   if( NEVER(p==0) ) return;
61221   db = p->db;
61222   assert( sqlite3_mutex_held(db->mutex) );
61223   sqlite3VdbeClearObject(db, p);
61224   if( p->pPrev ){
61225     p->pPrev->pNext = p->pNext;
61226   }else{
61227     assert( db->pVdbe==p );
61228     db->pVdbe = p->pNext;
61229   }
61230   if( p->pNext ){
61231     p->pNext->pPrev = p->pPrev;
61232   }
61233   p->magic = VDBE_MAGIC_DEAD;
61234   p->db = 0;
61235   sqlite3DbFree(db, p);
61236 }
61237
61238 /*
61239 ** Make sure the cursor p is ready to read or write the row to which it
61240 ** was last positioned.  Return an error code if an OOM fault or I/O error
61241 ** prevents us from positioning the cursor to its correct position.
61242 **
61243 ** If a MoveTo operation is pending on the given cursor, then do that
61244 ** MoveTo now.  If no move is pending, check to see if the row has been
61245 ** deleted out from under the cursor and if it has, mark the row as
61246 ** a NULL row.
61247 **
61248 ** If the cursor is already pointing to the correct row and that row has
61249 ** not been deleted out from under the cursor, then this routine is a no-op.
61250 */
61251 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
61252   if( p->deferredMoveto ){
61253     int res, rc;
61254 #ifdef SQLITE_TEST
61255     extern int sqlite3_search_count;
61256 #endif
61257     assert( p->isTable );
61258     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
61259     if( rc ) return rc;
61260     p->lastRowid = p->movetoTarget;
61261     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
61262     p->rowidIsValid = 1;
61263 #ifdef SQLITE_TEST
61264     sqlite3_search_count++;
61265 #endif
61266     p->deferredMoveto = 0;
61267     p->cacheStatus = CACHE_STALE;
61268   }else if( ALWAYS(p->pCursor) ){
61269     int hasMoved;
61270     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
61271     if( rc ) return rc;
61272     if( hasMoved ){
61273       p->cacheStatus = CACHE_STALE;
61274       p->nullRow = 1;
61275     }
61276   }
61277   return SQLITE_OK;
61278 }
61279
61280 /*
61281 ** The following functions:
61282 **
61283 ** sqlite3VdbeSerialType()
61284 ** sqlite3VdbeSerialTypeLen()
61285 ** sqlite3VdbeSerialLen()
61286 ** sqlite3VdbeSerialPut()
61287 ** sqlite3VdbeSerialGet()
61288 **
61289 ** encapsulate the code that serializes values for storage in SQLite
61290 ** data and index records. Each serialized value consists of a
61291 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
61292 ** integer, stored as a varint.
61293 **
61294 ** In an SQLite index record, the serial type is stored directly before
61295 ** the blob of data that it corresponds to. In a table record, all serial
61296 ** types are stored at the start of the record, and the blobs of data at
61297 ** the end. Hence these functions allow the caller to handle the
61298 ** serial-type and data blob separately.
61299 **
61300 ** The following table describes the various storage classes for data:
61301 **
61302 **   serial type        bytes of data      type
61303 **   --------------     ---------------    ---------------
61304 **      0                     0            NULL
61305 **      1                     1            signed integer
61306 **      2                     2            signed integer
61307 **      3                     3            signed integer
61308 **      4                     4            signed integer
61309 **      5                     6            signed integer
61310 **      6                     8            signed integer
61311 **      7                     8            IEEE float
61312 **      8                     0            Integer constant 0
61313 **      9                     0            Integer constant 1
61314 **     10,11                               reserved for expansion
61315 **    N>=12 and even       (N-12)/2        BLOB
61316 **    N>=13 and odd        (N-13)/2        text
61317 **
61318 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
61319 ** of SQLite will not understand those serial types.
61320 */
61321
61322 /*
61323 ** Return the serial-type for the value stored in pMem.
61324 */
61325 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
61326   int flags = pMem->flags;
61327   int n;
61328
61329   if( flags&MEM_Null ){
61330     return 0;
61331   }
61332   if( flags&MEM_Int ){
61333     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
61334 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
61335     i64 i = pMem->u.i;
61336     u64 u;
61337     if( i<0 ){
61338       if( i<(-MAX_6BYTE) ) return 6;
61339       /* Previous test prevents:  u = -(-9223372036854775808) */
61340       u = -i;
61341     }else{
61342       u = i;
61343     }
61344     if( u<=127 ){
61345       return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
61346     }
61347     if( u<=32767 ) return 2;
61348     if( u<=8388607 ) return 3;
61349     if( u<=2147483647 ) return 4;
61350     if( u<=MAX_6BYTE ) return 5;
61351     return 6;
61352   }
61353   if( flags&MEM_Real ){
61354     return 7;
61355   }
61356   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
61357   n = pMem->n;
61358   if( flags & MEM_Zero ){
61359     n += pMem->u.nZero;
61360   }
61361   assert( n>=0 );
61362   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
61363 }
61364
61365 /*
61366 ** Return the length of the data corresponding to the supplied serial-type.
61367 */
61368 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
61369   if( serial_type>=12 ){
61370     return (serial_type-12)/2;
61371   }else{
61372     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
61373     return aSize[serial_type];
61374   }
61375 }
61376
61377 /*
61378 ** If we are on an architecture with mixed-endian floating 
61379 ** points (ex: ARM7) then swap the lower 4 bytes with the 
61380 ** upper 4 bytes.  Return the result.
61381 **
61382 ** For most architectures, this is a no-op.
61383 **
61384 ** (later):  It is reported to me that the mixed-endian problem
61385 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
61386 ** that early versions of GCC stored the two words of a 64-bit
61387 ** float in the wrong order.  And that error has been propagated
61388 ** ever since.  The blame is not necessarily with GCC, though.
61389 ** GCC might have just copying the problem from a prior compiler.
61390 ** I am also told that newer versions of GCC that follow a different
61391 ** ABI get the byte order right.
61392 **
61393 ** Developers using SQLite on an ARM7 should compile and run their
61394 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
61395 ** enabled, some asserts below will ensure that the byte order of
61396 ** floating point values is correct.
61397 **
61398 ** (2007-08-30)  Frank van Vugt has studied this problem closely
61399 ** and has send his findings to the SQLite developers.  Frank
61400 ** writes that some Linux kernels offer floating point hardware
61401 ** emulation that uses only 32-bit mantissas instead of a full 
61402 ** 48-bits as required by the IEEE standard.  (This is the
61403 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
61404 ** byte swapping becomes very complicated.  To avoid problems,
61405 ** the necessary byte swapping is carried out using a 64-bit integer
61406 ** rather than a 64-bit float.  Frank assures us that the code here
61407 ** works for him.  We, the developers, have no way to independently
61408 ** verify this, but Frank seems to know what he is talking about
61409 ** so we trust him.
61410 */
61411 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
61412 static u64 floatSwap(u64 in){
61413   union {
61414     u64 r;
61415     u32 i[2];
61416   } u;
61417   u32 t;
61418
61419   u.r = in;
61420   t = u.i[0];
61421   u.i[0] = u.i[1];
61422   u.i[1] = t;
61423   return u.r;
61424 }
61425 # define swapMixedEndianFloat(X)  X = floatSwap(X)
61426 #else
61427 # define swapMixedEndianFloat(X)
61428 #endif
61429
61430 /*
61431 ** Write the serialized data blob for the value stored in pMem into 
61432 ** buf. It is assumed that the caller has allocated sufficient space.
61433 ** Return the number of bytes written.
61434 **
61435 ** nBuf is the amount of space left in buf[].  nBuf must always be
61436 ** large enough to hold the entire field.  Except, if the field is
61437 ** a blob with a zero-filled tail, then buf[] might be just the right
61438 ** size to hold everything except for the zero-filled tail.  If buf[]
61439 ** is only big enough to hold the non-zero prefix, then only write that
61440 ** prefix into buf[].  But if buf[] is large enough to hold both the
61441 ** prefix and the tail then write the prefix and set the tail to all
61442 ** zeros.
61443 **
61444 ** Return the number of bytes actually written into buf[].  The number
61445 ** of bytes in the zero-filled tail is included in the return value only
61446 ** if those bytes were zeroed in buf[].
61447 */ 
61448 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
61449   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
61450   u32 len;
61451
61452   /* Integer and Real */
61453   if( serial_type<=7 && serial_type>0 ){
61454     u64 v;
61455     u32 i;
61456     if( serial_type==7 ){
61457       assert( sizeof(v)==sizeof(pMem->r) );
61458       memcpy(&v, &pMem->r, sizeof(v));
61459       swapMixedEndianFloat(v);
61460     }else{
61461       v = pMem->u.i;
61462     }
61463     len = i = sqlite3VdbeSerialTypeLen(serial_type);
61464     assert( len<=(u32)nBuf );
61465     while( i-- ){
61466       buf[i] = (u8)(v&0xFF);
61467       v >>= 8;
61468     }
61469     return len;
61470   }
61471
61472   /* String or blob */
61473   if( serial_type>=12 ){
61474     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
61475              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
61476     assert( pMem->n<=nBuf );
61477     len = pMem->n;
61478     memcpy(buf, pMem->z, len);
61479     if( pMem->flags & MEM_Zero ){
61480       len += pMem->u.nZero;
61481       assert( nBuf>=0 );
61482       if( len > (u32)nBuf ){
61483         len = (u32)nBuf;
61484       }
61485       memset(&buf[pMem->n], 0, len-pMem->n);
61486     }
61487     return len;
61488   }
61489
61490   /* NULL or constants 0 or 1 */
61491   return 0;
61492 }
61493
61494 /*
61495 ** Deserialize the data blob pointed to by buf as serial type serial_type
61496 ** and store the result in pMem.  Return the number of bytes read.
61497 */ 
61498 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
61499   const unsigned char *buf,     /* Buffer to deserialize from */
61500   u32 serial_type,              /* Serial type to deserialize */
61501   Mem *pMem                     /* Memory cell to write value into */
61502 ){
61503   switch( serial_type ){
61504     case 10:   /* Reserved for future use */
61505     case 11:   /* Reserved for future use */
61506     case 0: {  /* NULL */
61507       pMem->flags = MEM_Null;
61508       break;
61509     }
61510     case 1: { /* 1-byte signed integer */
61511       pMem->u.i = (signed char)buf[0];
61512       pMem->flags = MEM_Int;
61513       return 1;
61514     }
61515     case 2: { /* 2-byte signed integer */
61516       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
61517       pMem->flags = MEM_Int;
61518       return 2;
61519     }
61520     case 3: { /* 3-byte signed integer */
61521       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
61522       pMem->flags = MEM_Int;
61523       return 3;
61524     }
61525     case 4: { /* 4-byte signed integer */
61526       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
61527       pMem->flags = MEM_Int;
61528       return 4;
61529     }
61530     case 5: { /* 6-byte signed integer */
61531       u64 x = (((signed char)buf[0])<<8) | buf[1];
61532       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
61533       x = (x<<32) | y;
61534       pMem->u.i = *(i64*)&x;
61535       pMem->flags = MEM_Int;
61536       return 6;
61537     }
61538     case 6:   /* 8-byte signed integer */
61539     case 7: { /* IEEE floating point */
61540       u64 x;
61541       u32 y;
61542 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
61543       /* Verify that integers and floating point values use the same
61544       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
61545       ** defined that 64-bit floating point values really are mixed
61546       ** endian.
61547       */
61548       static const u64 t1 = ((u64)0x3ff00000)<<32;
61549       static const double r1 = 1.0;
61550       u64 t2 = t1;
61551       swapMixedEndianFloat(t2);
61552       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
61553 #endif
61554
61555       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
61556       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
61557       x = (x<<32) | y;
61558       if( serial_type==6 ){
61559         pMem->u.i = *(i64*)&x;
61560         pMem->flags = MEM_Int;
61561       }else{
61562         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
61563         swapMixedEndianFloat(x);
61564         memcpy(&pMem->r, &x, sizeof(x));
61565         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
61566       }
61567       return 8;
61568     }
61569     case 8:    /* Integer 0 */
61570     case 9: {  /* Integer 1 */
61571       pMem->u.i = serial_type-8;
61572       pMem->flags = MEM_Int;
61573       return 0;
61574     }
61575     default: {
61576       u32 len = (serial_type-12)/2;
61577       pMem->z = (char *)buf;
61578       pMem->n = len;
61579       pMem->xDel = 0;
61580       if( serial_type&0x01 ){
61581         pMem->flags = MEM_Str | MEM_Ephem;
61582       }else{
61583         pMem->flags = MEM_Blob | MEM_Ephem;
61584       }
61585       return len;
61586     }
61587   }
61588   return 0;
61589 }
61590
61591 /*
61592 ** This routine is used to allocate sufficient space for an UnpackedRecord
61593 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
61594 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
61595 **
61596 ** The space is either allocated using sqlite3DbMallocRaw() or from within
61597 ** the unaligned buffer passed via the second and third arguments (presumably
61598 ** stack space). If the former, then *ppFree is set to a pointer that should
61599 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the 
61600 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
61601 ** before returning.
61602 **
61603 ** If an OOM error occurs, NULL is returned.
61604 */
61605 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
61606   KeyInfo *pKeyInfo,              /* Description of the record */
61607   char *pSpace,                   /* Unaligned space available */
61608   int szSpace,                    /* Size of pSpace[] in bytes */
61609   char **ppFree                   /* OUT: Caller should free this pointer */
61610 ){
61611   UnpackedRecord *p;              /* Unpacked record to return */
61612   int nOff;                       /* Increment pSpace by nOff to align it */
61613   int nByte;                      /* Number of bytes required for *p */
61614
61615   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
61616   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
61617   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
61618   */
61619   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
61620   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
61621   if( nByte>szSpace+nOff ){
61622     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
61623     *ppFree = (char *)p;
61624     if( !p ) return 0;
61625   }else{
61626     p = (UnpackedRecord*)&pSpace[nOff];
61627     *ppFree = 0;
61628   }
61629
61630   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
61631   assert( pKeyInfo->aSortOrder!=0 );
61632   p->pKeyInfo = pKeyInfo;
61633   p->nField = pKeyInfo->nField + 1;
61634   return p;
61635 }
61636
61637 /*
61638 ** Given the nKey-byte encoding of a record in pKey[], populate the 
61639 ** UnpackedRecord structure indicated by the fourth argument with the
61640 ** contents of the decoded record.
61641 */ 
61642 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
61643   KeyInfo *pKeyInfo,     /* Information about the record format */
61644   int nKey,              /* Size of the binary record */
61645   const void *pKey,      /* The binary record */
61646   UnpackedRecord *p      /* Populate this structure before returning. */
61647 ){
61648   const unsigned char *aKey = (const unsigned char *)pKey;
61649   int d; 
61650   u32 idx;                        /* Offset in aKey[] to read from */
61651   u16 u;                          /* Unsigned loop counter */
61652   u32 szHdr;
61653   Mem *pMem = p->aMem;
61654
61655   p->flags = 0;
61656   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
61657   idx = getVarint32(aKey, szHdr);
61658   d = szHdr;
61659   u = 0;
61660   while( idx<szHdr && u<p->nField && d<=nKey ){
61661     u32 serial_type;
61662
61663     idx += getVarint32(&aKey[idx], serial_type);
61664     pMem->enc = pKeyInfo->enc;
61665     pMem->db = pKeyInfo->db;
61666     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
61667     pMem->zMalloc = 0;
61668     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
61669     pMem++;
61670     u++;
61671   }
61672   assert( u<=pKeyInfo->nField + 1 );
61673   p->nField = u;
61674 }
61675
61676 /*
61677 ** This function compares the two table rows or index records
61678 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
61679 ** or positive integer if key1 is less than, equal to or 
61680 ** greater than key2.  The {nKey1, pKey1} key must be a blob
61681 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
61682 ** key must be a parsed key such as obtained from
61683 ** sqlite3VdbeParseRecord.
61684 **
61685 ** Key1 and Key2 do not have to contain the same number of fields.
61686 ** The key with fewer fields is usually compares less than the 
61687 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
61688 ** and the common prefixes are equal, then key1 is less than key2.
61689 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
61690 ** equal, then the keys are considered to be equal and
61691 ** the parts beyond the common prefix are ignored.
61692 */
61693 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
61694   int nKey1, const void *pKey1, /* Left key */
61695   UnpackedRecord *pPKey2        /* Right key */
61696 ){
61697   int d1;            /* Offset into aKey[] of next data element */
61698   u32 idx1;          /* Offset into aKey[] of next header element */
61699   u32 szHdr1;        /* Number of bytes in header */
61700   int i = 0;
61701   int nField;
61702   int rc = 0;
61703   const unsigned char *aKey1 = (const unsigned char *)pKey1;
61704   KeyInfo *pKeyInfo;
61705   Mem mem1;
61706
61707   pKeyInfo = pPKey2->pKeyInfo;
61708   mem1.enc = pKeyInfo->enc;
61709   mem1.db = pKeyInfo->db;
61710   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
61711   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
61712
61713   /* Compilers may complain that mem1.u.i is potentially uninitialized.
61714   ** We could initialize it, as shown here, to silence those complaints.
61715   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
61716   ** the unnecessary initialization has a measurable negative performance
61717   ** impact, since this routine is a very high runner.  And so, we choose
61718   ** to ignore the compiler warnings and leave this variable uninitialized.
61719   */
61720   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
61721   
61722   idx1 = getVarint32(aKey1, szHdr1);
61723   d1 = szHdr1;
61724   nField = pKeyInfo->nField;
61725   assert( pKeyInfo->aSortOrder!=0 );
61726   while( idx1<szHdr1 && i<pPKey2->nField ){
61727     u32 serial_type1;
61728
61729     /* Read the serial types for the next element in each key. */
61730     idx1 += getVarint32( aKey1+idx1, serial_type1 );
61731     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
61732
61733     /* Extract the values to be compared.
61734     */
61735     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
61736
61737     /* Do the comparison
61738     */
61739     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
61740                            i<nField ? pKeyInfo->aColl[i] : 0);
61741     if( rc!=0 ){
61742       assert( mem1.zMalloc==0 );  /* See comment below */
61743
61744       /* Invert the result if we are using DESC sort order. */
61745       if( i<nField && pKeyInfo->aSortOrder[i] ){
61746         rc = -rc;
61747       }
61748     
61749       /* If the PREFIX_SEARCH flag is set and all fields except the final
61750       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
61751       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
61752       ** This is used by the OP_IsUnique opcode.
61753       */
61754       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
61755         assert( idx1==szHdr1 && rc );
61756         assert( mem1.flags & MEM_Int );
61757         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
61758         pPKey2->rowid = mem1.u.i;
61759       }
61760     
61761       return rc;
61762     }
61763     i++;
61764   }
61765
61766   /* No memory allocation is ever used on mem1.  Prove this using
61767   ** the following assert().  If the assert() fails, it indicates a
61768   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
61769   */
61770   assert( mem1.zMalloc==0 );
61771
61772   /* rc==0 here means that one of the keys ran out of fields and
61773   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
61774   ** flag is set, then break the tie by treating key2 as larger.
61775   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
61776   ** are considered to be equal.  Otherwise, the longer key is the 
61777   ** larger.  As it happens, the pPKey2 will always be the longer
61778   ** if there is a difference.
61779   */
61780   assert( rc==0 );
61781   if( pPKey2->flags & UNPACKED_INCRKEY ){
61782     rc = -1;
61783   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
61784     /* Leave rc==0 */
61785   }else if( idx1<szHdr1 ){
61786     rc = 1;
61787   }
61788   return rc;
61789 }
61790  
61791
61792 /*
61793 ** pCur points at an index entry created using the OP_MakeRecord opcode.
61794 ** Read the rowid (the last field in the record) and store it in *rowid.
61795 ** Return SQLITE_OK if everything works, or an error code otherwise.
61796 **
61797 ** pCur might be pointing to text obtained from a corrupt database file.
61798 ** So the content cannot be trusted.  Do appropriate checks on the content.
61799 */
61800 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
61801   i64 nCellKey = 0;
61802   int rc;
61803   u32 szHdr;        /* Size of the header */
61804   u32 typeRowid;    /* Serial type of the rowid */
61805   u32 lenRowid;     /* Size of the rowid */
61806   Mem m, v;
61807
61808   UNUSED_PARAMETER(db);
61809
61810   /* Get the size of the index entry.  Only indices entries of less
61811   ** than 2GiB are support - anything large must be database corruption.
61812   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
61813   ** this code can safely assume that nCellKey is 32-bits  
61814   */
61815   assert( sqlite3BtreeCursorIsValid(pCur) );
61816   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
61817   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
61818   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
61819
61820   /* Read in the complete content of the index entry */
61821   memset(&m, 0, sizeof(m));
61822   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
61823   if( rc ){
61824     return rc;
61825   }
61826
61827   /* The index entry must begin with a header size */
61828   (void)getVarint32((u8*)m.z, szHdr);
61829   testcase( szHdr==3 );
61830   testcase( szHdr==m.n );
61831   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
61832     goto idx_rowid_corruption;
61833   }
61834
61835   /* The last field of the index should be an integer - the ROWID.
61836   ** Verify that the last entry really is an integer. */
61837   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
61838   testcase( typeRowid==1 );
61839   testcase( typeRowid==2 );
61840   testcase( typeRowid==3 );
61841   testcase( typeRowid==4 );
61842   testcase( typeRowid==5 );
61843   testcase( typeRowid==6 );
61844   testcase( typeRowid==8 );
61845   testcase( typeRowid==9 );
61846   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
61847     goto idx_rowid_corruption;
61848   }
61849   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
61850   testcase( (u32)m.n==szHdr+lenRowid );
61851   if( unlikely((u32)m.n<szHdr+lenRowid) ){
61852     goto idx_rowid_corruption;
61853   }
61854
61855   /* Fetch the integer off the end of the index record */
61856   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
61857   *rowid = v.u.i;
61858   sqlite3VdbeMemRelease(&m);
61859   return SQLITE_OK;
61860
61861   /* Jump here if database corruption is detected after m has been
61862   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
61863 idx_rowid_corruption:
61864   testcase( m.zMalloc!=0 );
61865   sqlite3VdbeMemRelease(&m);
61866   return SQLITE_CORRUPT_BKPT;
61867 }
61868
61869 /*
61870 ** Compare the key of the index entry that cursor pC is pointing to against
61871 ** the key string in pUnpacked.  Write into *pRes a number
61872 ** that is negative, zero, or positive if pC is less than, equal to,
61873 ** or greater than pUnpacked.  Return SQLITE_OK on success.
61874 **
61875 ** pUnpacked is either created without a rowid or is truncated so that it
61876 ** omits the rowid at the end.  The rowid at the end of the index entry
61877 ** is ignored as well.  Hence, this routine only compares the prefixes 
61878 ** of the keys prior to the final rowid, not the entire key.
61879 */
61880 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
61881   VdbeCursor *pC,             /* The cursor to compare against */
61882   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
61883   int *res                    /* Write the comparison result here */
61884 ){
61885   i64 nCellKey = 0;
61886   int rc;
61887   BtCursor *pCur = pC->pCursor;
61888   Mem m;
61889
61890   assert( sqlite3BtreeCursorIsValid(pCur) );
61891   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
61892   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
61893   /* nCellKey will always be between 0 and 0xffffffff because of the say
61894   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
61895   if( nCellKey<=0 || nCellKey>0x7fffffff ){
61896     *res = 0;
61897     return SQLITE_CORRUPT_BKPT;
61898   }
61899   memset(&m, 0, sizeof(m));
61900   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
61901   if( rc ){
61902     return rc;
61903   }
61904   assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
61905   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
61906   sqlite3VdbeMemRelease(&m);
61907   return SQLITE_OK;
61908 }
61909
61910 /*
61911 ** This routine sets the value to be returned by subsequent calls to
61912 ** sqlite3_changes() on the database handle 'db'. 
61913 */
61914 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
61915   assert( sqlite3_mutex_held(db->mutex) );
61916   db->nChange = nChange;
61917   db->nTotalChange += nChange;
61918 }
61919
61920 /*
61921 ** Set a flag in the vdbe to update the change counter when it is finalised
61922 ** or reset.
61923 */
61924 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
61925   v->changeCntOn = 1;
61926 }
61927
61928 /*
61929 ** Mark every prepared statement associated with a database connection
61930 ** as expired.
61931 **
61932 ** An expired statement means that recompilation of the statement is
61933 ** recommend.  Statements expire when things happen that make their
61934 ** programs obsolete.  Removing user-defined functions or collating
61935 ** sequences, or changing an authorization function are the types of
61936 ** things that make prepared statements obsolete.
61937 */
61938 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
61939   Vdbe *p;
61940   for(p = db->pVdbe; p; p=p->pNext){
61941     p->expired = 1;
61942   }
61943 }
61944
61945 /*
61946 ** Return the database associated with the Vdbe.
61947 */
61948 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
61949   return v->db;
61950 }
61951
61952 /*
61953 ** Return a pointer to an sqlite3_value structure containing the value bound
61954 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
61955 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
61956 ** constants) to the value before returning it.
61957 **
61958 ** The returned value must be freed by the caller using sqlite3ValueFree().
61959 */
61960 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
61961   assert( iVar>0 );
61962   if( v ){
61963     Mem *pMem = &v->aVar[iVar-1];
61964     if( 0==(pMem->flags & MEM_Null) ){
61965       sqlite3_value *pRet = sqlite3ValueNew(v->db);
61966       if( pRet ){
61967         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
61968         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
61969         sqlite3VdbeMemStoreType((Mem *)pRet);
61970       }
61971       return pRet;
61972     }
61973   }
61974   return 0;
61975 }
61976
61977 /*
61978 ** Configure SQL variable iVar so that binding a new value to it signals
61979 ** to sqlite3_reoptimize() that re-preparing the statement may result
61980 ** in a better query plan.
61981 */
61982 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
61983   assert( iVar>0 );
61984   if( iVar>32 ){
61985     v->expmask = 0xffffffff;
61986   }else{
61987     v->expmask |= ((u32)1 << (iVar-1));
61988   }
61989 }
61990
61991 /************** End of vdbeaux.c *********************************************/
61992 /************** Begin file vdbeapi.c *****************************************/
61993 /*
61994 ** 2004 May 26
61995 **
61996 ** The author disclaims copyright to this source code.  In place of
61997 ** a legal notice, here is a blessing:
61998 **
61999 **    May you do good and not evil.
62000 **    May you find forgiveness for yourself and forgive others.
62001 **    May you share freely, never taking more than you give.
62002 **
62003 *************************************************************************
62004 **
62005 ** This file contains code use to implement APIs that are part of the
62006 ** VDBE.
62007 */
62008
62009 #ifndef SQLITE_OMIT_DEPRECATED
62010 /*
62011 ** Return TRUE (non-zero) of the statement supplied as an argument needs
62012 ** to be recompiled.  A statement needs to be recompiled whenever the
62013 ** execution environment changes in a way that would alter the program
62014 ** that sqlite3_prepare() generates.  For example, if new functions or
62015 ** collating sequences are registered or if an authorizer function is
62016 ** added or changed.
62017 */
62018 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
62019   Vdbe *p = (Vdbe*)pStmt;
62020   return p==0 || p->expired;
62021 }
62022 #endif
62023
62024 /*
62025 ** Check on a Vdbe to make sure it has not been finalized.  Log
62026 ** an error and return true if it has been finalized (or is otherwise
62027 ** invalid).  Return false if it is ok.
62028 */
62029 static int vdbeSafety(Vdbe *p){
62030   if( p->db==0 ){
62031     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
62032     return 1;
62033   }else{
62034     return 0;
62035   }
62036 }
62037 static int vdbeSafetyNotNull(Vdbe *p){
62038   if( p==0 ){
62039     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
62040     return 1;
62041   }else{
62042     return vdbeSafety(p);
62043   }
62044 }
62045
62046 /*
62047 ** The following routine destroys a virtual machine that is created by
62048 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
62049 ** success/failure code that describes the result of executing the virtual
62050 ** machine.
62051 **
62052 ** This routine sets the error code and string returned by
62053 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
62054 */
62055 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
62056   int rc;
62057   if( pStmt==0 ){
62058     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
62059     ** pointer is a harmless no-op. */
62060     rc = SQLITE_OK;
62061   }else{
62062     Vdbe *v = (Vdbe*)pStmt;
62063     sqlite3 *db = v->db;
62064     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
62065     sqlite3_mutex_enter(db->mutex);
62066     rc = sqlite3VdbeFinalize(v);
62067     rc = sqlite3ApiExit(db, rc);
62068     sqlite3LeaveMutexAndCloseZombie(db);
62069   }
62070   return rc;
62071 }
62072
62073 /*
62074 ** Terminate the current execution of an SQL statement and reset it
62075 ** back to its starting state so that it can be reused. A success code from
62076 ** the prior execution is returned.
62077 **
62078 ** This routine sets the error code and string returned by
62079 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
62080 */
62081 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
62082   int rc;
62083   if( pStmt==0 ){
62084     rc = SQLITE_OK;
62085   }else{
62086     Vdbe *v = (Vdbe*)pStmt;
62087     sqlite3_mutex_enter(v->db->mutex);
62088     rc = sqlite3VdbeReset(v);
62089     sqlite3VdbeRewind(v);
62090     assert( (rc & (v->db->errMask))==rc );
62091     rc = sqlite3ApiExit(v->db, rc);
62092     sqlite3_mutex_leave(v->db->mutex);
62093   }
62094   return rc;
62095 }
62096
62097 /*
62098 ** Set all the parameters in the compiled SQL statement to NULL.
62099 */
62100 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
62101   int i;
62102   int rc = SQLITE_OK;
62103   Vdbe *p = (Vdbe*)pStmt;
62104 #if SQLITE_THREADSAFE
62105   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
62106 #endif
62107   sqlite3_mutex_enter(mutex);
62108   for(i=0; i<p->nVar; i++){
62109     sqlite3VdbeMemRelease(&p->aVar[i]);
62110     p->aVar[i].flags = MEM_Null;
62111   }
62112   if( p->isPrepareV2 && p->expmask ){
62113     p->expired = 1;
62114   }
62115   sqlite3_mutex_leave(mutex);
62116   return rc;
62117 }
62118
62119
62120 /**************************** sqlite3_value_  *******************************
62121 ** The following routines extract information from a Mem or sqlite3_value
62122 ** structure.
62123 */
62124 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
62125   Mem *p = (Mem*)pVal;
62126   if( p->flags & (MEM_Blob|MEM_Str) ){
62127     sqlite3VdbeMemExpandBlob(p);
62128     p->flags &= ~MEM_Str;
62129     p->flags |= MEM_Blob;
62130     return p->n ? p->z : 0;
62131   }else{
62132     return sqlite3_value_text(pVal);
62133   }
62134 }
62135 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
62136   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
62137 }
62138 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
62139   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
62140 }
62141 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
62142   return sqlite3VdbeRealValue((Mem*)pVal);
62143 }
62144 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
62145   return (int)sqlite3VdbeIntValue((Mem*)pVal);
62146 }
62147 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
62148   return sqlite3VdbeIntValue((Mem*)pVal);
62149 }
62150 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
62151   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
62152 }
62153 #ifndef SQLITE_OMIT_UTF16
62154 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
62155   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
62156 }
62157 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
62158   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
62159 }
62160 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
62161   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
62162 }
62163 #endif /* SQLITE_OMIT_UTF16 */
62164 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
62165   return pVal->type;
62166 }
62167
62168 /**************************** sqlite3_result_  *******************************
62169 ** The following routines are used by user-defined functions to specify
62170 ** the function result.
62171 **
62172 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
62173 ** result as a string or blob but if the string or blob is too large, it
62174 ** then sets the error code to SQLITE_TOOBIG
62175 */
62176 static void setResultStrOrError(
62177   sqlite3_context *pCtx,  /* Function context */
62178   const char *z,          /* String pointer */
62179   int n,                  /* Bytes in string, or negative */
62180   u8 enc,                 /* Encoding of z.  0 for BLOBs */
62181   void (*xDel)(void*)     /* Destructor function */
62182 ){
62183   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
62184     sqlite3_result_error_toobig(pCtx);
62185   }
62186 }
62187 SQLITE_API void sqlite3_result_blob(
62188   sqlite3_context *pCtx, 
62189   const void *z, 
62190   int n, 
62191   void (*xDel)(void *)
62192 ){
62193   assert( n>=0 );
62194   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62195   setResultStrOrError(pCtx, z, n, 0, xDel);
62196 }
62197 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
62198   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62199   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
62200 }
62201 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
62202   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62203   pCtx->isError = SQLITE_ERROR;
62204   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
62205 }
62206 #ifndef SQLITE_OMIT_UTF16
62207 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
62208   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62209   pCtx->isError = SQLITE_ERROR;
62210   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
62211 }
62212 #endif
62213 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
62214   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62215   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
62216 }
62217 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
62218   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62219   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
62220 }
62221 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
62222   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62223   sqlite3VdbeMemSetNull(&pCtx->s);
62224 }
62225 SQLITE_API void sqlite3_result_text(
62226   sqlite3_context *pCtx, 
62227   const char *z, 
62228   int n,
62229   void (*xDel)(void *)
62230 ){
62231   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62232   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
62233 }
62234 #ifndef SQLITE_OMIT_UTF16
62235 SQLITE_API void sqlite3_result_text16(
62236   sqlite3_context *pCtx, 
62237   const void *z, 
62238   int n, 
62239   void (*xDel)(void *)
62240 ){
62241   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62242   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
62243 }
62244 SQLITE_API void sqlite3_result_text16be(
62245   sqlite3_context *pCtx, 
62246   const void *z, 
62247   int n, 
62248   void (*xDel)(void *)
62249 ){
62250   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62251   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
62252 }
62253 SQLITE_API void sqlite3_result_text16le(
62254   sqlite3_context *pCtx, 
62255   const void *z, 
62256   int n, 
62257   void (*xDel)(void *)
62258 ){
62259   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62260   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
62261 }
62262 #endif /* SQLITE_OMIT_UTF16 */
62263 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
62264   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62265   sqlite3VdbeMemCopy(&pCtx->s, pValue);
62266 }
62267 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
62268   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62269   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
62270 }
62271 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
62272   pCtx->isError = errCode;
62273   if( pCtx->s.flags & MEM_Null ){
62274     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
62275                          SQLITE_UTF8, SQLITE_STATIC);
62276   }
62277 }
62278
62279 /* Force an SQLITE_TOOBIG error. */
62280 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
62281   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62282   pCtx->isError = SQLITE_TOOBIG;
62283   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
62284                        SQLITE_UTF8, SQLITE_STATIC);
62285 }
62286
62287 /* An SQLITE_NOMEM error. */
62288 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
62289   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62290   sqlite3VdbeMemSetNull(&pCtx->s);
62291   pCtx->isError = SQLITE_NOMEM;
62292   pCtx->s.db->mallocFailed = 1;
62293 }
62294
62295 /*
62296 ** This function is called after a transaction has been committed. It 
62297 ** invokes callbacks registered with sqlite3_wal_hook() as required.
62298 */
62299 static int doWalCallbacks(sqlite3 *db){
62300   int rc = SQLITE_OK;
62301 #ifndef SQLITE_OMIT_WAL
62302   int i;
62303   for(i=0; i<db->nDb; i++){
62304     Btree *pBt = db->aDb[i].pBt;
62305     if( pBt ){
62306       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
62307       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
62308         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
62309       }
62310     }
62311   }
62312 #endif
62313   return rc;
62314 }
62315
62316 /*
62317 ** Execute the statement pStmt, either until a row of data is ready, the
62318 ** statement is completely executed or an error occurs.
62319 **
62320 ** This routine implements the bulk of the logic behind the sqlite_step()
62321 ** API.  The only thing omitted is the automatic recompile if a 
62322 ** schema change has occurred.  That detail is handled by the
62323 ** outer sqlite3_step() wrapper procedure.
62324 */
62325 static int sqlite3Step(Vdbe *p){
62326   sqlite3 *db;
62327   int rc;
62328
62329   assert(p);
62330   if( p->magic!=VDBE_MAGIC_RUN ){
62331     /* We used to require that sqlite3_reset() be called before retrying
62332     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
62333     ** with version 3.7.0, we changed this so that sqlite3_reset() would
62334     ** be called automatically instead of throwing the SQLITE_MISUSE error.
62335     ** This "automatic-reset" change is not technically an incompatibility, 
62336     ** since any application that receives an SQLITE_MISUSE is broken by
62337     ** definition.
62338     **
62339     ** Nevertheless, some published applications that were originally written
62340     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
62341     ** returns, and those were broken by the automatic-reset change.  As a
62342     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
62343     ** legacy behavior of returning SQLITE_MISUSE for cases where the 
62344     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
62345     ** or SQLITE_BUSY error.
62346     */
62347 #ifdef SQLITE_OMIT_AUTORESET
62348     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
62349       sqlite3_reset((sqlite3_stmt*)p);
62350     }else{
62351       return SQLITE_MISUSE_BKPT;
62352     }
62353 #else
62354     sqlite3_reset((sqlite3_stmt*)p);
62355 #endif
62356   }
62357
62358   /* Check that malloc() has not failed. If it has, return early. */
62359   db = p->db;
62360   if( db->mallocFailed ){
62361     p->rc = SQLITE_NOMEM;
62362     return SQLITE_NOMEM;
62363   }
62364
62365   if( p->pc<=0 && p->expired ){
62366     p->rc = SQLITE_SCHEMA;
62367     rc = SQLITE_ERROR;
62368     goto end_of_step;
62369   }
62370   if( p->pc<0 ){
62371     /* If there are no other statements currently running, then
62372     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
62373     ** from interrupting a statement that has not yet started.
62374     */
62375     if( db->activeVdbeCnt==0 ){
62376       db->u1.isInterrupted = 0;
62377     }
62378
62379     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
62380
62381 #ifndef SQLITE_OMIT_TRACE
62382     if( db->xProfile && !db->init.busy ){
62383       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
62384     }
62385 #endif
62386
62387     db->activeVdbeCnt++;
62388     if( p->readOnly==0 ) db->writeVdbeCnt++;
62389     p->pc = 0;
62390   }
62391 #ifndef SQLITE_OMIT_EXPLAIN
62392   if( p->explain ){
62393     rc = sqlite3VdbeList(p);
62394   }else
62395 #endif /* SQLITE_OMIT_EXPLAIN */
62396   {
62397     db->vdbeExecCnt++;
62398     rc = sqlite3VdbeExec(p);
62399     db->vdbeExecCnt--;
62400   }
62401
62402 #ifndef SQLITE_OMIT_TRACE
62403   /* Invoke the profile callback if there is one
62404   */
62405   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
62406     sqlite3_int64 iNow;
62407     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
62408     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
62409   }
62410 #endif
62411
62412   if( rc==SQLITE_DONE ){
62413     assert( p->rc==SQLITE_OK );
62414     p->rc = doWalCallbacks(db);
62415     if( p->rc!=SQLITE_OK ){
62416       rc = SQLITE_ERROR;
62417     }
62418   }
62419
62420   db->errCode = rc;
62421   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
62422     p->rc = SQLITE_NOMEM;
62423   }
62424 end_of_step:
62425   /* At this point local variable rc holds the value that should be 
62426   ** returned if this statement was compiled using the legacy 
62427   ** sqlite3_prepare() interface. According to the docs, this can only
62428   ** be one of the values in the first assert() below. Variable p->rc 
62429   ** contains the value that would be returned if sqlite3_finalize() 
62430   ** were called on statement p.
62431   */
62432   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
62433        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
62434   );
62435   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
62436   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
62437     /* If this statement was prepared using sqlite3_prepare_v2(), and an
62438     ** error has occurred, then return the error code in p->rc to the
62439     ** caller. Set the error code in the database handle to the same value.
62440     */ 
62441     rc = sqlite3VdbeTransferError(p);
62442   }
62443   return (rc&db->errMask);
62444 }
62445
62446 /*
62447 ** The maximum number of times that a statement will try to reparse
62448 ** itself before giving up and returning SQLITE_SCHEMA.
62449 */
62450 #ifndef SQLITE_MAX_SCHEMA_RETRY
62451 # define SQLITE_MAX_SCHEMA_RETRY 5
62452 #endif
62453
62454 /*
62455 ** This is the top-level implementation of sqlite3_step().  Call
62456 ** sqlite3Step() to do most of the work.  If a schema error occurs,
62457 ** call sqlite3Reprepare() and try again.
62458 */
62459 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
62460   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
62461   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
62462   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
62463   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
62464   sqlite3 *db;             /* The database connection */
62465
62466   if( vdbeSafetyNotNull(v) ){
62467     return SQLITE_MISUSE_BKPT;
62468   }
62469   db = v->db;
62470   sqlite3_mutex_enter(db->mutex);
62471   v->doingRerun = 0;
62472   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
62473          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
62474          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
62475     sqlite3_reset(pStmt);
62476     v->doingRerun = 1;
62477     assert( v->expired==0 );
62478   }
62479   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
62480     /* This case occurs after failing to recompile an sql statement. 
62481     ** The error message from the SQL compiler has already been loaded 
62482     ** into the database handle. This block copies the error message 
62483     ** from the database handle into the statement and sets the statement
62484     ** program counter to 0 to ensure that when the statement is 
62485     ** finalized or reset the parser error message is available via
62486     ** sqlite3_errmsg() and sqlite3_errcode().
62487     */
62488     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
62489     sqlite3DbFree(db, v->zErrMsg);
62490     if( !db->mallocFailed ){
62491       v->zErrMsg = sqlite3DbStrDup(db, zErr);
62492       v->rc = rc2;
62493     } else {
62494       v->zErrMsg = 0;
62495       v->rc = rc = SQLITE_NOMEM;
62496     }
62497   }
62498   rc = sqlite3ApiExit(db, rc);
62499   sqlite3_mutex_leave(db->mutex);
62500   return rc;
62501 }
62502
62503 /*
62504 ** Extract the user data from a sqlite3_context structure and return a
62505 ** pointer to it.
62506 */
62507 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
62508   assert( p && p->pFunc );
62509   return p->pFunc->pUserData;
62510 }
62511
62512 /*
62513 ** Extract the user data from a sqlite3_context structure and return a
62514 ** pointer to it.
62515 **
62516 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
62517 ** returns a copy of the pointer to the database connection (the 1st
62518 ** parameter) of the sqlite3_create_function() and
62519 ** sqlite3_create_function16() routines that originally registered the
62520 ** application defined function.
62521 */
62522 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
62523   assert( p && p->pFunc );
62524   return p->s.db;
62525 }
62526
62527 /*
62528 ** The following is the implementation of an SQL function that always
62529 ** fails with an error message stating that the function is used in the
62530 ** wrong context.  The sqlite3_overload_function() API might construct
62531 ** SQL function that use this routine so that the functions will exist
62532 ** for name resolution but are actually overloaded by the xFindFunction
62533 ** method of virtual tables.
62534 */
62535 SQLITE_PRIVATE void sqlite3InvalidFunction(
62536   sqlite3_context *context,  /* The function calling context */
62537   int NotUsed,               /* Number of arguments to the function */
62538   sqlite3_value **NotUsed2   /* Value of each argument */
62539 ){
62540   const char *zName = context->pFunc->zName;
62541   char *zErr;
62542   UNUSED_PARAMETER2(NotUsed, NotUsed2);
62543   zErr = sqlite3_mprintf(
62544       "unable to use function %s in the requested context", zName);
62545   sqlite3_result_error(context, zErr, -1);
62546   sqlite3_free(zErr);
62547 }
62548
62549 /*
62550 ** Allocate or return the aggregate context for a user function.  A new
62551 ** context is allocated on the first call.  Subsequent calls return the
62552 ** same context that was returned on prior calls.
62553 */
62554 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
62555   Mem *pMem;
62556   assert( p && p->pFunc && p->pFunc->xStep );
62557   assert( sqlite3_mutex_held(p->s.db->mutex) );
62558   pMem = p->pMem;
62559   testcase( nByte<0 );
62560   if( (pMem->flags & MEM_Agg)==0 ){
62561     if( nByte<=0 ){
62562       sqlite3VdbeMemReleaseExternal(pMem);
62563       pMem->flags = MEM_Null;
62564       pMem->z = 0;
62565     }else{
62566       sqlite3VdbeMemGrow(pMem, nByte, 0);
62567       pMem->flags = MEM_Agg;
62568       pMem->u.pDef = p->pFunc;
62569       if( pMem->z ){
62570         memset(pMem->z, 0, nByte);
62571       }
62572     }
62573   }
62574   return (void*)pMem->z;
62575 }
62576
62577 /*
62578 ** Return the auxilary data pointer, if any, for the iArg'th argument to
62579 ** the user-function defined by pCtx.
62580 */
62581 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
62582   VdbeFunc *pVdbeFunc;
62583
62584   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62585   pVdbeFunc = pCtx->pVdbeFunc;
62586   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
62587     return 0;
62588   }
62589   return pVdbeFunc->apAux[iArg].pAux;
62590 }
62591
62592 /*
62593 ** Set the auxilary data pointer and delete function, for the iArg'th
62594 ** argument to the user-function defined by pCtx. Any previous value is
62595 ** deleted by calling the delete function specified when it was set.
62596 */
62597 SQLITE_API void sqlite3_set_auxdata(
62598   sqlite3_context *pCtx, 
62599   int iArg, 
62600   void *pAux, 
62601   void (*xDelete)(void*)
62602 ){
62603   struct AuxData *pAuxData;
62604   VdbeFunc *pVdbeFunc;
62605   if( iArg<0 ) goto failed;
62606
62607   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62608   pVdbeFunc = pCtx->pVdbeFunc;
62609   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
62610     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
62611     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
62612     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
62613     if( !pVdbeFunc ){
62614       goto failed;
62615     }
62616     pCtx->pVdbeFunc = pVdbeFunc;
62617     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
62618     pVdbeFunc->nAux = iArg+1;
62619     pVdbeFunc->pFunc = pCtx->pFunc;
62620   }
62621
62622   pAuxData = &pVdbeFunc->apAux[iArg];
62623   if( pAuxData->pAux && pAuxData->xDelete ){
62624     pAuxData->xDelete(pAuxData->pAux);
62625   }
62626   pAuxData->pAux = pAux;
62627   pAuxData->xDelete = xDelete;
62628   return;
62629
62630 failed:
62631   if( xDelete ){
62632     xDelete(pAux);
62633   }
62634 }
62635
62636 #ifndef SQLITE_OMIT_DEPRECATED
62637 /*
62638 ** Return the number of times the Step function of a aggregate has been 
62639 ** called.
62640 **
62641 ** This function is deprecated.  Do not use it for new code.  It is
62642 ** provide only to avoid breaking legacy code.  New aggregate function
62643 ** implementations should keep their own counts within their aggregate
62644 ** context.
62645 */
62646 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
62647   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
62648   return p->pMem->n;
62649 }
62650 #endif
62651
62652 /*
62653 ** Return the number of columns in the result set for the statement pStmt.
62654 */
62655 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
62656   Vdbe *pVm = (Vdbe *)pStmt;
62657   return pVm ? pVm->nResColumn : 0;
62658 }
62659
62660 /*
62661 ** Return the number of values available from the current row of the
62662 ** currently executing statement pStmt.
62663 */
62664 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
62665   Vdbe *pVm = (Vdbe *)pStmt;
62666   if( pVm==0 || pVm->pResultSet==0 ) return 0;
62667   return pVm->nResColumn;
62668 }
62669
62670
62671 /*
62672 ** Check to see if column iCol of the given statement is valid.  If
62673 ** it is, return a pointer to the Mem for the value of that column.
62674 ** If iCol is not valid, return a pointer to a Mem which has a value
62675 ** of NULL.
62676 */
62677 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
62678   Vdbe *pVm;
62679   Mem *pOut;
62680
62681   pVm = (Vdbe *)pStmt;
62682   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
62683     sqlite3_mutex_enter(pVm->db->mutex);
62684     pOut = &pVm->pResultSet[i];
62685   }else{
62686     /* If the value passed as the second argument is out of range, return
62687     ** a pointer to the following static Mem object which contains the
62688     ** value SQL NULL. Even though the Mem structure contains an element
62689     ** of type i64, on certain architectures (x86) with certain compiler
62690     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
62691     ** instead of an 8-byte one. This all works fine, except that when
62692     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
62693     ** that a Mem structure is located on an 8-byte boundary. To prevent
62694     ** these assert()s from failing, when building with SQLITE_DEBUG defined
62695     ** using gcc, we force nullMem to be 8-byte aligned using the magical
62696     ** __attribute__((aligned(8))) macro.  */
62697     static const Mem nullMem 
62698 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
62699       __attribute__((aligned(8))) 
62700 #endif
62701       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
62702 #ifdef SQLITE_DEBUG
62703          0, 0,  /* pScopyFrom, pFiller */
62704 #endif
62705          0, 0 };
62706
62707     if( pVm && ALWAYS(pVm->db) ){
62708       sqlite3_mutex_enter(pVm->db->mutex);
62709       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
62710     }
62711     pOut = (Mem*)&nullMem;
62712   }
62713   return pOut;
62714 }
62715
62716 /*
62717 ** This function is called after invoking an sqlite3_value_XXX function on a 
62718 ** column value (i.e. a value returned by evaluating an SQL expression in the
62719 ** select list of a SELECT statement) that may cause a malloc() failure. If 
62720 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
62721 ** code of statement pStmt set to SQLITE_NOMEM.
62722 **
62723 ** Specifically, this is called from within:
62724 **
62725 **     sqlite3_column_int()
62726 **     sqlite3_column_int64()
62727 **     sqlite3_column_text()
62728 **     sqlite3_column_text16()
62729 **     sqlite3_column_real()
62730 **     sqlite3_column_bytes()
62731 **     sqlite3_column_bytes16()
62732 **     sqiite3_column_blob()
62733 */
62734 static void columnMallocFailure(sqlite3_stmt *pStmt)
62735 {
62736   /* If malloc() failed during an encoding conversion within an
62737   ** sqlite3_column_XXX API, then set the return code of the statement to
62738   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
62739   ** and _finalize() will return NOMEM.
62740   */
62741   Vdbe *p = (Vdbe *)pStmt;
62742   if( p ){
62743     p->rc = sqlite3ApiExit(p->db, p->rc);
62744     sqlite3_mutex_leave(p->db->mutex);
62745   }
62746 }
62747
62748 /**************************** sqlite3_column_  *******************************
62749 ** The following routines are used to access elements of the current row
62750 ** in the result set.
62751 */
62752 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
62753   const void *val;
62754   val = sqlite3_value_blob( columnMem(pStmt,i) );
62755   /* Even though there is no encoding conversion, value_blob() might
62756   ** need to call malloc() to expand the result of a zeroblob() 
62757   ** expression. 
62758   */
62759   columnMallocFailure(pStmt);
62760   return val;
62761 }
62762 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
62763   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
62764   columnMallocFailure(pStmt);
62765   return val;
62766 }
62767 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
62768   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
62769   columnMallocFailure(pStmt);
62770   return val;
62771 }
62772 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
62773   double val = sqlite3_value_double( columnMem(pStmt,i) );
62774   columnMallocFailure(pStmt);
62775   return val;
62776 }
62777 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
62778   int val = sqlite3_value_int( columnMem(pStmt,i) );
62779   columnMallocFailure(pStmt);
62780   return val;
62781 }
62782 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
62783   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
62784   columnMallocFailure(pStmt);
62785   return val;
62786 }
62787 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
62788   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
62789   columnMallocFailure(pStmt);
62790   return val;
62791 }
62792 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
62793   Mem *pOut = columnMem(pStmt, i);
62794   if( pOut->flags&MEM_Static ){
62795     pOut->flags &= ~MEM_Static;
62796     pOut->flags |= MEM_Ephem;
62797   }
62798   columnMallocFailure(pStmt);
62799   return (sqlite3_value *)pOut;
62800 }
62801 #ifndef SQLITE_OMIT_UTF16
62802 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
62803   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
62804   columnMallocFailure(pStmt);
62805   return val;
62806 }
62807 #endif /* SQLITE_OMIT_UTF16 */
62808 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
62809   int iType = sqlite3_value_type( columnMem(pStmt,i) );
62810   columnMallocFailure(pStmt);
62811   return iType;
62812 }
62813
62814 /* The following function is experimental and subject to change or
62815 ** removal */
62816 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
62817 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
62818 **}
62819 */
62820
62821 /*
62822 ** Convert the N-th element of pStmt->pColName[] into a string using
62823 ** xFunc() then return that string.  If N is out of range, return 0.
62824 **
62825 ** There are up to 5 names for each column.  useType determines which
62826 ** name is returned.  Here are the names:
62827 **
62828 **    0      The column name as it should be displayed for output
62829 **    1      The datatype name for the column
62830 **    2      The name of the database that the column derives from
62831 **    3      The name of the table that the column derives from
62832 **    4      The name of the table column that the result column derives from
62833 **
62834 ** If the result is not a simple column reference (if it is an expression
62835 ** or a constant) then useTypes 2, 3, and 4 return NULL.
62836 */
62837 static const void *columnName(
62838   sqlite3_stmt *pStmt,
62839   int N,
62840   const void *(*xFunc)(Mem*),
62841   int useType
62842 ){
62843   const void *ret = 0;
62844   Vdbe *p = (Vdbe *)pStmt;
62845   int n;
62846   sqlite3 *db = p->db;
62847   
62848   assert( db!=0 );
62849   n = sqlite3_column_count(pStmt);
62850   if( N<n && N>=0 ){
62851     N += useType*n;
62852     sqlite3_mutex_enter(db->mutex);
62853     assert( db->mallocFailed==0 );
62854     ret = xFunc(&p->aColName[N]);
62855      /* A malloc may have failed inside of the xFunc() call. If this
62856     ** is the case, clear the mallocFailed flag and return NULL.
62857     */
62858     if( db->mallocFailed ){
62859       db->mallocFailed = 0;
62860       ret = 0;
62861     }
62862     sqlite3_mutex_leave(db->mutex);
62863   }
62864   return ret;
62865 }
62866
62867 /*
62868 ** Return the name of the Nth column of the result set returned by SQL
62869 ** statement pStmt.
62870 */
62871 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
62872   return columnName(
62873       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
62874 }
62875 #ifndef SQLITE_OMIT_UTF16
62876 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
62877   return columnName(
62878       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
62879 }
62880 #endif
62881
62882 /*
62883 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
62884 ** not define OMIT_DECLTYPE.
62885 */
62886 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
62887 # error "Must not define both SQLITE_OMIT_DECLTYPE \
62888          and SQLITE_ENABLE_COLUMN_METADATA"
62889 #endif
62890
62891 #ifndef SQLITE_OMIT_DECLTYPE
62892 /*
62893 ** Return the column declaration type (if applicable) of the 'i'th column
62894 ** of the result set of SQL statement pStmt.
62895 */
62896 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
62897   return columnName(
62898       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
62899 }
62900 #ifndef SQLITE_OMIT_UTF16
62901 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
62902   return columnName(
62903       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
62904 }
62905 #endif /* SQLITE_OMIT_UTF16 */
62906 #endif /* SQLITE_OMIT_DECLTYPE */
62907
62908 #ifdef SQLITE_ENABLE_COLUMN_METADATA
62909 /*
62910 ** Return the name of the database from which a result column derives.
62911 ** NULL is returned if the result column is an expression or constant or
62912 ** anything else which is not an unabiguous reference to a database column.
62913 */
62914 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
62915   return columnName(
62916       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
62917 }
62918 #ifndef SQLITE_OMIT_UTF16
62919 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
62920   return columnName(
62921       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
62922 }
62923 #endif /* SQLITE_OMIT_UTF16 */
62924
62925 /*
62926 ** Return the name of the table from which a result column derives.
62927 ** NULL is returned if the result column is an expression or constant or
62928 ** anything else which is not an unabiguous reference to a database column.
62929 */
62930 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
62931   return columnName(
62932       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
62933 }
62934 #ifndef SQLITE_OMIT_UTF16
62935 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
62936   return columnName(
62937       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
62938 }
62939 #endif /* SQLITE_OMIT_UTF16 */
62940
62941 /*
62942 ** Return the name of the table column from which a result column derives.
62943 ** NULL is returned if the result column is an expression or constant or
62944 ** anything else which is not an unabiguous reference to a database column.
62945 */
62946 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
62947   return columnName(
62948       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
62949 }
62950 #ifndef SQLITE_OMIT_UTF16
62951 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
62952   return columnName(
62953       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
62954 }
62955 #endif /* SQLITE_OMIT_UTF16 */
62956 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
62957
62958
62959 /******************************* sqlite3_bind_  ***************************
62960 ** 
62961 ** Routines used to attach values to wildcards in a compiled SQL statement.
62962 */
62963 /*
62964 ** Unbind the value bound to variable i in virtual machine p. This is the 
62965 ** the same as binding a NULL value to the column. If the "i" parameter is
62966 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
62967 **
62968 ** A successful evaluation of this routine acquires the mutex on p.
62969 ** the mutex is released if any kind of error occurs.
62970 **
62971 ** The error code stored in database p->db is overwritten with the return
62972 ** value in any case.
62973 */
62974 static int vdbeUnbind(Vdbe *p, int i){
62975   Mem *pVar;
62976   if( vdbeSafetyNotNull(p) ){
62977     return SQLITE_MISUSE_BKPT;
62978   }
62979   sqlite3_mutex_enter(p->db->mutex);
62980   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
62981     sqlite3Error(p->db, SQLITE_MISUSE, 0);
62982     sqlite3_mutex_leave(p->db->mutex);
62983     sqlite3_log(SQLITE_MISUSE, 
62984         "bind on a busy prepared statement: [%s]", p->zSql);
62985     return SQLITE_MISUSE_BKPT;
62986   }
62987   if( i<1 || i>p->nVar ){
62988     sqlite3Error(p->db, SQLITE_RANGE, 0);
62989     sqlite3_mutex_leave(p->db->mutex);
62990     return SQLITE_RANGE;
62991   }
62992   i--;
62993   pVar = &p->aVar[i];
62994   sqlite3VdbeMemRelease(pVar);
62995   pVar->flags = MEM_Null;
62996   sqlite3Error(p->db, SQLITE_OK, 0);
62997
62998   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
62999   ** binding a new value to this variable invalidates the current query plan.
63000   **
63001   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
63002   ** parameter in the WHERE clause might influence the choice of query plan
63003   ** for a statement, then the statement will be automatically recompiled,
63004   ** as if there had been a schema change, on the first sqlite3_step() call
63005   ** following any change to the bindings of that parameter.
63006   */
63007   if( p->isPrepareV2 &&
63008      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
63009   ){
63010     p->expired = 1;
63011   }
63012   return SQLITE_OK;
63013 }
63014
63015 /*
63016 ** Bind a text or BLOB value.
63017 */
63018 static int bindText(
63019   sqlite3_stmt *pStmt,   /* The statement to bind against */
63020   int i,                 /* Index of the parameter to bind */
63021   const void *zData,     /* Pointer to the data to be bound */
63022   int nData,             /* Number of bytes of data to be bound */
63023   void (*xDel)(void*),   /* Destructor for the data */
63024   u8 encoding            /* Encoding for the data */
63025 ){
63026   Vdbe *p = (Vdbe *)pStmt;
63027   Mem *pVar;
63028   int rc;
63029
63030   rc = vdbeUnbind(p, i);
63031   if( rc==SQLITE_OK ){
63032     if( zData!=0 ){
63033       pVar = &p->aVar[i-1];
63034       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
63035       if( rc==SQLITE_OK && encoding!=0 ){
63036         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
63037       }
63038       sqlite3Error(p->db, rc, 0);
63039       rc = sqlite3ApiExit(p->db, rc);
63040     }
63041     sqlite3_mutex_leave(p->db->mutex);
63042   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
63043     xDel((void*)zData);
63044   }
63045   return rc;
63046 }
63047
63048
63049 /*
63050 ** Bind a blob value to an SQL statement variable.
63051 */
63052 SQLITE_API int sqlite3_bind_blob(
63053   sqlite3_stmt *pStmt, 
63054   int i, 
63055   const void *zData, 
63056   int nData, 
63057   void (*xDel)(void*)
63058 ){
63059   return bindText(pStmt, i, zData, nData, xDel, 0);
63060 }
63061 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
63062   int rc;
63063   Vdbe *p = (Vdbe *)pStmt;
63064   rc = vdbeUnbind(p, i);
63065   if( rc==SQLITE_OK ){
63066     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
63067     sqlite3_mutex_leave(p->db->mutex);
63068   }
63069   return rc;
63070 }
63071 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
63072   return sqlite3_bind_int64(p, i, (i64)iValue);
63073 }
63074 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
63075   int rc;
63076   Vdbe *p = (Vdbe *)pStmt;
63077   rc = vdbeUnbind(p, i);
63078   if( rc==SQLITE_OK ){
63079     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
63080     sqlite3_mutex_leave(p->db->mutex);
63081   }
63082   return rc;
63083 }
63084 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
63085   int rc;
63086   Vdbe *p = (Vdbe*)pStmt;
63087   rc = vdbeUnbind(p, i);
63088   if( rc==SQLITE_OK ){
63089     sqlite3_mutex_leave(p->db->mutex);
63090   }
63091   return rc;
63092 }
63093 SQLITE_API int sqlite3_bind_text( 
63094   sqlite3_stmt *pStmt, 
63095   int i, 
63096   const char *zData, 
63097   int nData, 
63098   void (*xDel)(void*)
63099 ){
63100   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
63101 }
63102 #ifndef SQLITE_OMIT_UTF16
63103 SQLITE_API int sqlite3_bind_text16(
63104   sqlite3_stmt *pStmt, 
63105   int i, 
63106   const void *zData, 
63107   int nData, 
63108   void (*xDel)(void*)
63109 ){
63110   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
63111 }
63112 #endif /* SQLITE_OMIT_UTF16 */
63113 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
63114   int rc;
63115   switch( pValue->type ){
63116     case SQLITE_INTEGER: {
63117       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
63118       break;
63119     }
63120     case SQLITE_FLOAT: {
63121       rc = sqlite3_bind_double(pStmt, i, pValue->r);
63122       break;
63123     }
63124     case SQLITE_BLOB: {
63125       if( pValue->flags & MEM_Zero ){
63126         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
63127       }else{
63128         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
63129       }
63130       break;
63131     }
63132     case SQLITE_TEXT: {
63133       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
63134                               pValue->enc);
63135       break;
63136     }
63137     default: {
63138       rc = sqlite3_bind_null(pStmt, i);
63139       break;
63140     }
63141   }
63142   return rc;
63143 }
63144 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
63145   int rc;
63146   Vdbe *p = (Vdbe *)pStmt;
63147   rc = vdbeUnbind(p, i);
63148   if( rc==SQLITE_OK ){
63149     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
63150     sqlite3_mutex_leave(p->db->mutex);
63151   }
63152   return rc;
63153 }
63154
63155 /*
63156 ** Return the number of wildcards that can be potentially bound to.
63157 ** This routine is added to support DBD::SQLite.  
63158 */
63159 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
63160   Vdbe *p = (Vdbe*)pStmt;
63161   return p ? p->nVar : 0;
63162 }
63163
63164 /*
63165 ** Return the name of a wildcard parameter.  Return NULL if the index
63166 ** is out of range or if the wildcard is unnamed.
63167 **
63168 ** The result is always UTF-8.
63169 */
63170 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
63171   Vdbe *p = (Vdbe*)pStmt;
63172   if( p==0 || i<1 || i>p->nzVar ){
63173     return 0;
63174   }
63175   return p->azVar[i-1];
63176 }
63177
63178 /*
63179 ** Given a wildcard parameter name, return the index of the variable
63180 ** with that name.  If there is no variable with the given name,
63181 ** return 0.
63182 */
63183 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
63184   int i;
63185   if( p==0 ){
63186     return 0;
63187   }
63188   if( zName ){
63189     for(i=0; i<p->nzVar; i++){
63190       const char *z = p->azVar[i];
63191       if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
63192         return i+1;
63193       }
63194     }
63195   }
63196   return 0;
63197 }
63198 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
63199   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
63200 }
63201
63202 /*
63203 ** Transfer all bindings from the first statement over to the second.
63204 */
63205 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
63206   Vdbe *pFrom = (Vdbe*)pFromStmt;
63207   Vdbe *pTo = (Vdbe*)pToStmt;
63208   int i;
63209   assert( pTo->db==pFrom->db );
63210   assert( pTo->nVar==pFrom->nVar );
63211   sqlite3_mutex_enter(pTo->db->mutex);
63212   for(i=0; i<pFrom->nVar; i++){
63213     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
63214   }
63215   sqlite3_mutex_leave(pTo->db->mutex);
63216   return SQLITE_OK;
63217 }
63218
63219 #ifndef SQLITE_OMIT_DEPRECATED
63220 /*
63221 ** Deprecated external interface.  Internal/core SQLite code
63222 ** should call sqlite3TransferBindings.
63223 **
63224 ** Is is misuse to call this routine with statements from different
63225 ** database connections.  But as this is a deprecated interface, we
63226 ** will not bother to check for that condition.
63227 **
63228 ** If the two statements contain a different number of bindings, then
63229 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
63230 ** SQLITE_OK is returned.
63231 */
63232 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
63233   Vdbe *pFrom = (Vdbe*)pFromStmt;
63234   Vdbe *pTo = (Vdbe*)pToStmt;
63235   if( pFrom->nVar!=pTo->nVar ){
63236     return SQLITE_ERROR;
63237   }
63238   if( pTo->isPrepareV2 && pTo->expmask ){
63239     pTo->expired = 1;
63240   }
63241   if( pFrom->isPrepareV2 && pFrom->expmask ){
63242     pFrom->expired = 1;
63243   }
63244   return sqlite3TransferBindings(pFromStmt, pToStmt);
63245 }
63246 #endif
63247
63248 /*
63249 ** Return the sqlite3* database handle to which the prepared statement given
63250 ** in the argument belongs.  This is the same database handle that was
63251 ** the first argument to the sqlite3_prepare() that was used to create
63252 ** the statement in the first place.
63253 */
63254 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
63255   return pStmt ? ((Vdbe*)pStmt)->db : 0;
63256 }
63257
63258 /*
63259 ** Return true if the prepared statement is guaranteed to not modify the
63260 ** database.
63261 */
63262 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
63263   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
63264 }
63265
63266 /*
63267 ** Return true if the prepared statement is in need of being reset.
63268 */
63269 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
63270   Vdbe *v = (Vdbe*)pStmt;
63271   return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
63272 }
63273
63274 /*
63275 ** Return a pointer to the next prepared statement after pStmt associated
63276 ** with database connection pDb.  If pStmt is NULL, return the first
63277 ** prepared statement for the database connection.  Return NULL if there
63278 ** are no more.
63279 */
63280 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
63281   sqlite3_stmt *pNext;
63282   sqlite3_mutex_enter(pDb->mutex);
63283   if( pStmt==0 ){
63284     pNext = (sqlite3_stmt*)pDb->pVdbe;
63285   }else{
63286     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
63287   }
63288   sqlite3_mutex_leave(pDb->mutex);
63289   return pNext;
63290 }
63291
63292 /*
63293 ** Return the value of a status counter for a prepared statement
63294 */
63295 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
63296   Vdbe *pVdbe = (Vdbe*)pStmt;
63297   int v = pVdbe->aCounter[op-1];
63298   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
63299   return v;
63300 }
63301
63302 /************** End of vdbeapi.c *********************************************/
63303 /************** Begin file vdbetrace.c ***************************************/
63304 /*
63305 ** 2009 November 25
63306 **
63307 ** The author disclaims copyright to this source code.  In place of
63308 ** a legal notice, here is a blessing:
63309 **
63310 **    May you do good and not evil.
63311 **    May you find forgiveness for yourself and forgive others.
63312 **    May you share freely, never taking more than you give.
63313 **
63314 *************************************************************************
63315 **
63316 ** This file contains code used to insert the values of host parameters
63317 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
63318 **
63319 ** The Vdbe parse-tree explainer is also found here.
63320 */
63321
63322 #ifndef SQLITE_OMIT_TRACE
63323
63324 /*
63325 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
63326 ** bytes in this text up to but excluding the first character in
63327 ** a host parameter.  If the text contains no host parameters, return
63328 ** the total number of bytes in the text.
63329 */
63330 static int findNextHostParameter(const char *zSql, int *pnToken){
63331   int tokenType;
63332   int nTotal = 0;
63333   int n;
63334
63335   *pnToken = 0;
63336   while( zSql[0] ){
63337     n = sqlite3GetToken((u8*)zSql, &tokenType);
63338     assert( n>0 && tokenType!=TK_ILLEGAL );
63339     if( tokenType==TK_VARIABLE ){
63340       *pnToken = n;
63341       break;
63342     }
63343     nTotal += n;
63344     zSql += n;
63345   }
63346   return nTotal;
63347 }
63348
63349 /*
63350 ** This function returns a pointer to a nul-terminated string in memory
63351 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
63352 ** string contains a copy of zRawSql but with host parameters expanded to 
63353 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1, 
63354 ** then the returned string holds a copy of zRawSql with "-- " prepended
63355 ** to each line of text.
63356 **
63357 ** The calling function is responsible for making sure the memory returned
63358 ** is eventually freed.
63359 **
63360 ** ALGORITHM:  Scan the input string looking for host parameters in any of
63361 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
63362 ** string literals, quoted identifier names, and comments.  For text forms,
63363 ** the host parameter index is found by scanning the perpared
63364 ** statement for the corresponding OP_Variable opcode.  Once the host
63365 ** parameter index is known, locate the value in p->aVar[].  Then render
63366 ** the value as a literal in place of the host parameter name.
63367 */
63368 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
63369   Vdbe *p,                 /* The prepared statement being evaluated */
63370   const char *zRawSql      /* Raw text of the SQL statement */
63371 ){
63372   sqlite3 *db;             /* The database connection */
63373   int idx = 0;             /* Index of a host parameter */
63374   int nextIndex = 1;       /* Index of next ? host parameter */
63375   int n;                   /* Length of a token prefix */
63376   int nToken;              /* Length of the parameter token */
63377   int i;                   /* Loop counter */
63378   Mem *pVar;               /* Value of a host parameter */
63379   StrAccum out;            /* Accumulate the output here */
63380   char zBase[100];         /* Initial working space */
63381
63382   db = p->db;
63383   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
63384                       db->aLimit[SQLITE_LIMIT_LENGTH]);
63385   out.db = db;
63386   if( db->vdbeExecCnt>1 ){
63387     while( *zRawSql ){
63388       const char *zStart = zRawSql;
63389       while( *(zRawSql++)!='\n' && *zRawSql );
63390       sqlite3StrAccumAppend(&out, "-- ", 3);
63391       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
63392     }
63393   }else{
63394     while( zRawSql[0] ){
63395       n = findNextHostParameter(zRawSql, &nToken);
63396       assert( n>0 );
63397       sqlite3StrAccumAppend(&out, zRawSql, n);
63398       zRawSql += n;
63399       assert( zRawSql[0] || nToken==0 );
63400       if( nToken==0 ) break;
63401       if( zRawSql[0]=='?' ){
63402         if( nToken>1 ){
63403           assert( sqlite3Isdigit(zRawSql[1]) );
63404           sqlite3GetInt32(&zRawSql[1], &idx);
63405         }else{
63406           idx = nextIndex;
63407         }
63408       }else{
63409         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
63410         testcase( zRawSql[0]==':' );
63411         testcase( zRawSql[0]=='$' );
63412         testcase( zRawSql[0]=='@' );
63413         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
63414         assert( idx>0 );
63415       }
63416       zRawSql += nToken;
63417       nextIndex = idx + 1;
63418       assert( idx>0 && idx<=p->nVar );
63419       pVar = &p->aVar[idx-1];
63420       if( pVar->flags & MEM_Null ){
63421         sqlite3StrAccumAppend(&out, "NULL", 4);
63422       }else if( pVar->flags & MEM_Int ){
63423         sqlite3XPrintf(&out, "%lld", pVar->u.i);
63424       }else if( pVar->flags & MEM_Real ){
63425         sqlite3XPrintf(&out, "%!.15g", pVar->r);
63426       }else if( pVar->flags & MEM_Str ){
63427 #ifndef SQLITE_OMIT_UTF16
63428         u8 enc = ENC(db);
63429         if( enc!=SQLITE_UTF8 ){
63430           Mem utf8;
63431           memset(&utf8, 0, sizeof(utf8));
63432           utf8.db = db;
63433           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
63434           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
63435           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
63436           sqlite3VdbeMemRelease(&utf8);
63437         }else
63438 #endif
63439         {
63440           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
63441         }
63442       }else if( pVar->flags & MEM_Zero ){
63443         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
63444       }else{
63445         assert( pVar->flags & MEM_Blob );
63446         sqlite3StrAccumAppend(&out, "x'", 2);
63447         for(i=0; i<pVar->n; i++){
63448           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
63449         }
63450         sqlite3StrAccumAppend(&out, "'", 1);
63451       }
63452     }
63453   }
63454   return sqlite3StrAccumFinish(&out);
63455 }
63456
63457 #endif /* #ifndef SQLITE_OMIT_TRACE */
63458
63459 /*****************************************************************************
63460 ** The following code implements the data-structure explaining logic
63461 ** for the Vdbe.
63462 */
63463
63464 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
63465
63466 /*
63467 ** Allocate a new Explain object
63468 */
63469 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
63470   if( pVdbe ){
63471     Explain *p;
63472     sqlite3BeginBenignMalloc();
63473     p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
63474     if( p ){
63475       p->pVdbe = pVdbe;
63476       sqlite3_free(pVdbe->pExplain);
63477       pVdbe->pExplain = p;
63478       sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
63479                           SQLITE_MAX_LENGTH);
63480       p->str.useMalloc = 2;
63481     }else{
63482       sqlite3EndBenignMalloc();
63483     }
63484   }
63485 }
63486
63487 /*
63488 ** Return true if the Explain ends with a new-line.
63489 */
63490 static int endsWithNL(Explain *p){
63491   return p && p->str.zText && p->str.nChar
63492            && p->str.zText[p->str.nChar-1]=='\n';
63493 }
63494     
63495 /*
63496 ** Append text to the indentation
63497 */
63498 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
63499   Explain *p;
63500   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
63501     va_list ap;
63502     if( p->nIndent && endsWithNL(p) ){
63503       int n = p->nIndent;
63504       if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
63505       sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
63506     }   
63507     va_start(ap, zFormat);
63508     sqlite3VXPrintf(&p->str, 1, zFormat, ap);
63509     va_end(ap);
63510   }
63511 }
63512
63513 /*
63514 ** Append a '\n' if there is not already one.
63515 */
63516 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
63517   Explain *p;
63518   if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
63519     sqlite3StrAccumAppend(&p->str, "\n", 1);
63520   }
63521 }
63522
63523 /*
63524 ** Push a new indentation level.  Subsequent lines will be indented
63525 ** so that they begin at the current cursor position.
63526 */
63527 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
63528   Explain *p;
63529   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
63530     if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
63531       const char *z = p->str.zText;
63532       int i = p->str.nChar-1;
63533       int x;
63534       while( i>=0 && z[i]!='\n' ){ i--; }
63535       x = (p->str.nChar - 1) - i;
63536       if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
63537         x = p->aIndent[p->nIndent-1];
63538       }
63539       p->aIndent[p->nIndent] = x;
63540     }
63541     p->nIndent++;
63542   }
63543 }
63544
63545 /*
63546 ** Pop the indentation stack by one level.
63547 */
63548 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
63549   if( p && p->pExplain ) p->pExplain->nIndent--;
63550 }
63551
63552 /*
63553 ** Free the indentation structure
63554 */
63555 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
63556   if( pVdbe && pVdbe->pExplain ){
63557     sqlite3_free(pVdbe->zExplain);
63558     sqlite3ExplainNL(pVdbe);
63559     pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
63560     sqlite3_free(pVdbe->pExplain);
63561     pVdbe->pExplain = 0;
63562     sqlite3EndBenignMalloc();
63563   }
63564 }
63565
63566 /*
63567 ** Return the explanation of a virtual machine.
63568 */
63569 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
63570   return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
63571 }
63572 #endif /* defined(SQLITE_DEBUG) */
63573
63574 /************** End of vdbetrace.c *******************************************/
63575 /************** Begin file vdbe.c ********************************************/
63576 /*
63577 ** 2001 September 15
63578 **
63579 ** The author disclaims copyright to this source code.  In place of
63580 ** a legal notice, here is a blessing:
63581 **
63582 **    May you do good and not evil.
63583 **    May you find forgiveness for yourself and forgive others.
63584 **    May you share freely, never taking more than you give.
63585 **
63586 *************************************************************************
63587 ** The code in this file implements execution method of the 
63588 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
63589 ** handles housekeeping details such as creating and deleting
63590 ** VDBE instances.  This file is solely interested in executing
63591 ** the VDBE program.
63592 **
63593 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
63594 ** to a VDBE.
63595 **
63596 ** The SQL parser generates a program which is then executed by
63597 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
63598 ** similar in form to assembly language.  The program consists of
63599 ** a linear sequence of operations.  Each operation has an opcode 
63600 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
63601 ** is a null-terminated string.  Operand P5 is an unsigned character.
63602 ** Few opcodes use all 5 operands.
63603 **
63604 ** Computation results are stored on a set of registers numbered beginning
63605 ** with 1 and going up to Vdbe.nMem.  Each register can store
63606 ** either an integer, a null-terminated string, a floating point
63607 ** number, or the SQL "NULL" value.  An implicit conversion from one
63608 ** type to the other occurs as necessary.
63609 ** 
63610 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
63611 ** function which does the work of interpreting a VDBE program.
63612 ** But other routines are also provided to help in building up
63613 ** a program instruction by instruction.
63614 **
63615 ** Various scripts scan this source file in order to generate HTML
63616 ** documentation, headers files, or other derived files.  The formatting
63617 ** of the code in this file is, therefore, important.  See other comments
63618 ** in this file for details.  If in doubt, do not deviate from existing
63619 ** commenting and indentation practices when changing or adding code.
63620 */
63621
63622 /*
63623 ** Invoke this macro on memory cells just prior to changing the
63624 ** value of the cell.  This macro verifies that shallow copies are
63625 ** not misused.
63626 */
63627 #ifdef SQLITE_DEBUG
63628 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
63629 #else
63630 # define memAboutToChange(P,M)
63631 #endif
63632
63633 /*
63634 ** The following global variable is incremented every time a cursor
63635 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
63636 ** procedures use this information to make sure that indices are
63637 ** working correctly.  This variable has no function other than to
63638 ** help verify the correct operation of the library.
63639 */
63640 #ifdef SQLITE_TEST
63641 SQLITE_API int sqlite3_search_count = 0;
63642 #endif
63643
63644 /*
63645 ** When this global variable is positive, it gets decremented once before
63646 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
63647 ** field of the sqlite3 structure is set in order to simulate an interrupt.
63648 **
63649 ** This facility is used for testing purposes only.  It does not function
63650 ** in an ordinary build.
63651 */
63652 #ifdef SQLITE_TEST
63653 SQLITE_API int sqlite3_interrupt_count = 0;
63654 #endif
63655
63656 /*
63657 ** The next global variable is incremented each type the OP_Sort opcode
63658 ** is executed.  The test procedures use this information to make sure that
63659 ** sorting is occurring or not occurring at appropriate times.   This variable
63660 ** has no function other than to help verify the correct operation of the
63661 ** library.
63662 */
63663 #ifdef SQLITE_TEST
63664 SQLITE_API int sqlite3_sort_count = 0;
63665 #endif
63666
63667 /*
63668 ** The next global variable records the size of the largest MEM_Blob
63669 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
63670 ** use this information to make sure that the zero-blob functionality
63671 ** is working correctly.   This variable has no function other than to
63672 ** help verify the correct operation of the library.
63673 */
63674 #ifdef SQLITE_TEST
63675 SQLITE_API int sqlite3_max_blobsize = 0;
63676 static void updateMaxBlobsize(Mem *p){
63677   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
63678     sqlite3_max_blobsize = p->n;
63679   }
63680 }
63681 #endif
63682
63683 /*
63684 ** The next global variable is incremented each type the OP_Found opcode
63685 ** is executed. This is used to test whether or not the foreign key
63686 ** operation implemented using OP_FkIsZero is working. This variable
63687 ** has no function other than to help verify the correct operation of the
63688 ** library.
63689 */
63690 #ifdef SQLITE_TEST
63691 SQLITE_API int sqlite3_found_count = 0;
63692 #endif
63693
63694 /*
63695 ** Test a register to see if it exceeds the current maximum blob size.
63696 ** If it does, record the new maximum blob size.
63697 */
63698 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
63699 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
63700 #else
63701 # define UPDATE_MAX_BLOBSIZE(P)
63702 #endif
63703
63704 /*
63705 ** Convert the given register into a string if it isn't one
63706 ** already. Return non-zero if a malloc() fails.
63707 */
63708 #define Stringify(P, enc) \
63709    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
63710      { goto no_mem; }
63711
63712 /*
63713 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
63714 ** a pointer to a dynamically allocated string where some other entity
63715 ** is responsible for deallocating that string.  Because the register
63716 ** does not control the string, it might be deleted without the register
63717 ** knowing it.
63718 **
63719 ** This routine converts an ephemeral string into a dynamically allocated
63720 ** string that the register itself controls.  In other words, it
63721 ** converts an MEM_Ephem string into an MEM_Dyn string.
63722 */
63723 #define Deephemeralize(P) \
63724    if( ((P)->flags&MEM_Ephem)!=0 \
63725        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
63726
63727 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
63728 # define isSorter(x) ((x)->pSorter!=0)
63729
63730 /*
63731 ** Argument pMem points at a register that will be passed to a
63732 ** user-defined function or returned to the user as the result of a query.
63733 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
63734 ** routines.
63735 */
63736 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
63737   int flags = pMem->flags;
63738   if( flags & MEM_Null ){
63739     pMem->type = SQLITE_NULL;
63740   }
63741   else if( flags & MEM_Int ){
63742     pMem->type = SQLITE_INTEGER;
63743   }
63744   else if( flags & MEM_Real ){
63745     pMem->type = SQLITE_FLOAT;
63746   }
63747   else if( flags & MEM_Str ){
63748     pMem->type = SQLITE_TEXT;
63749   }else{
63750     pMem->type = SQLITE_BLOB;
63751   }
63752 }
63753
63754 /*
63755 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
63756 ** if we run out of memory.
63757 */
63758 static VdbeCursor *allocateCursor(
63759   Vdbe *p,              /* The virtual machine */
63760   int iCur,             /* Index of the new VdbeCursor */
63761   int nField,           /* Number of fields in the table or index */
63762   int iDb,              /* Database the cursor belongs to, or -1 */
63763   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
63764 ){
63765   /* Find the memory cell that will be used to store the blob of memory
63766   ** required for this VdbeCursor structure. It is convenient to use a 
63767   ** vdbe memory cell to manage the memory allocation required for a
63768   ** VdbeCursor structure for the following reasons:
63769   **
63770   **   * Sometimes cursor numbers are used for a couple of different
63771   **     purposes in a vdbe program. The different uses might require
63772   **     different sized allocations. Memory cells provide growable
63773   **     allocations.
63774   **
63775   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
63776   **     be freed lazily via the sqlite3_release_memory() API. This
63777   **     minimizes the number of malloc calls made by the system.
63778   **
63779   ** Memory cells for cursors are allocated at the top of the address
63780   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
63781   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
63782   */
63783   Mem *pMem = &p->aMem[p->nMem-iCur];
63784
63785   int nByte;
63786   VdbeCursor *pCx = 0;
63787   nByte = 
63788       ROUND8(sizeof(VdbeCursor)) + 
63789       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
63790       2*nField*sizeof(u32);
63791
63792   assert( iCur<p->nCursor );
63793   if( p->apCsr[iCur] ){
63794     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
63795     p->apCsr[iCur] = 0;
63796   }
63797   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
63798     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
63799     memset(pCx, 0, sizeof(VdbeCursor));
63800     pCx->iDb = iDb;
63801     pCx->nField = nField;
63802     if( nField ){
63803       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
63804     }
63805     if( isBtreeCursor ){
63806       pCx->pCursor = (BtCursor*)
63807           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
63808       sqlite3BtreeCursorZero(pCx->pCursor);
63809     }
63810   }
63811   return pCx;
63812 }
63813
63814 /*
63815 ** Try to convert a value into a numeric representation if we can
63816 ** do so without loss of information.  In other words, if the string
63817 ** looks like a number, convert it into a number.  If it does not
63818 ** look like a number, leave it alone.
63819 */
63820 static void applyNumericAffinity(Mem *pRec){
63821   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
63822     double rValue;
63823     i64 iValue;
63824     u8 enc = pRec->enc;
63825     if( (pRec->flags&MEM_Str)==0 ) return;
63826     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
63827     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
63828       pRec->u.i = iValue;
63829       pRec->flags |= MEM_Int;
63830     }else{
63831       pRec->r = rValue;
63832       pRec->flags |= MEM_Real;
63833     }
63834   }
63835 }
63836
63837 /*
63838 ** Processing is determine by the affinity parameter:
63839 **
63840 ** SQLITE_AFF_INTEGER:
63841 ** SQLITE_AFF_REAL:
63842 ** SQLITE_AFF_NUMERIC:
63843 **    Try to convert pRec to an integer representation or a 
63844 **    floating-point representation if an integer representation
63845 **    is not possible.  Note that the integer representation is
63846 **    always preferred, even if the affinity is REAL, because
63847 **    an integer representation is more space efficient on disk.
63848 **
63849 ** SQLITE_AFF_TEXT:
63850 **    Convert pRec to a text representation.
63851 **
63852 ** SQLITE_AFF_NONE:
63853 **    No-op.  pRec is unchanged.
63854 */
63855 static void applyAffinity(
63856   Mem *pRec,          /* The value to apply affinity to */
63857   char affinity,      /* The affinity to be applied */
63858   u8 enc              /* Use this text encoding */
63859 ){
63860   if( affinity==SQLITE_AFF_TEXT ){
63861     /* Only attempt the conversion to TEXT if there is an integer or real
63862     ** representation (blob and NULL do not get converted) but no string
63863     ** representation.
63864     */
63865     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
63866       sqlite3VdbeMemStringify(pRec, enc);
63867     }
63868     pRec->flags &= ~(MEM_Real|MEM_Int);
63869   }else if( affinity!=SQLITE_AFF_NONE ){
63870     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
63871              || affinity==SQLITE_AFF_NUMERIC );
63872     applyNumericAffinity(pRec);
63873     if( pRec->flags & MEM_Real ){
63874       sqlite3VdbeIntegerAffinity(pRec);
63875     }
63876   }
63877 }
63878
63879 /*
63880 ** Try to convert the type of a function argument or a result column
63881 ** into a numeric representation.  Use either INTEGER or REAL whichever
63882 ** is appropriate.  But only do the conversion if it is possible without
63883 ** loss of information and return the revised type of the argument.
63884 */
63885 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
63886   Mem *pMem = (Mem*)pVal;
63887   if( pMem->type==SQLITE_TEXT ){
63888     applyNumericAffinity(pMem);
63889     sqlite3VdbeMemStoreType(pMem);
63890   }
63891   return pMem->type;
63892 }
63893
63894 /*
63895 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
63896 ** not the internal Mem* type.
63897 */
63898 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
63899   sqlite3_value *pVal, 
63900   u8 affinity, 
63901   u8 enc
63902 ){
63903   applyAffinity((Mem *)pVal, affinity, enc);
63904 }
63905
63906 #ifdef SQLITE_DEBUG
63907 /*
63908 ** Write a nice string representation of the contents of cell pMem
63909 ** into buffer zBuf, length nBuf.
63910 */
63911 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
63912   char *zCsr = zBuf;
63913   int f = pMem->flags;
63914
63915   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
63916
63917   if( f&MEM_Blob ){
63918     int i;
63919     char c;
63920     if( f & MEM_Dyn ){
63921       c = 'z';
63922       assert( (f & (MEM_Static|MEM_Ephem))==0 );
63923     }else if( f & MEM_Static ){
63924       c = 't';
63925       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
63926     }else if( f & MEM_Ephem ){
63927       c = 'e';
63928       assert( (f & (MEM_Static|MEM_Dyn))==0 );
63929     }else{
63930       c = 's';
63931     }
63932
63933     sqlite3_snprintf(100, zCsr, "%c", c);
63934     zCsr += sqlite3Strlen30(zCsr);
63935     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
63936     zCsr += sqlite3Strlen30(zCsr);
63937     for(i=0; i<16 && i<pMem->n; i++){
63938       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
63939       zCsr += sqlite3Strlen30(zCsr);
63940     }
63941     for(i=0; i<16 && i<pMem->n; i++){
63942       char z = pMem->z[i];
63943       if( z<32 || z>126 ) *zCsr++ = '.';
63944       else *zCsr++ = z;
63945     }
63946
63947     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
63948     zCsr += sqlite3Strlen30(zCsr);
63949     if( f & MEM_Zero ){
63950       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
63951       zCsr += sqlite3Strlen30(zCsr);
63952     }
63953     *zCsr = '\0';
63954   }else if( f & MEM_Str ){
63955     int j, k;
63956     zBuf[0] = ' ';
63957     if( f & MEM_Dyn ){
63958       zBuf[1] = 'z';
63959       assert( (f & (MEM_Static|MEM_Ephem))==0 );
63960     }else if( f & MEM_Static ){
63961       zBuf[1] = 't';
63962       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
63963     }else if( f & MEM_Ephem ){
63964       zBuf[1] = 'e';
63965       assert( (f & (MEM_Static|MEM_Dyn))==0 );
63966     }else{
63967       zBuf[1] = 's';
63968     }
63969     k = 2;
63970     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
63971     k += sqlite3Strlen30(&zBuf[k]);
63972     zBuf[k++] = '[';
63973     for(j=0; j<15 && j<pMem->n; j++){
63974       u8 c = pMem->z[j];
63975       if( c>=0x20 && c<0x7f ){
63976         zBuf[k++] = c;
63977       }else{
63978         zBuf[k++] = '.';
63979       }
63980     }
63981     zBuf[k++] = ']';
63982     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
63983     k += sqlite3Strlen30(&zBuf[k]);
63984     zBuf[k++] = 0;
63985   }
63986 }
63987 #endif
63988
63989 #ifdef SQLITE_DEBUG
63990 /*
63991 ** Print the value of a register for tracing purposes:
63992 */
63993 static void memTracePrint(FILE *out, Mem *p){
63994   if( p->flags & MEM_Invalid ){
63995     fprintf(out, " undefined");
63996   }else if( p->flags & MEM_Null ){
63997     fprintf(out, " NULL");
63998   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
63999     fprintf(out, " si:%lld", p->u.i);
64000   }else if( p->flags & MEM_Int ){
64001     fprintf(out, " i:%lld", p->u.i);
64002 #ifndef SQLITE_OMIT_FLOATING_POINT
64003   }else if( p->flags & MEM_Real ){
64004     fprintf(out, " r:%g", p->r);
64005 #endif
64006   }else if( p->flags & MEM_RowSet ){
64007     fprintf(out, " (rowset)");
64008   }else{
64009     char zBuf[200];
64010     sqlite3VdbeMemPrettyPrint(p, zBuf);
64011     fprintf(out, " ");
64012     fprintf(out, "%s", zBuf);
64013   }
64014 }
64015 static void registerTrace(FILE *out, int iReg, Mem *p){
64016   fprintf(out, "REG[%d] = ", iReg);
64017   memTracePrint(out, p);
64018   fprintf(out, "\n");
64019 }
64020 #endif
64021
64022 #ifdef SQLITE_DEBUG
64023 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
64024 #else
64025 #  define REGISTER_TRACE(R,M)
64026 #endif
64027
64028
64029 #ifdef VDBE_PROFILE
64030
64031 /* 
64032 ** hwtime.h contains inline assembler code for implementing 
64033 ** high-performance timing routines.
64034 */
64035 /************** Include hwtime.h in the middle of vdbe.c *********************/
64036 /************** Begin file hwtime.h ******************************************/
64037 /*
64038 ** 2008 May 27
64039 **
64040 ** The author disclaims copyright to this source code.  In place of
64041 ** a legal notice, here is a blessing:
64042 **
64043 **    May you do good and not evil.
64044 **    May you find forgiveness for yourself and forgive others.
64045 **    May you share freely, never taking more than you give.
64046 **
64047 ******************************************************************************
64048 **
64049 ** This file contains inline asm code for retrieving "high-performance"
64050 ** counters for x86 class CPUs.
64051 */
64052 #ifndef _HWTIME_H_
64053 #define _HWTIME_H_
64054
64055 /*
64056 ** The following routine only works on pentium-class (or newer) processors.
64057 ** It uses the RDTSC opcode to read the cycle count value out of the
64058 ** processor and returns that value.  This can be used for high-res
64059 ** profiling.
64060 */
64061 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
64062       (defined(i386) || defined(__i386__) || defined(_M_IX86))
64063
64064   #if defined(__GNUC__)
64065
64066   __inline__ sqlite_uint64 sqlite3Hwtime(void){
64067      unsigned int lo, hi;
64068      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
64069      return (sqlite_uint64)hi << 32 | lo;
64070   }
64071
64072   #elif defined(_MSC_VER)
64073
64074   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
64075      __asm {
64076         rdtsc
64077         ret       ; return value at EDX:EAX
64078      }
64079   }
64080
64081   #endif
64082
64083 #elif (defined(__GNUC__) && defined(__x86_64__))
64084
64085   __inline__ sqlite_uint64 sqlite3Hwtime(void){
64086       unsigned long val;
64087       __asm__ __volatile__ ("rdtsc" : "=A" (val));
64088       return val;
64089   }
64090  
64091 #elif (defined(__GNUC__) && defined(__ppc__))
64092
64093   __inline__ sqlite_uint64 sqlite3Hwtime(void){
64094       unsigned long long retval;
64095       unsigned long junk;
64096       __asm__ __volatile__ ("\n\
64097           1:      mftbu   %1\n\
64098                   mftb    %L0\n\
64099                   mftbu   %0\n\
64100                   cmpw    %0,%1\n\
64101                   bne     1b"
64102                   : "=r" (retval), "=r" (junk));
64103       return retval;
64104   }
64105
64106 #else
64107
64108   #error Need implementation of sqlite3Hwtime() for your platform.
64109
64110   /*
64111   ** To compile without implementing sqlite3Hwtime() for your platform,
64112   ** you can remove the above #error and use the following
64113   ** stub function.  You will lose timing support for many
64114   ** of the debugging and testing utilities, but it should at
64115   ** least compile and run.
64116   */
64117 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
64118
64119 #endif
64120
64121 #endif /* !defined(_HWTIME_H_) */
64122
64123 /************** End of hwtime.h **********************************************/
64124 /************** Continuing where we left off in vdbe.c ***********************/
64125
64126 #endif
64127
64128 /*
64129 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
64130 ** sqlite3_interrupt() routine has been called.  If it has been, then
64131 ** processing of the VDBE program is interrupted.
64132 **
64133 ** This macro added to every instruction that does a jump in order to
64134 ** implement a loop.  This test used to be on every single instruction,
64135 ** but that meant we more testing than we needed.  By only testing the
64136 ** flag on jump instructions, we get a (small) speed improvement.
64137 */
64138 #define CHECK_FOR_INTERRUPT \
64139    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
64140
64141
64142 #ifndef NDEBUG
64143 /*
64144 ** This function is only called from within an assert() expression. It
64145 ** checks that the sqlite3.nTransaction variable is correctly set to
64146 ** the number of non-transaction savepoints currently in the 
64147 ** linked list starting at sqlite3.pSavepoint.
64148 ** 
64149 ** Usage:
64150 **
64151 **     assert( checkSavepointCount(db) );
64152 */
64153 static int checkSavepointCount(sqlite3 *db){
64154   int n = 0;
64155   Savepoint *p;
64156   for(p=db->pSavepoint; p; p=p->pNext) n++;
64157   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
64158   return 1;
64159 }
64160 #endif
64161
64162 /*
64163 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
64164 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
64165 ** in memory obtained from sqlite3DbMalloc).
64166 */
64167 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
64168   sqlite3 *db = p->db;
64169   sqlite3DbFree(db, p->zErrMsg);
64170   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
64171   sqlite3_free(pVtab->zErrMsg);
64172   pVtab->zErrMsg = 0;
64173 }
64174
64175
64176 /*
64177 ** Execute as much of a VDBE program as we can then return.
64178 **
64179 ** sqlite3VdbeMakeReady() must be called before this routine in order to
64180 ** close the program with a final OP_Halt and to set up the callbacks
64181 ** and the error message pointer.
64182 **
64183 ** Whenever a row or result data is available, this routine will either
64184 ** invoke the result callback (if there is one) or return with
64185 ** SQLITE_ROW.
64186 **
64187 ** If an attempt is made to open a locked database, then this routine
64188 ** will either invoke the busy callback (if there is one) or it will
64189 ** return SQLITE_BUSY.
64190 **
64191 ** If an error occurs, an error message is written to memory obtained
64192 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
64193 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
64194 **
64195 ** If the callback ever returns non-zero, then the program exits
64196 ** immediately.  There will be no error message but the p->rc field is
64197 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
64198 **
64199 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
64200 ** routine to return SQLITE_ERROR.
64201 **
64202 ** Other fatal errors return SQLITE_ERROR.
64203 **
64204 ** After this routine has finished, sqlite3VdbeFinalize() should be
64205 ** used to clean up the mess that was left behind.
64206 */
64207 SQLITE_PRIVATE int sqlite3VdbeExec(
64208   Vdbe *p                    /* The VDBE */
64209 ){
64210   int pc=0;                  /* The program counter */
64211   Op *aOp = p->aOp;          /* Copy of p->aOp */
64212   Op *pOp;                   /* Current operation */
64213   int rc = SQLITE_OK;        /* Value to return */
64214   sqlite3 *db = p->db;       /* The database */
64215   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
64216   u8 encoding = ENC(db);     /* The database encoding */
64217 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64218   int checkProgress;         /* True if progress callbacks are enabled */
64219   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
64220 #endif
64221   Mem *aMem = p->aMem;       /* Copy of p->aMem */
64222   Mem *pIn1 = 0;             /* 1st input operand */
64223   Mem *pIn2 = 0;             /* 2nd input operand */
64224   Mem *pIn3 = 0;             /* 3rd input operand */
64225   Mem *pOut = 0;             /* Output operand */
64226   int iCompare = 0;          /* Result of last OP_Compare operation */
64227   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
64228   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
64229 #ifdef VDBE_PROFILE
64230   u64 start;                 /* CPU clock count at start of opcode */
64231   int origPc;                /* Program counter at start of opcode */
64232 #endif
64233   /********************************************************************
64234   ** Automatically generated code
64235   **
64236   ** The following union is automatically generated by the
64237   ** vdbe-compress.tcl script.  The purpose of this union is to
64238   ** reduce the amount of stack space required by this function.
64239   ** See comments in the vdbe-compress.tcl script for details.
64240   */
64241   union vdbeExecUnion {
64242     struct OP_Yield_stack_vars {
64243       int pcDest;
64244     } aa;
64245     struct OP_Null_stack_vars {
64246       int cnt;
64247       u16 nullFlag;
64248     } ab;
64249     struct OP_Variable_stack_vars {
64250       Mem *pVar;       /* Value being transferred */
64251     } ac;
64252     struct OP_Move_stack_vars {
64253       char *zMalloc;   /* Holding variable for allocated memory */
64254       int n;           /* Number of registers left to copy */
64255       int p1;          /* Register to copy from */
64256       int p2;          /* Register to copy to */
64257     } ad;
64258     struct OP_Copy_stack_vars {
64259       int n;
64260     } ae;
64261     struct OP_ResultRow_stack_vars {
64262       Mem *pMem;
64263       int i;
64264     } af;
64265     struct OP_Concat_stack_vars {
64266       i64 nByte;
64267     } ag;
64268     struct OP_Remainder_stack_vars {
64269       char bIntint;   /* Started out as two integer operands */
64270       int flags;      /* Combined MEM_* flags from both inputs */
64271       i64 iA;         /* Integer value of left operand */
64272       i64 iB;         /* Integer value of right operand */
64273       double rA;      /* Real value of left operand */
64274       double rB;      /* Real value of right operand */
64275     } ah;
64276     struct OP_Function_stack_vars {
64277       int i;
64278       Mem *pArg;
64279       sqlite3_context ctx;
64280       sqlite3_value **apVal;
64281       int n;
64282     } ai;
64283     struct OP_ShiftRight_stack_vars {
64284       i64 iA;
64285       u64 uA;
64286       i64 iB;
64287       u8 op;
64288     } aj;
64289     struct OP_Ge_stack_vars {
64290       int res;            /* Result of the comparison of pIn1 against pIn3 */
64291       char affinity;      /* Affinity to use for comparison */
64292       u16 flags1;         /* Copy of initial value of pIn1->flags */
64293       u16 flags3;         /* Copy of initial value of pIn3->flags */
64294     } ak;
64295     struct OP_Compare_stack_vars {
64296       int n;
64297       int i;
64298       int p1;
64299       int p2;
64300       const KeyInfo *pKeyInfo;
64301       int idx;
64302       CollSeq *pColl;    /* Collating sequence to use on this term */
64303       int bRev;          /* True for DESCENDING sort order */
64304     } al;
64305     struct OP_Or_stack_vars {
64306       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64307       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64308     } am;
64309     struct OP_IfNot_stack_vars {
64310       int c;
64311     } an;
64312     struct OP_Column_stack_vars {
64313       u32 payloadSize;   /* Number of bytes in the record */
64314       i64 payloadSize64; /* Number of bytes in the record */
64315       int p1;            /* P1 value of the opcode */
64316       int p2;            /* column number to retrieve */
64317       VdbeCursor *pC;    /* The VDBE cursor */
64318       char *zRec;        /* Pointer to complete record-data */
64319       BtCursor *pCrsr;   /* The BTree cursor */
64320       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
64321       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
64322       int nField;        /* number of fields in the record */
64323       int len;           /* The length of the serialized data for the column */
64324       int i;             /* Loop counter */
64325       char *zData;       /* Part of the record being decoded */
64326       Mem *pDest;        /* Where to write the extracted value */
64327       Mem sMem;          /* For storing the record being decoded */
64328       u8 *zIdx;          /* Index into header */
64329       u8 *zEndHdr;       /* Pointer to first byte after the header */
64330       u32 offset;        /* Offset into the data */
64331       u32 szField;       /* Number of bytes in the content of a field */
64332       int szHdr;         /* Size of the header size field at start of record */
64333       int avail;         /* Number of bytes of available data */
64334       u32 t;             /* A type code from the record header */
64335       Mem *pReg;         /* PseudoTable input register */
64336     } ao;
64337     struct OP_Affinity_stack_vars {
64338       const char *zAffinity;   /* The affinity to be applied */
64339       char cAff;               /* A single character of affinity */
64340     } ap;
64341     struct OP_MakeRecord_stack_vars {
64342       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
64343       Mem *pRec;             /* The new record */
64344       u64 nData;             /* Number of bytes of data space */
64345       int nHdr;              /* Number of bytes of header space */
64346       i64 nByte;             /* Data space required for this record */
64347       int nZero;             /* Number of zero bytes at the end of the record */
64348       int nVarint;           /* Number of bytes in a varint */
64349       u32 serial_type;       /* Type field */
64350       Mem *pData0;           /* First field to be combined into the record */
64351       Mem *pLast;            /* Last field of the record */
64352       int nField;            /* Number of fields in the record */
64353       char *zAffinity;       /* The affinity string for the record */
64354       int file_format;       /* File format to use for encoding */
64355       int i;                 /* Space used in zNewRecord[] */
64356       int len;               /* Length of a field */
64357     } aq;
64358     struct OP_Count_stack_vars {
64359       i64 nEntry;
64360       BtCursor *pCrsr;
64361     } ar;
64362     struct OP_Savepoint_stack_vars {
64363       int p1;                         /* Value of P1 operand */
64364       char *zName;                    /* Name of savepoint */
64365       int nName;
64366       Savepoint *pNew;
64367       Savepoint *pSavepoint;
64368       Savepoint *pTmp;
64369       int iSavepoint;
64370       int ii;
64371     } as;
64372     struct OP_AutoCommit_stack_vars {
64373       int desiredAutoCommit;
64374       int iRollback;
64375       int turnOnAC;
64376     } at;
64377     struct OP_Transaction_stack_vars {
64378       Btree *pBt;
64379     } au;
64380     struct OP_ReadCookie_stack_vars {
64381       int iMeta;
64382       int iDb;
64383       int iCookie;
64384     } av;
64385     struct OP_SetCookie_stack_vars {
64386       Db *pDb;
64387     } aw;
64388     struct OP_VerifyCookie_stack_vars {
64389       int iMeta;
64390       int iGen;
64391       Btree *pBt;
64392     } ax;
64393     struct OP_OpenWrite_stack_vars {
64394       int nField;
64395       KeyInfo *pKeyInfo;
64396       int p2;
64397       int iDb;
64398       int wrFlag;
64399       Btree *pX;
64400       VdbeCursor *pCur;
64401       Db *pDb;
64402     } ay;
64403     struct OP_OpenEphemeral_stack_vars {
64404       VdbeCursor *pCx;
64405     } az;
64406     struct OP_SorterOpen_stack_vars {
64407       VdbeCursor *pCx;
64408     } ba;
64409     struct OP_OpenPseudo_stack_vars {
64410       VdbeCursor *pCx;
64411     } bb;
64412     struct OP_SeekGt_stack_vars {
64413       int res;
64414       int oc;
64415       VdbeCursor *pC;
64416       UnpackedRecord r;
64417       int nField;
64418       i64 iKey;      /* The rowid we are to seek to */
64419     } bc;
64420     struct OP_Seek_stack_vars {
64421       VdbeCursor *pC;
64422     } bd;
64423     struct OP_Found_stack_vars {
64424       int alreadyExists;
64425       VdbeCursor *pC;
64426       int res;
64427       char *pFree;
64428       UnpackedRecord *pIdxKey;
64429       UnpackedRecord r;
64430       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
64431     } be;
64432     struct OP_IsUnique_stack_vars {
64433       u16 ii;
64434       VdbeCursor *pCx;
64435       BtCursor *pCrsr;
64436       u16 nField;
64437       Mem *aMx;
64438       UnpackedRecord r;                  /* B-Tree index search key */
64439       i64 R;                             /* Rowid stored in register P3 */
64440     } bf;
64441     struct OP_NotExists_stack_vars {
64442       VdbeCursor *pC;
64443       BtCursor *pCrsr;
64444       int res;
64445       u64 iKey;
64446     } bg;
64447     struct OP_NewRowid_stack_vars {
64448       i64 v;                 /* The new rowid */
64449       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
64450       int res;               /* Result of an sqlite3BtreeLast() */
64451       int cnt;               /* Counter to limit the number of searches */
64452       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
64453       VdbeFrame *pFrame;     /* Root frame of VDBE */
64454     } bh;
64455     struct OP_InsertInt_stack_vars {
64456       Mem *pData;       /* MEM cell holding data for the record to be inserted */
64457       Mem *pKey;        /* MEM cell holding key  for the record */
64458       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
64459       VdbeCursor *pC;   /* Cursor to table into which insert is written */
64460       int nZero;        /* Number of zero-bytes to append */
64461       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
64462       const char *zDb;  /* database name - used by the update hook */
64463       const char *zTbl; /* Table name - used by the opdate hook */
64464       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
64465     } bi;
64466     struct OP_Delete_stack_vars {
64467       i64 iKey;
64468       VdbeCursor *pC;
64469     } bj;
64470     struct OP_SorterCompare_stack_vars {
64471       VdbeCursor *pC;
64472       int res;
64473     } bk;
64474     struct OP_SorterData_stack_vars {
64475       VdbeCursor *pC;
64476     } bl;
64477     struct OP_RowData_stack_vars {
64478       VdbeCursor *pC;
64479       BtCursor *pCrsr;
64480       u32 n;
64481       i64 n64;
64482     } bm;
64483     struct OP_Rowid_stack_vars {
64484       VdbeCursor *pC;
64485       i64 v;
64486       sqlite3_vtab *pVtab;
64487       const sqlite3_module *pModule;
64488     } bn;
64489     struct OP_NullRow_stack_vars {
64490       VdbeCursor *pC;
64491     } bo;
64492     struct OP_Last_stack_vars {
64493       VdbeCursor *pC;
64494       BtCursor *pCrsr;
64495       int res;
64496     } bp;
64497     struct OP_Rewind_stack_vars {
64498       VdbeCursor *pC;
64499       BtCursor *pCrsr;
64500       int res;
64501     } bq;
64502     struct OP_Next_stack_vars {
64503       VdbeCursor *pC;
64504       int res;
64505     } br;
64506     struct OP_IdxInsert_stack_vars {
64507       VdbeCursor *pC;
64508       BtCursor *pCrsr;
64509       int nKey;
64510       const char *zKey;
64511     } bs;
64512     struct OP_IdxDelete_stack_vars {
64513       VdbeCursor *pC;
64514       BtCursor *pCrsr;
64515       int res;
64516       UnpackedRecord r;
64517     } bt;
64518     struct OP_IdxRowid_stack_vars {
64519       BtCursor *pCrsr;
64520       VdbeCursor *pC;
64521       i64 rowid;
64522     } bu;
64523     struct OP_IdxGE_stack_vars {
64524       VdbeCursor *pC;
64525       int res;
64526       UnpackedRecord r;
64527     } bv;
64528     struct OP_Destroy_stack_vars {
64529       int iMoved;
64530       int iCnt;
64531       Vdbe *pVdbe;
64532       int iDb;
64533     } bw;
64534     struct OP_Clear_stack_vars {
64535       int nChange;
64536     } bx;
64537     struct OP_CreateTable_stack_vars {
64538       int pgno;
64539       int flags;
64540       Db *pDb;
64541     } by;
64542     struct OP_ParseSchema_stack_vars {
64543       int iDb;
64544       const char *zMaster;
64545       char *zSql;
64546       InitData initData;
64547     } bz;
64548     struct OP_IntegrityCk_stack_vars {
64549       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
64550       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
64551       int j;          /* Loop counter */
64552       int nErr;       /* Number of errors reported */
64553       char *z;        /* Text of the error report */
64554       Mem *pnErr;     /* Register keeping track of errors remaining */
64555     } ca;
64556     struct OP_RowSetRead_stack_vars {
64557       i64 val;
64558     } cb;
64559     struct OP_RowSetTest_stack_vars {
64560       int iSet;
64561       int exists;
64562     } cc;
64563     struct OP_Program_stack_vars {
64564       int nMem;               /* Number of memory registers for sub-program */
64565       int nByte;              /* Bytes of runtime space required for sub-program */
64566       Mem *pRt;               /* Register to allocate runtime space */
64567       Mem *pMem;              /* Used to iterate through memory cells */
64568       Mem *pEnd;              /* Last memory cell in new array */
64569       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
64570       SubProgram *pProgram;   /* Sub-program to execute */
64571       void *t;                /* Token identifying trigger */
64572     } cd;
64573     struct OP_Param_stack_vars {
64574       VdbeFrame *pFrame;
64575       Mem *pIn;
64576     } ce;
64577     struct OP_MemMax_stack_vars {
64578       Mem *pIn1;
64579       VdbeFrame *pFrame;
64580     } cf;
64581     struct OP_AggStep_stack_vars {
64582       int n;
64583       int i;
64584       Mem *pMem;
64585       Mem *pRec;
64586       sqlite3_context ctx;
64587       sqlite3_value **apVal;
64588     } cg;
64589     struct OP_AggFinal_stack_vars {
64590       Mem *pMem;
64591     } ch;
64592     struct OP_Checkpoint_stack_vars {
64593       int i;                          /* Loop counter */
64594       int aRes[3];                    /* Results */
64595       Mem *pMem;                      /* Write results here */
64596     } ci;
64597     struct OP_JournalMode_stack_vars {
64598       Btree *pBt;                     /* Btree to change journal mode of */
64599       Pager *pPager;                  /* Pager associated with pBt */
64600       int eNew;                       /* New journal mode */
64601       int eOld;                       /* The old journal mode */
64602 #ifndef SQLITE_OMIT_WAL
64603       const char *zFilename;          /* Name of database file for pPager */
64604 #endif
64605     } cj;
64606     struct OP_IncrVacuum_stack_vars {
64607       Btree *pBt;
64608     } ck;
64609     struct OP_VBegin_stack_vars {
64610       VTable *pVTab;
64611     } cl;
64612     struct OP_VOpen_stack_vars {
64613       VdbeCursor *pCur;
64614       sqlite3_vtab_cursor *pVtabCursor;
64615       sqlite3_vtab *pVtab;
64616       sqlite3_module *pModule;
64617     } cm;
64618     struct OP_VFilter_stack_vars {
64619       int nArg;
64620       int iQuery;
64621       const sqlite3_module *pModule;
64622       Mem *pQuery;
64623       Mem *pArgc;
64624       sqlite3_vtab_cursor *pVtabCursor;
64625       sqlite3_vtab *pVtab;
64626       VdbeCursor *pCur;
64627       int res;
64628       int i;
64629       Mem **apArg;
64630     } cn;
64631     struct OP_VColumn_stack_vars {
64632       sqlite3_vtab *pVtab;
64633       const sqlite3_module *pModule;
64634       Mem *pDest;
64635       sqlite3_context sContext;
64636     } co;
64637     struct OP_VNext_stack_vars {
64638       sqlite3_vtab *pVtab;
64639       const sqlite3_module *pModule;
64640       int res;
64641       VdbeCursor *pCur;
64642     } cp;
64643     struct OP_VRename_stack_vars {
64644       sqlite3_vtab *pVtab;
64645       Mem *pName;
64646     } cq;
64647     struct OP_VUpdate_stack_vars {
64648       sqlite3_vtab *pVtab;
64649       sqlite3_module *pModule;
64650       int nArg;
64651       int i;
64652       sqlite_int64 rowid;
64653       Mem **apArg;
64654       Mem *pX;
64655     } cr;
64656     struct OP_Trace_stack_vars {
64657       char *zTrace;
64658       char *z;
64659     } cs;
64660   } u;
64661   /* End automatically generated code
64662   ********************************************************************/
64663
64664   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
64665   sqlite3VdbeEnter(p);
64666   if( p->rc==SQLITE_NOMEM ){
64667     /* This happens if a malloc() inside a call to sqlite3_column_text() or
64668     ** sqlite3_column_text16() failed.  */
64669     goto no_mem;
64670   }
64671   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
64672   p->rc = SQLITE_OK;
64673   assert( p->explain==0 );
64674   p->pResultSet = 0;
64675   db->busyHandler.nBusy = 0;
64676   CHECK_FOR_INTERRUPT;
64677   sqlite3VdbeIOTraceSql(p);
64678 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64679   checkProgress = db->xProgress!=0;
64680 #endif
64681 #ifdef SQLITE_DEBUG
64682   sqlite3BeginBenignMalloc();
64683   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
64684     int i;
64685     printf("VDBE Program Listing:\n");
64686     sqlite3VdbePrintSql(p);
64687     for(i=0; i<p->nOp; i++){
64688       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
64689     }
64690   }
64691   sqlite3EndBenignMalloc();
64692 #endif
64693   for(pc=p->pc; rc==SQLITE_OK; pc++){
64694     assert( pc>=0 && pc<p->nOp );
64695     if( db->mallocFailed ) goto no_mem;
64696 #ifdef VDBE_PROFILE
64697     origPc = pc;
64698     start = sqlite3Hwtime();
64699 #endif
64700     pOp = &aOp[pc];
64701
64702     /* Only allow tracing if SQLITE_DEBUG is defined.
64703     */
64704 #ifdef SQLITE_DEBUG
64705     if( p->trace ){
64706       if( pc==0 ){
64707         printf("VDBE Execution Trace:\n");
64708         sqlite3VdbePrintSql(p);
64709       }
64710       sqlite3VdbePrintOp(p->trace, pc, pOp);
64711     }
64712 #endif
64713       
64714
64715     /* Check to see if we need to simulate an interrupt.  This only happens
64716     ** if we have a special test build.
64717     */
64718 #ifdef SQLITE_TEST
64719     if( sqlite3_interrupt_count>0 ){
64720       sqlite3_interrupt_count--;
64721       if( sqlite3_interrupt_count==0 ){
64722         sqlite3_interrupt(db);
64723       }
64724     }
64725 #endif
64726
64727 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64728     /* Call the progress callback if it is configured and the required number
64729     ** of VDBE ops have been executed (either since this invocation of
64730     ** sqlite3VdbeExec() or since last time the progress callback was called).
64731     ** If the progress callback returns non-zero, exit the virtual machine with
64732     ** a return code SQLITE_ABORT.
64733     */
64734     if( checkProgress ){
64735       if( db->nProgressOps==nProgressOps ){
64736         int prc;
64737         prc = db->xProgress(db->pProgressArg);
64738         if( prc!=0 ){
64739           rc = SQLITE_INTERRUPT;
64740           goto vdbe_error_halt;
64741         }
64742         nProgressOps = 0;
64743       }
64744       nProgressOps++;
64745     }
64746 #endif
64747
64748     /* On any opcode with the "out2-prerelease" tag, free any
64749     ** external allocations out of mem[p2] and set mem[p2] to be
64750     ** an undefined integer.  Opcodes will either fill in the integer
64751     ** value or convert mem[p2] to a different type.
64752     */
64753     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
64754     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
64755       assert( pOp->p2>0 );
64756       assert( pOp->p2<=p->nMem );
64757       pOut = &aMem[pOp->p2];
64758       memAboutToChange(p, pOut);
64759       VdbeMemRelease(pOut);
64760       pOut->flags = MEM_Int;
64761     }
64762
64763     /* Sanity checking on other operands */
64764 #ifdef SQLITE_DEBUG
64765     if( (pOp->opflags & OPFLG_IN1)!=0 ){
64766       assert( pOp->p1>0 );
64767       assert( pOp->p1<=p->nMem );
64768       assert( memIsValid(&aMem[pOp->p1]) );
64769       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
64770     }
64771     if( (pOp->opflags & OPFLG_IN2)!=0 ){
64772       assert( pOp->p2>0 );
64773       assert( pOp->p2<=p->nMem );
64774       assert( memIsValid(&aMem[pOp->p2]) );
64775       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
64776     }
64777     if( (pOp->opflags & OPFLG_IN3)!=0 ){
64778       assert( pOp->p3>0 );
64779       assert( pOp->p3<=p->nMem );
64780       assert( memIsValid(&aMem[pOp->p3]) );
64781       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
64782     }
64783     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
64784       assert( pOp->p2>0 );
64785       assert( pOp->p2<=p->nMem );
64786       memAboutToChange(p, &aMem[pOp->p2]);
64787     }
64788     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
64789       assert( pOp->p3>0 );
64790       assert( pOp->p3<=p->nMem );
64791       memAboutToChange(p, &aMem[pOp->p3]);
64792     }
64793 #endif
64794   
64795     switch( pOp->opcode ){
64796
64797 /*****************************************************************************
64798 ** What follows is a massive switch statement where each case implements a
64799 ** separate instruction in the virtual machine.  If we follow the usual
64800 ** indentation conventions, each case should be indented by 6 spaces.  But
64801 ** that is a lot of wasted space on the left margin.  So the code within
64802 ** the switch statement will break with convention and be flush-left. Another
64803 ** big comment (similar to this one) will mark the point in the code where
64804 ** we transition back to normal indentation.
64805 **
64806 ** The formatting of each case is important.  The makefile for SQLite
64807 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
64808 ** file looking for lines that begin with "case OP_".  The opcodes.h files
64809 ** will be filled with #defines that give unique integer values to each
64810 ** opcode and the opcodes.c file is filled with an array of strings where
64811 ** each string is the symbolic name for the corresponding opcode.  If the
64812 ** case statement is followed by a comment of the form "/# same as ... #/"
64813 ** that comment is used to determine the particular value of the opcode.
64814 **
64815 ** Other keywords in the comment that follows each case are used to
64816 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
64817 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
64818 ** the mkopcodeh.awk script for additional information.
64819 **
64820 ** Documentation about VDBE opcodes is generated by scanning this file
64821 ** for lines of that contain "Opcode:".  That line and all subsequent
64822 ** comment lines are used in the generation of the opcode.html documentation
64823 ** file.
64824 **
64825 ** SUMMARY:
64826 **
64827 **     Formatting is important to scripts that scan this file.
64828 **     Do not deviate from the formatting style currently in use.
64829 **
64830 *****************************************************************************/
64831
64832 /* Opcode:  Goto * P2 * * *
64833 **
64834 ** An unconditional jump to address P2.
64835 ** The next instruction executed will be 
64836 ** the one at index P2 from the beginning of
64837 ** the program.
64838 */
64839 case OP_Goto: {             /* jump */
64840   CHECK_FOR_INTERRUPT;
64841   pc = pOp->p2 - 1;
64842   break;
64843 }
64844
64845 /* Opcode:  Gosub P1 P2 * * *
64846 **
64847 ** Write the current address onto register P1
64848 ** and then jump to address P2.
64849 */
64850 case OP_Gosub: {            /* jump */
64851   assert( pOp->p1>0 && pOp->p1<=p->nMem );
64852   pIn1 = &aMem[pOp->p1];
64853   assert( (pIn1->flags & MEM_Dyn)==0 );
64854   memAboutToChange(p, pIn1);
64855   pIn1->flags = MEM_Int;
64856   pIn1->u.i = pc;
64857   REGISTER_TRACE(pOp->p1, pIn1);
64858   pc = pOp->p2 - 1;
64859   break;
64860 }
64861
64862 /* Opcode:  Return P1 * * * *
64863 **
64864 ** Jump to the next instruction after the address in register P1.
64865 */
64866 case OP_Return: {           /* in1 */
64867   pIn1 = &aMem[pOp->p1];
64868   assert( pIn1->flags & MEM_Int );
64869   pc = (int)pIn1->u.i;
64870   break;
64871 }
64872
64873 /* Opcode:  Yield P1 * * * *
64874 **
64875 ** Swap the program counter with the value in register P1.
64876 */
64877 case OP_Yield: {            /* in1 */
64878 #if 0  /* local variables moved into u.aa */
64879   int pcDest;
64880 #endif /* local variables moved into u.aa */
64881   pIn1 = &aMem[pOp->p1];
64882   assert( (pIn1->flags & MEM_Dyn)==0 );
64883   pIn1->flags = MEM_Int;
64884   u.aa.pcDest = (int)pIn1->u.i;
64885   pIn1->u.i = pc;
64886   REGISTER_TRACE(pOp->p1, pIn1);
64887   pc = u.aa.pcDest;
64888   break;
64889 }
64890
64891 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
64892 **
64893 ** Check the value in register P3.  If it is NULL then Halt using
64894 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
64895 ** value in register P3 is not NULL, then this routine is a no-op.
64896 */
64897 case OP_HaltIfNull: {      /* in3 */
64898   pIn3 = &aMem[pOp->p3];
64899   if( (pIn3->flags & MEM_Null)==0 ) break;
64900   /* Fall through into OP_Halt */
64901 }
64902
64903 /* Opcode:  Halt P1 P2 * P4 *
64904 **
64905 ** Exit immediately.  All open cursors, etc are closed
64906 ** automatically.
64907 **
64908 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
64909 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
64910 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
64911 ** whether or not to rollback the current transaction.  Do not rollback
64912 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
64913 ** then back out all changes that have occurred during this execution of the
64914 ** VDBE, but do not rollback the transaction. 
64915 **
64916 ** If P4 is not null then it is an error message string.
64917 **
64918 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
64919 ** every program.  So a jump past the last instruction of the program
64920 ** is the same as executing Halt.
64921 */
64922 case OP_Halt: {
64923   if( pOp->p1==SQLITE_OK && p->pFrame ){
64924     /* Halt the sub-program. Return control to the parent frame. */
64925     VdbeFrame *pFrame = p->pFrame;
64926     p->pFrame = pFrame->pParent;
64927     p->nFrame--;
64928     sqlite3VdbeSetChanges(db, p->nChange);
64929     pc = sqlite3VdbeFrameRestore(pFrame);
64930     lastRowid = db->lastRowid;
64931     if( pOp->p2==OE_Ignore ){
64932       /* Instruction pc is the OP_Program that invoked the sub-program 
64933       ** currently being halted. If the p2 instruction of this OP_Halt
64934       ** instruction is set to OE_Ignore, then the sub-program is throwing
64935       ** an IGNORE exception. In this case jump to the address specified
64936       ** as the p2 of the calling OP_Program.  */
64937       pc = p->aOp[pc].p2-1;
64938     }
64939     aOp = p->aOp;
64940     aMem = p->aMem;
64941     break;
64942   }
64943
64944   p->rc = pOp->p1;
64945   p->errorAction = (u8)pOp->p2;
64946   p->pc = pc;
64947   if( pOp->p4.z ){
64948     assert( p->rc!=SQLITE_OK );
64949     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
64950     testcase( sqlite3GlobalConfig.xLog!=0 );
64951     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
64952   }else if( p->rc ){
64953     testcase( sqlite3GlobalConfig.xLog!=0 );
64954     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
64955   }
64956   rc = sqlite3VdbeHalt(p);
64957   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
64958   if( rc==SQLITE_BUSY ){
64959     p->rc = rc = SQLITE_BUSY;
64960   }else{
64961     assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
64962     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
64963     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
64964   }
64965   goto vdbe_return;
64966 }
64967
64968 /* Opcode: Integer P1 P2 * * *
64969 **
64970 ** The 32-bit integer value P1 is written into register P2.
64971 */
64972 case OP_Integer: {         /* out2-prerelease */
64973   pOut->u.i = pOp->p1;
64974   break;
64975 }
64976
64977 /* Opcode: Int64 * P2 * P4 *
64978 **
64979 ** P4 is a pointer to a 64-bit integer value.
64980 ** Write that value into register P2.
64981 */
64982 case OP_Int64: {           /* out2-prerelease */
64983   assert( pOp->p4.pI64!=0 );
64984   pOut->u.i = *pOp->p4.pI64;
64985   break;
64986 }
64987
64988 #ifndef SQLITE_OMIT_FLOATING_POINT
64989 /* Opcode: Real * P2 * P4 *
64990 **
64991 ** P4 is a pointer to a 64-bit floating point value.
64992 ** Write that value into register P2.
64993 */
64994 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
64995   pOut->flags = MEM_Real;
64996   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
64997   pOut->r = *pOp->p4.pReal;
64998   break;
64999 }
65000 #endif
65001
65002 /* Opcode: String8 * P2 * P4 *
65003 **
65004 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
65005 ** into an OP_String before it is executed for the first time.
65006 */
65007 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
65008   assert( pOp->p4.z!=0 );
65009   pOp->opcode = OP_String;
65010   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
65011
65012 #ifndef SQLITE_OMIT_UTF16
65013   if( encoding!=SQLITE_UTF8 ){
65014     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
65015     if( rc==SQLITE_TOOBIG ) goto too_big;
65016     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
65017     assert( pOut->zMalloc==pOut->z );
65018     assert( pOut->flags & MEM_Dyn );
65019     pOut->zMalloc = 0;
65020     pOut->flags |= MEM_Static;
65021     pOut->flags &= ~MEM_Dyn;
65022     if( pOp->p4type==P4_DYNAMIC ){
65023       sqlite3DbFree(db, pOp->p4.z);
65024     }
65025     pOp->p4type = P4_DYNAMIC;
65026     pOp->p4.z = pOut->z;
65027     pOp->p1 = pOut->n;
65028   }
65029 #endif
65030   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
65031     goto too_big;
65032   }
65033   /* Fall through to the next case, OP_String */
65034 }
65035   
65036 /* Opcode: String P1 P2 * P4 *
65037 **
65038 ** The string value P4 of length P1 (bytes) is stored in register P2.
65039 */
65040 case OP_String: {          /* out2-prerelease */
65041   assert( pOp->p4.z!=0 );
65042   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
65043   pOut->z = pOp->p4.z;
65044   pOut->n = pOp->p1;
65045   pOut->enc = encoding;
65046   UPDATE_MAX_BLOBSIZE(pOut);
65047   break;
65048 }
65049
65050 /* Opcode: Null P1 P2 P3 * *
65051 **
65052 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
65053 ** NULL into register P3 and every register in between P2 and P3.  If P3
65054 ** is less than P2 (typically P3 is zero) then only register P2 is
65055 ** set to NULL.
65056 **
65057 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
65058 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
65059 ** OP_Ne or OP_Eq.
65060 */
65061 case OP_Null: {           /* out2-prerelease */
65062 #if 0  /* local variables moved into u.ab */
65063   int cnt;
65064   u16 nullFlag;
65065 #endif /* local variables moved into u.ab */
65066   u.ab.cnt = pOp->p3-pOp->p2;
65067   assert( pOp->p3<=p->nMem );
65068   pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
65069   while( u.ab.cnt>0 ){
65070     pOut++;
65071     memAboutToChange(p, pOut);
65072     VdbeMemRelease(pOut);
65073     pOut->flags = u.ab.nullFlag;
65074     u.ab.cnt--;
65075   }
65076   break;
65077 }
65078
65079
65080 /* Opcode: Blob P1 P2 * P4
65081 **
65082 ** P4 points to a blob of data P1 bytes long.  Store this
65083 ** blob in register P2.
65084 */
65085 case OP_Blob: {                /* out2-prerelease */
65086   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
65087   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
65088   pOut->enc = encoding;
65089   UPDATE_MAX_BLOBSIZE(pOut);
65090   break;
65091 }
65092
65093 /* Opcode: Variable P1 P2 * P4 *
65094 **
65095 ** Transfer the values of bound parameter P1 into register P2
65096 **
65097 ** If the parameter is named, then its name appears in P4 and P3==1.
65098 ** The P4 value is used by sqlite3_bind_parameter_name().
65099 */
65100 case OP_Variable: {            /* out2-prerelease */
65101 #if 0  /* local variables moved into u.ac */
65102   Mem *pVar;       /* Value being transferred */
65103 #endif /* local variables moved into u.ac */
65104
65105   assert( pOp->p1>0 && pOp->p1<=p->nVar );
65106   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
65107   u.ac.pVar = &p->aVar[pOp->p1 - 1];
65108   if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
65109     goto too_big;
65110   }
65111   sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
65112   UPDATE_MAX_BLOBSIZE(pOut);
65113   break;
65114 }
65115
65116 /* Opcode: Move P1 P2 P3 * *
65117 **
65118 ** Move the values in register P1..P1+P3 over into
65119 ** registers P2..P2+P3.  Registers P1..P1+P3 are
65120 ** left holding a NULL.  It is an error for register ranges
65121 ** P1..P1+P3 and P2..P2+P3 to overlap.
65122 */
65123 case OP_Move: {
65124 #if 0  /* local variables moved into u.ad */
65125   char *zMalloc;   /* Holding variable for allocated memory */
65126   int n;           /* Number of registers left to copy */
65127   int p1;          /* Register to copy from */
65128   int p2;          /* Register to copy to */
65129 #endif /* local variables moved into u.ad */
65130
65131   u.ad.n = pOp->p3 + 1;
65132   u.ad.p1 = pOp->p1;
65133   u.ad.p2 = pOp->p2;
65134   assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
65135   assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
65136
65137   pIn1 = &aMem[u.ad.p1];
65138   pOut = &aMem[u.ad.p2];
65139   while( u.ad.n-- ){
65140     assert( pOut<=&aMem[p->nMem] );
65141     assert( pIn1<=&aMem[p->nMem] );
65142     assert( memIsValid(pIn1) );
65143     memAboutToChange(p, pOut);
65144     u.ad.zMalloc = pOut->zMalloc;
65145     pOut->zMalloc = 0;
65146     sqlite3VdbeMemMove(pOut, pIn1);
65147 #ifdef SQLITE_DEBUG
65148     if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
65149       pOut->pScopyFrom += u.ad.p1 - pOp->p2;
65150     }
65151 #endif
65152     pIn1->zMalloc = u.ad.zMalloc;
65153     REGISTER_TRACE(u.ad.p2++, pOut);
65154     pIn1++;
65155     pOut++;
65156   }
65157   break;
65158 }
65159
65160 /* Opcode: Copy P1 P2 P3 * *
65161 **
65162 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
65163 **
65164 ** This instruction makes a deep copy of the value.  A duplicate
65165 ** is made of any string or blob constant.  See also OP_SCopy.
65166 */
65167 case OP_Copy: {
65168 #if 0  /* local variables moved into u.ae */
65169   int n;
65170 #endif /* local variables moved into u.ae */
65171
65172   u.ae.n = pOp->p3;
65173   pIn1 = &aMem[pOp->p1];
65174   pOut = &aMem[pOp->p2];
65175   assert( pOut!=pIn1 );
65176   while( 1 ){
65177     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65178     Deephemeralize(pOut);
65179 #ifdef SQLITE_DEBUG
65180     pOut->pScopyFrom = 0;
65181 #endif
65182     REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
65183     if( (u.ae.n--)==0 ) break;
65184     pOut++;
65185     pIn1++;
65186   }
65187   break;
65188 }
65189
65190 /* Opcode: SCopy P1 P2 * * *
65191 **
65192 ** Make a shallow copy of register P1 into register P2.
65193 **
65194 ** This instruction makes a shallow copy of the value.  If the value
65195 ** is a string or blob, then the copy is only a pointer to the
65196 ** original and hence if the original changes so will the copy.
65197 ** Worse, if the original is deallocated, the copy becomes invalid.
65198 ** Thus the program must guarantee that the original will not change
65199 ** during the lifetime of the copy.  Use OP_Copy to make a complete
65200 ** copy.
65201 */
65202 case OP_SCopy: {            /* in1, out2 */
65203   pIn1 = &aMem[pOp->p1];
65204   pOut = &aMem[pOp->p2];
65205   assert( pOut!=pIn1 );
65206   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65207 #ifdef SQLITE_DEBUG
65208   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
65209 #endif
65210   REGISTER_TRACE(pOp->p2, pOut);
65211   break;
65212 }
65213
65214 /* Opcode: ResultRow P1 P2 * * *
65215 **
65216 ** The registers P1 through P1+P2-1 contain a single row of
65217 ** results. This opcode causes the sqlite3_step() call to terminate
65218 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
65219 ** structure to provide access to the top P1 values as the result
65220 ** row.
65221 */
65222 case OP_ResultRow: {
65223 #if 0  /* local variables moved into u.af */
65224   Mem *pMem;
65225   int i;
65226 #endif /* local variables moved into u.af */
65227   assert( p->nResColumn==pOp->p2 );
65228   assert( pOp->p1>0 );
65229   assert( pOp->p1+pOp->p2<=p->nMem+1 );
65230
65231   /* If this statement has violated immediate foreign key constraints, do
65232   ** not return the number of rows modified. And do not RELEASE the statement
65233   ** transaction. It needs to be rolled back.  */
65234   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
65235     assert( db->flags&SQLITE_CountRows );
65236     assert( p->usesStmtJournal );
65237     break;
65238   }
65239
65240   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
65241   ** DML statements invoke this opcode to return the number of rows
65242   ** modified to the user. This is the only way that a VM that
65243   ** opens a statement transaction may invoke this opcode.
65244   **
65245   ** In case this is such a statement, close any statement transaction
65246   ** opened by this VM before returning control to the user. This is to
65247   ** ensure that statement-transactions are always nested, not overlapping.
65248   ** If the open statement-transaction is not closed here, then the user
65249   ** may step another VM that opens its own statement transaction. This
65250   ** may lead to overlapping statement transactions.
65251   **
65252   ** The statement transaction is never a top-level transaction.  Hence
65253   ** the RELEASE call below can never fail.
65254   */
65255   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
65256   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
65257   if( NEVER(rc!=SQLITE_OK) ){
65258     break;
65259   }
65260
65261   /* Invalidate all ephemeral cursor row caches */
65262   p->cacheCtr = (p->cacheCtr + 2)|1;
65263
65264   /* Make sure the results of the current row are \000 terminated
65265   ** and have an assigned type.  The results are de-ephemeralized as
65266   ** a side effect.
65267   */
65268   u.af.pMem = p->pResultSet = &aMem[pOp->p1];
65269   for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
65270     assert( memIsValid(&u.af.pMem[u.af.i]) );
65271     Deephemeralize(&u.af.pMem[u.af.i]);
65272     assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
65273             || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
65274     sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
65275     sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
65276     REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
65277   }
65278   if( db->mallocFailed ) goto no_mem;
65279
65280   /* Return SQLITE_ROW
65281   */
65282   p->pc = pc + 1;
65283   rc = SQLITE_ROW;
65284   goto vdbe_return;
65285 }
65286
65287 /* Opcode: Concat P1 P2 P3 * *
65288 **
65289 ** Add the text in register P1 onto the end of the text in
65290 ** register P2 and store the result in register P3.
65291 ** If either the P1 or P2 text are NULL then store NULL in P3.
65292 **
65293 **   P3 = P2 || P1
65294 **
65295 ** It is illegal for P1 and P3 to be the same register. Sometimes,
65296 ** if P3 is the same register as P2, the implementation is able
65297 ** to avoid a memcpy().
65298 */
65299 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
65300 #if 0  /* local variables moved into u.ag */
65301   i64 nByte;
65302 #endif /* local variables moved into u.ag */
65303
65304   pIn1 = &aMem[pOp->p1];
65305   pIn2 = &aMem[pOp->p2];
65306   pOut = &aMem[pOp->p3];
65307   assert( pIn1!=pOut );
65308   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
65309     sqlite3VdbeMemSetNull(pOut);
65310     break;
65311   }
65312   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
65313   Stringify(pIn1, encoding);
65314   Stringify(pIn2, encoding);
65315   u.ag.nByte = pIn1->n + pIn2->n;
65316   if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
65317     goto too_big;
65318   }
65319   MemSetTypeFlag(pOut, MEM_Str);
65320   if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
65321     goto no_mem;
65322   }
65323   if( pOut!=pIn2 ){
65324     memcpy(pOut->z, pIn2->z, pIn2->n);
65325   }
65326   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
65327   pOut->z[u.ag.nByte] = 0;
65328   pOut->z[u.ag.nByte+1] = 0;
65329   pOut->flags |= MEM_Term;
65330   pOut->n = (int)u.ag.nByte;
65331   pOut->enc = encoding;
65332   UPDATE_MAX_BLOBSIZE(pOut);
65333   break;
65334 }
65335
65336 /* Opcode: Add P1 P2 P3 * *
65337 **
65338 ** Add the value in register P1 to the value in register P2
65339 ** and store the result in register P3.
65340 ** If either input is NULL, the result is NULL.
65341 */
65342 /* Opcode: Multiply P1 P2 P3 * *
65343 **
65344 **
65345 ** Multiply the value in register P1 by the value in register P2
65346 ** and store the result in register P3.
65347 ** If either input is NULL, the result is NULL.
65348 */
65349 /* Opcode: Subtract P1 P2 P3 * *
65350 **
65351 ** Subtract the value in register P1 from the value in register P2
65352 ** and store the result in register P3.
65353 ** If either input is NULL, the result is NULL.
65354 */
65355 /* Opcode: Divide P1 P2 P3 * *
65356 **
65357 ** Divide the value in register P1 by the value in register P2
65358 ** and store the result in register P3 (P3=P2/P1). If the value in 
65359 ** register P1 is zero, then the result is NULL. If either input is 
65360 ** NULL, the result is NULL.
65361 */
65362 /* Opcode: Remainder P1 P2 P3 * *
65363 **
65364 ** Compute the remainder after integer division of the value in
65365 ** register P1 by the value in register P2 and store the result in P3. 
65366 ** If the value in register P2 is zero the result is NULL.
65367 ** If either operand is NULL, the result is NULL.
65368 */
65369 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
65370 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
65371 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
65372 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
65373 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
65374 #if 0  /* local variables moved into u.ah */
65375   char bIntint;   /* Started out as two integer operands */
65376   int flags;      /* Combined MEM_* flags from both inputs */
65377   i64 iA;         /* Integer value of left operand */
65378   i64 iB;         /* Integer value of right operand */
65379   double rA;      /* Real value of left operand */
65380   double rB;      /* Real value of right operand */
65381 #endif /* local variables moved into u.ah */
65382
65383   pIn1 = &aMem[pOp->p1];
65384   applyNumericAffinity(pIn1);
65385   pIn2 = &aMem[pOp->p2];
65386   applyNumericAffinity(pIn2);
65387   pOut = &aMem[pOp->p3];
65388   u.ah.flags = pIn1->flags | pIn2->flags;
65389   if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
65390   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
65391     u.ah.iA = pIn1->u.i;
65392     u.ah.iB = pIn2->u.i;
65393     u.ah.bIntint = 1;
65394     switch( pOp->opcode ){
65395       case OP_Add:       if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
65396       case OP_Subtract:  if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
65397       case OP_Multiply:  if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
65398       case OP_Divide: {
65399         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
65400         if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
65401         u.ah.iB /= u.ah.iA;
65402         break;
65403       }
65404       default: {
65405         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
65406         if( u.ah.iA==-1 ) u.ah.iA = 1;
65407         u.ah.iB %= u.ah.iA;
65408         break;
65409       }
65410     }
65411     pOut->u.i = u.ah.iB;
65412     MemSetTypeFlag(pOut, MEM_Int);
65413   }else{
65414     u.ah.bIntint = 0;
65415 fp_math:
65416     u.ah.rA = sqlite3VdbeRealValue(pIn1);
65417     u.ah.rB = sqlite3VdbeRealValue(pIn2);
65418     switch( pOp->opcode ){
65419       case OP_Add:         u.ah.rB += u.ah.rA;       break;
65420       case OP_Subtract:    u.ah.rB -= u.ah.rA;       break;
65421       case OP_Multiply:    u.ah.rB *= u.ah.rA;       break;
65422       case OP_Divide: {
65423         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
65424         if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
65425         u.ah.rB /= u.ah.rA;
65426         break;
65427       }
65428       default: {
65429         u.ah.iA = (i64)u.ah.rA;
65430         u.ah.iB = (i64)u.ah.rB;
65431         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
65432         if( u.ah.iA==-1 ) u.ah.iA = 1;
65433         u.ah.rB = (double)(u.ah.iB % u.ah.iA);
65434         break;
65435       }
65436     }
65437 #ifdef SQLITE_OMIT_FLOATING_POINT
65438     pOut->u.i = u.ah.rB;
65439     MemSetTypeFlag(pOut, MEM_Int);
65440 #else
65441     if( sqlite3IsNaN(u.ah.rB) ){
65442       goto arithmetic_result_is_null;
65443     }
65444     pOut->r = u.ah.rB;
65445     MemSetTypeFlag(pOut, MEM_Real);
65446     if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
65447       sqlite3VdbeIntegerAffinity(pOut);
65448     }
65449 #endif
65450   }
65451   break;
65452
65453 arithmetic_result_is_null:
65454   sqlite3VdbeMemSetNull(pOut);
65455   break;
65456 }
65457
65458 /* Opcode: CollSeq P1 * * P4
65459 **
65460 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
65461 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
65462 ** be returned. This is used by the built-in min(), max() and nullif()
65463 ** functions.
65464 **
65465 ** If P1 is not zero, then it is a register that a subsequent min() or
65466 ** max() aggregate will set to 1 if the current row is not the minimum or
65467 ** maximum.  The P1 register is initialized to 0 by this instruction.
65468 **
65469 ** The interface used by the implementation of the aforementioned functions
65470 ** to retrieve the collation sequence set by this opcode is not available
65471 ** publicly, only to user functions defined in func.c.
65472 */
65473 case OP_CollSeq: {
65474   assert( pOp->p4type==P4_COLLSEQ );
65475   if( pOp->p1 ){
65476     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
65477   }
65478   break;
65479 }
65480
65481 /* Opcode: Function P1 P2 P3 P4 P5
65482 **
65483 ** Invoke a user function (P4 is a pointer to a Function structure that
65484 ** defines the function) with P5 arguments taken from register P2 and
65485 ** successors.  The result of the function is stored in register P3.
65486 ** Register P3 must not be one of the function inputs.
65487 **
65488 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
65489 ** function was determined to be constant at compile time. If the first
65490 ** argument was constant then bit 0 of P1 is set. This is used to determine
65491 ** whether meta data associated with a user function argument using the
65492 ** sqlite3_set_auxdata() API may be safely retained until the next
65493 ** invocation of this opcode.
65494 **
65495 ** See also: AggStep and AggFinal
65496 */
65497 case OP_Function: {
65498 #if 0  /* local variables moved into u.ai */
65499   int i;
65500   Mem *pArg;
65501   sqlite3_context ctx;
65502   sqlite3_value **apVal;
65503   int n;
65504 #endif /* local variables moved into u.ai */
65505
65506   u.ai.n = pOp->p5;
65507   u.ai.apVal = p->apArg;
65508   assert( u.ai.apVal || u.ai.n==0 );
65509   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65510   pOut = &aMem[pOp->p3];
65511   memAboutToChange(p, pOut);
65512
65513   assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=p->nMem+1) );
65514   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
65515   u.ai.pArg = &aMem[pOp->p2];
65516   for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
65517     assert( memIsValid(u.ai.pArg) );
65518     u.ai.apVal[u.ai.i] = u.ai.pArg;
65519     Deephemeralize(u.ai.pArg);
65520     sqlite3VdbeMemStoreType(u.ai.pArg);
65521     REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
65522   }
65523
65524   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
65525   if( pOp->p4type==P4_FUNCDEF ){
65526     u.ai.ctx.pFunc = pOp->p4.pFunc;
65527     u.ai.ctx.pVdbeFunc = 0;
65528   }else{
65529     u.ai.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
65530     u.ai.ctx.pFunc = u.ai.ctx.pVdbeFunc->pFunc;
65531   }
65532
65533   u.ai.ctx.s.flags = MEM_Null;
65534   u.ai.ctx.s.db = db;
65535   u.ai.ctx.s.xDel = 0;
65536   u.ai.ctx.s.zMalloc = 0;
65537
65538   /* The output cell may already have a buffer allocated. Move
65539   ** the pointer to u.ai.ctx.s so in case the user-function can use
65540   ** the already allocated buffer instead of allocating a new one.
65541   */
65542   sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
65543   MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
65544
65545   u.ai.ctx.isError = 0;
65546   if( u.ai.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
65547     assert( pOp>aOp );
65548     assert( pOp[-1].p4type==P4_COLLSEQ );
65549     assert( pOp[-1].opcode==OP_CollSeq );
65550     u.ai.ctx.pColl = pOp[-1].p4.pColl;
65551   }
65552   db->lastRowid = lastRowid;
65553   (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
65554   lastRowid = db->lastRowid;
65555
65556   /* If any auxiliary data functions have been called by this user function,
65557   ** immediately call the destructor for any non-static values.
65558   */
65559   if( u.ai.ctx.pVdbeFunc ){
65560     sqlite3VdbeDeleteAuxData(u.ai.ctx.pVdbeFunc, pOp->p1);
65561     pOp->p4.pVdbeFunc = u.ai.ctx.pVdbeFunc;
65562     pOp->p4type = P4_VDBEFUNC;
65563   }
65564
65565   if( db->mallocFailed ){
65566     /* Even though a malloc() has failed, the implementation of the
65567     ** user function may have called an sqlite3_result_XXX() function
65568     ** to return a value. The following call releases any resources
65569     ** associated with such a value.
65570     */
65571     sqlite3VdbeMemRelease(&u.ai.ctx.s);
65572     goto no_mem;
65573   }
65574
65575   /* If the function returned an error, throw an exception */
65576   if( u.ai.ctx.isError ){
65577     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
65578     rc = u.ai.ctx.isError;
65579   }
65580
65581   /* Copy the result of the function into register P3 */
65582   sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
65583   sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
65584   if( sqlite3VdbeMemTooBig(pOut) ){
65585     goto too_big;
65586   }
65587
65588 #if 0
65589   /* The app-defined function has done something that as caused this
65590   ** statement to expire.  (Perhaps the function called sqlite3_exec()
65591   ** with a CREATE TABLE statement.)
65592   */
65593   if( p->expired ) rc = SQLITE_ABORT;
65594 #endif
65595
65596   REGISTER_TRACE(pOp->p3, pOut);
65597   UPDATE_MAX_BLOBSIZE(pOut);
65598   break;
65599 }
65600
65601 /* Opcode: BitAnd P1 P2 P3 * *
65602 **
65603 ** Take the bit-wise AND of the values in register P1 and P2 and
65604 ** store the result in register P3.
65605 ** If either input is NULL, the result is NULL.
65606 */
65607 /* Opcode: BitOr P1 P2 P3 * *
65608 **
65609 ** Take the bit-wise OR of the values in register P1 and P2 and
65610 ** store the result in register P3.
65611 ** If either input is NULL, the result is NULL.
65612 */
65613 /* Opcode: ShiftLeft P1 P2 P3 * *
65614 **
65615 ** Shift the integer value in register P2 to the left by the
65616 ** number of bits specified by the integer in register P1.
65617 ** Store the result in register P3.
65618 ** If either input is NULL, the result is NULL.
65619 */
65620 /* Opcode: ShiftRight P1 P2 P3 * *
65621 **
65622 ** Shift the integer value in register P2 to the right by the
65623 ** number of bits specified by the integer in register P1.
65624 ** Store the result in register P3.
65625 ** If either input is NULL, the result is NULL.
65626 */
65627 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
65628 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
65629 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
65630 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
65631 #if 0  /* local variables moved into u.aj */
65632   i64 iA;
65633   u64 uA;
65634   i64 iB;
65635   u8 op;
65636 #endif /* local variables moved into u.aj */
65637
65638   pIn1 = &aMem[pOp->p1];
65639   pIn2 = &aMem[pOp->p2];
65640   pOut = &aMem[pOp->p3];
65641   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
65642     sqlite3VdbeMemSetNull(pOut);
65643     break;
65644   }
65645   u.aj.iA = sqlite3VdbeIntValue(pIn2);
65646   u.aj.iB = sqlite3VdbeIntValue(pIn1);
65647   u.aj.op = pOp->opcode;
65648   if( u.aj.op==OP_BitAnd ){
65649     u.aj.iA &= u.aj.iB;
65650   }else if( u.aj.op==OP_BitOr ){
65651     u.aj.iA |= u.aj.iB;
65652   }else if( u.aj.iB!=0 ){
65653     assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
65654
65655     /* If shifting by a negative amount, shift in the other direction */
65656     if( u.aj.iB<0 ){
65657       assert( OP_ShiftRight==OP_ShiftLeft+1 );
65658       u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
65659       u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
65660     }
65661
65662     if( u.aj.iB>=64 ){
65663       u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
65664     }else{
65665       memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
65666       if( u.aj.op==OP_ShiftLeft ){
65667         u.aj.uA <<= u.aj.iB;
65668       }else{
65669         u.aj.uA >>= u.aj.iB;
65670         /* Sign-extend on a right shift of a negative number */
65671         if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
65672       }
65673       memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
65674     }
65675   }
65676   pOut->u.i = u.aj.iA;
65677   MemSetTypeFlag(pOut, MEM_Int);
65678   break;
65679 }
65680
65681 /* Opcode: AddImm  P1 P2 * * *
65682 ** 
65683 ** Add the constant P2 to the value in register P1.
65684 ** The result is always an integer.
65685 **
65686 ** To force any register to be an integer, just add 0.
65687 */
65688 case OP_AddImm: {            /* in1 */
65689   pIn1 = &aMem[pOp->p1];
65690   memAboutToChange(p, pIn1);
65691   sqlite3VdbeMemIntegerify(pIn1);
65692   pIn1->u.i += pOp->p2;
65693   break;
65694 }
65695
65696 /* Opcode: MustBeInt P1 P2 * * *
65697 ** 
65698 ** Force the value in register P1 to be an integer.  If the value
65699 ** in P1 is not an integer and cannot be converted into an integer
65700 ** without data loss, then jump immediately to P2, or if P2==0
65701 ** raise an SQLITE_MISMATCH exception.
65702 */
65703 case OP_MustBeInt: {            /* jump, in1 */
65704   pIn1 = &aMem[pOp->p1];
65705   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
65706   if( (pIn1->flags & MEM_Int)==0 ){
65707     if( pOp->p2==0 ){
65708       rc = SQLITE_MISMATCH;
65709       goto abort_due_to_error;
65710     }else{
65711       pc = pOp->p2 - 1;
65712     }
65713   }else{
65714     MemSetTypeFlag(pIn1, MEM_Int);
65715   }
65716   break;
65717 }
65718
65719 #ifndef SQLITE_OMIT_FLOATING_POINT
65720 /* Opcode: RealAffinity P1 * * * *
65721 **
65722 ** If register P1 holds an integer convert it to a real value.
65723 **
65724 ** This opcode is used when extracting information from a column that
65725 ** has REAL affinity.  Such column values may still be stored as
65726 ** integers, for space efficiency, but after extraction we want them
65727 ** to have only a real value.
65728 */
65729 case OP_RealAffinity: {                  /* in1 */
65730   pIn1 = &aMem[pOp->p1];
65731   if( pIn1->flags & MEM_Int ){
65732     sqlite3VdbeMemRealify(pIn1);
65733   }
65734   break;
65735 }
65736 #endif
65737
65738 #ifndef SQLITE_OMIT_CAST
65739 /* Opcode: ToText P1 * * * *
65740 **
65741 ** Force the value in register P1 to be text.
65742 ** If the value is numeric, convert it to a string using the
65743 ** equivalent of printf().  Blob values are unchanged and
65744 ** are afterwards simply interpreted as text.
65745 **
65746 ** A NULL value is not changed by this routine.  It remains NULL.
65747 */
65748 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
65749   pIn1 = &aMem[pOp->p1];
65750   memAboutToChange(p, pIn1);
65751   if( pIn1->flags & MEM_Null ) break;
65752   assert( MEM_Str==(MEM_Blob>>3) );
65753   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
65754   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
65755   rc = ExpandBlob(pIn1);
65756   assert( pIn1->flags & MEM_Str || db->mallocFailed );
65757   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
65758   UPDATE_MAX_BLOBSIZE(pIn1);
65759   break;
65760 }
65761
65762 /* Opcode: ToBlob P1 * * * *
65763 **
65764 ** Force the value in register P1 to be a BLOB.
65765 ** If the value is numeric, convert it to a string first.
65766 ** Strings are simply reinterpreted as blobs with no change
65767 ** to the underlying data.
65768 **
65769 ** A NULL value is not changed by this routine.  It remains NULL.
65770 */
65771 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
65772   pIn1 = &aMem[pOp->p1];
65773   if( pIn1->flags & MEM_Null ) break;
65774   if( (pIn1->flags & MEM_Blob)==0 ){
65775     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
65776     assert( pIn1->flags & MEM_Str || db->mallocFailed );
65777     MemSetTypeFlag(pIn1, MEM_Blob);
65778   }else{
65779     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
65780   }
65781   UPDATE_MAX_BLOBSIZE(pIn1);
65782   break;
65783 }
65784
65785 /* Opcode: ToNumeric P1 * * * *
65786 **
65787 ** Force the value in register P1 to be numeric (either an
65788 ** integer or a floating-point number.)
65789 ** If the value is text or blob, try to convert it to an using the
65790 ** equivalent of atoi() or atof() and store 0 if no such conversion 
65791 ** is possible.
65792 **
65793 ** A NULL value is not changed by this routine.  It remains NULL.
65794 */
65795 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
65796   pIn1 = &aMem[pOp->p1];
65797   sqlite3VdbeMemNumerify(pIn1);
65798   break;
65799 }
65800 #endif /* SQLITE_OMIT_CAST */
65801
65802 /* Opcode: ToInt P1 * * * *
65803 **
65804 ** Force the value in register P1 to be an integer.  If
65805 ** The value is currently a real number, drop its fractional part.
65806 ** If the value is text or blob, try to convert it to an integer using the
65807 ** equivalent of atoi() and store 0 if no such conversion is possible.
65808 **
65809 ** A NULL value is not changed by this routine.  It remains NULL.
65810 */
65811 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
65812   pIn1 = &aMem[pOp->p1];
65813   if( (pIn1->flags & MEM_Null)==0 ){
65814     sqlite3VdbeMemIntegerify(pIn1);
65815   }
65816   break;
65817 }
65818
65819 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
65820 /* Opcode: ToReal P1 * * * *
65821 **
65822 ** Force the value in register P1 to be a floating point number.
65823 ** If The value is currently an integer, convert it.
65824 ** If the value is text or blob, try to convert it to an integer using the
65825 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
65826 **
65827 ** A NULL value is not changed by this routine.  It remains NULL.
65828 */
65829 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
65830   pIn1 = &aMem[pOp->p1];
65831   memAboutToChange(p, pIn1);
65832   if( (pIn1->flags & MEM_Null)==0 ){
65833     sqlite3VdbeMemRealify(pIn1);
65834   }
65835   break;
65836 }
65837 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
65838
65839 /* Opcode: Lt P1 P2 P3 P4 P5
65840 **
65841 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
65842 ** jump to address P2.  
65843 **
65844 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
65845 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
65846 ** bit is clear then fall through if either operand is NULL.
65847 **
65848 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
65849 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
65850 ** to coerce both inputs according to this affinity before the
65851 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
65852 ** affinity is used. Note that the affinity conversions are stored
65853 ** back into the input registers P1 and P3.  So this opcode can cause
65854 ** persistent changes to registers P1 and P3.
65855 **
65856 ** Once any conversions have taken place, and neither value is NULL, 
65857 ** the values are compared. If both values are blobs then memcmp() is
65858 ** used to determine the results of the comparison.  If both values
65859 ** are text, then the appropriate collating function specified in
65860 ** P4 is  used to do the comparison.  If P4 is not specified then
65861 ** memcmp() is used to compare text string.  If both values are
65862 ** numeric, then a numeric comparison is used. If the two values
65863 ** are of different types, then numbers are considered less than
65864 ** strings and strings are considered less than blobs.
65865 **
65866 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
65867 ** store a boolean result (either 0, or 1, or NULL) in register P2.
65868 **
65869 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
65870 ** equal to one another, provided that they do not have their MEM_Cleared
65871 ** bit set.
65872 */
65873 /* Opcode: Ne P1 P2 P3 P4 P5
65874 **
65875 ** This works just like the Lt opcode except that the jump is taken if
65876 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
65877 ** additional information.
65878 **
65879 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
65880 ** true or false and is never NULL.  If both operands are NULL then the result
65881 ** of comparison is false.  If either operand is NULL then the result is true.
65882 ** If neither operand is NULL the result is the same as it would be if
65883 ** the SQLITE_NULLEQ flag were omitted from P5.
65884 */
65885 /* Opcode: Eq P1 P2 P3 P4 P5
65886 **
65887 ** This works just like the Lt opcode except that the jump is taken if
65888 ** the operands in registers P1 and P3 are equal.
65889 ** See the Lt opcode for additional information.
65890 **
65891 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
65892 ** true or false and is never NULL.  If both operands are NULL then the result
65893 ** of comparison is true.  If either operand is NULL then the result is false.
65894 ** If neither operand is NULL the result is the same as it would be if
65895 ** the SQLITE_NULLEQ flag were omitted from P5.
65896 */
65897 /* Opcode: Le P1 P2 P3 P4 P5
65898 **
65899 ** This works just like the Lt opcode except that the jump is taken if
65900 ** the content of register P3 is less than or equal to the content of
65901 ** register P1.  See the Lt opcode for additional information.
65902 */
65903 /* Opcode: Gt P1 P2 P3 P4 P5
65904 **
65905 ** This works just like the Lt opcode except that the jump is taken if
65906 ** the content of register P3 is greater than the content of
65907 ** register P1.  See the Lt opcode for additional information.
65908 */
65909 /* Opcode: Ge P1 P2 P3 P4 P5
65910 **
65911 ** This works just like the Lt opcode except that the jump is taken if
65912 ** the content of register P3 is greater than or equal to the content of
65913 ** register P1.  See the Lt opcode for additional information.
65914 */
65915 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
65916 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
65917 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
65918 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
65919 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
65920 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
65921 #if 0  /* local variables moved into u.ak */
65922   int res;            /* Result of the comparison of pIn1 against pIn3 */
65923   char affinity;      /* Affinity to use for comparison */
65924   u16 flags1;         /* Copy of initial value of pIn1->flags */
65925   u16 flags3;         /* Copy of initial value of pIn3->flags */
65926 #endif /* local variables moved into u.ak */
65927
65928   pIn1 = &aMem[pOp->p1];
65929   pIn3 = &aMem[pOp->p3];
65930   u.ak.flags1 = pIn1->flags;
65931   u.ak.flags3 = pIn3->flags;
65932   if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
65933     /* One or both operands are NULL */
65934     if( pOp->p5 & SQLITE_NULLEQ ){
65935       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
65936       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
65937       ** or not both operands are null.
65938       */
65939       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
65940       assert( (u.ak.flags1 & MEM_Cleared)==0 );
65941       if( (u.ak.flags1&MEM_Null)!=0
65942        && (u.ak.flags3&MEM_Null)!=0
65943        && (u.ak.flags3&MEM_Cleared)==0
65944       ){
65945         u.ak.res = 0;  /* Results are equal */
65946       }else{
65947         u.ak.res = 1;  /* Results are not equal */
65948       }
65949     }else{
65950       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
65951       ** then the result is always NULL.
65952       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
65953       */
65954       if( pOp->p5 & SQLITE_STOREP2 ){
65955         pOut = &aMem[pOp->p2];
65956         MemSetTypeFlag(pOut, MEM_Null);
65957         REGISTER_TRACE(pOp->p2, pOut);
65958       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
65959         pc = pOp->p2-1;
65960       }
65961       break;
65962     }
65963   }else{
65964     /* Neither operand is NULL.  Do a comparison. */
65965     u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
65966     if( u.ak.affinity ){
65967       applyAffinity(pIn1, u.ak.affinity, encoding);
65968       applyAffinity(pIn3, u.ak.affinity, encoding);
65969       if( db->mallocFailed ) goto no_mem;
65970     }
65971
65972     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
65973     ExpandBlob(pIn1);
65974     ExpandBlob(pIn3);
65975     u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
65976   }
65977   switch( pOp->opcode ){
65978     case OP_Eq:    u.ak.res = u.ak.res==0;     break;
65979     case OP_Ne:    u.ak.res = u.ak.res!=0;     break;
65980     case OP_Lt:    u.ak.res = u.ak.res<0;      break;
65981     case OP_Le:    u.ak.res = u.ak.res<=0;     break;
65982     case OP_Gt:    u.ak.res = u.ak.res>0;      break;
65983     default:       u.ak.res = u.ak.res>=0;     break;
65984   }
65985
65986   if( pOp->p5 & SQLITE_STOREP2 ){
65987     pOut = &aMem[pOp->p2];
65988     memAboutToChange(p, pOut);
65989     MemSetTypeFlag(pOut, MEM_Int);
65990     pOut->u.i = u.ak.res;
65991     REGISTER_TRACE(pOp->p2, pOut);
65992   }else if( u.ak.res ){
65993     pc = pOp->p2-1;
65994   }
65995
65996   /* Undo any changes made by applyAffinity() to the input registers. */
65997   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
65998   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
65999   break;
66000 }
66001
66002 /* Opcode: Permutation * * * P4 *
66003 **
66004 ** Set the permutation used by the OP_Compare operator to be the array
66005 ** of integers in P4.
66006 **
66007 ** The permutation is only valid until the next OP_Compare that has
66008 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should 
66009 ** occur immediately prior to the OP_Compare.
66010 */
66011 case OP_Permutation: {
66012   assert( pOp->p4type==P4_INTARRAY );
66013   assert( pOp->p4.ai );
66014   aPermute = pOp->p4.ai;
66015   break;
66016 }
66017
66018 /* Opcode: Compare P1 P2 P3 P4 P5
66019 **
66020 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
66021 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
66022 ** the comparison for use by the next OP_Jump instruct.
66023 **
66024 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
66025 ** determined by the most recent OP_Permutation operator.  If the
66026 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
66027 ** order.
66028 **
66029 ** P4 is a KeyInfo structure that defines collating sequences and sort
66030 ** orders for the comparison.  The permutation applies to registers
66031 ** only.  The KeyInfo elements are used sequentially.
66032 **
66033 ** The comparison is a sort comparison, so NULLs compare equal,
66034 ** NULLs are less than numbers, numbers are less than strings,
66035 ** and strings are less than blobs.
66036 */
66037 case OP_Compare: {
66038 #if 0  /* local variables moved into u.al */
66039   int n;
66040   int i;
66041   int p1;
66042   int p2;
66043   const KeyInfo *pKeyInfo;
66044   int idx;
66045   CollSeq *pColl;    /* Collating sequence to use on this term */
66046   int bRev;          /* True for DESCENDING sort order */
66047 #endif /* local variables moved into u.al */
66048
66049   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
66050   u.al.n = pOp->p3;
66051   u.al.pKeyInfo = pOp->p4.pKeyInfo;
66052   assert( u.al.n>0 );
66053   assert( u.al.pKeyInfo!=0 );
66054   u.al.p1 = pOp->p1;
66055   u.al.p2 = pOp->p2;
66056 #if SQLITE_DEBUG
66057   if( aPermute ){
66058     int k, mx = 0;
66059     for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
66060     assert( u.al.p1>0 && u.al.p1+mx<=p->nMem+1 );
66061     assert( u.al.p2>0 && u.al.p2+mx<=p->nMem+1 );
66062   }else{
66063     assert( u.al.p1>0 && u.al.p1+u.al.n<=p->nMem+1 );
66064     assert( u.al.p2>0 && u.al.p2+u.al.n<=p->nMem+1 );
66065   }
66066 #endif /* SQLITE_DEBUG */
66067   for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
66068     u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
66069     assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
66070     assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
66071     REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
66072     REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
66073     assert( u.al.i<u.al.pKeyInfo->nField );
66074     u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
66075     u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
66076     iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
66077     if( iCompare ){
66078       if( u.al.bRev ) iCompare = -iCompare;
66079       break;
66080     }
66081   }
66082   aPermute = 0;
66083   break;
66084 }
66085
66086 /* Opcode: Jump P1 P2 P3 * *
66087 **
66088 ** Jump to the instruction at address P1, P2, or P3 depending on whether
66089 ** in the most recent OP_Compare instruction the P1 vector was less than
66090 ** equal to, or greater than the P2 vector, respectively.
66091 */
66092 case OP_Jump: {             /* jump */
66093   if( iCompare<0 ){
66094     pc = pOp->p1 - 1;
66095   }else if( iCompare==0 ){
66096     pc = pOp->p2 - 1;
66097   }else{
66098     pc = pOp->p3 - 1;
66099   }
66100   break;
66101 }
66102
66103 /* Opcode: And P1 P2 P3 * *
66104 **
66105 ** Take the logical AND of the values in registers P1 and P2 and
66106 ** write the result into register P3.
66107 **
66108 ** If either P1 or P2 is 0 (false) then the result is 0 even if
66109 ** the other input is NULL.  A NULL and true or two NULLs give
66110 ** a NULL output.
66111 */
66112 /* Opcode: Or P1 P2 P3 * *
66113 **
66114 ** Take the logical OR of the values in register P1 and P2 and
66115 ** store the answer in register P3.
66116 **
66117 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
66118 ** even if the other input is NULL.  A NULL and false or two NULLs
66119 ** give a NULL output.
66120 */
66121 case OP_And:              /* same as TK_AND, in1, in2, out3 */
66122 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
66123 #if 0  /* local variables moved into u.am */
66124   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
66125   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
66126 #endif /* local variables moved into u.am */
66127
66128   pIn1 = &aMem[pOp->p1];
66129   if( pIn1->flags & MEM_Null ){
66130     u.am.v1 = 2;
66131   }else{
66132     u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
66133   }
66134   pIn2 = &aMem[pOp->p2];
66135   if( pIn2->flags & MEM_Null ){
66136     u.am.v2 = 2;
66137   }else{
66138     u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
66139   }
66140   if( pOp->opcode==OP_And ){
66141     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
66142     u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
66143   }else{
66144     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
66145     u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
66146   }
66147   pOut = &aMem[pOp->p3];
66148   if( u.am.v1==2 ){
66149     MemSetTypeFlag(pOut, MEM_Null);
66150   }else{
66151     pOut->u.i = u.am.v1;
66152     MemSetTypeFlag(pOut, MEM_Int);
66153   }
66154   break;
66155 }
66156
66157 /* Opcode: Not P1 P2 * * *
66158 **
66159 ** Interpret the value in register P1 as a boolean value.  Store the
66160 ** boolean complement in register P2.  If the value in register P1 is 
66161 ** NULL, then a NULL is stored in P2.
66162 */
66163 case OP_Not: {                /* same as TK_NOT, in1, out2 */
66164   pIn1 = &aMem[pOp->p1];
66165   pOut = &aMem[pOp->p2];
66166   if( pIn1->flags & MEM_Null ){
66167     sqlite3VdbeMemSetNull(pOut);
66168   }else{
66169     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
66170   }
66171   break;
66172 }
66173
66174 /* Opcode: BitNot P1 P2 * * *
66175 **
66176 ** Interpret the content of register P1 as an integer.  Store the
66177 ** ones-complement of the P1 value into register P2.  If P1 holds
66178 ** a NULL then store a NULL in P2.
66179 */
66180 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
66181   pIn1 = &aMem[pOp->p1];
66182   pOut = &aMem[pOp->p2];
66183   if( pIn1->flags & MEM_Null ){
66184     sqlite3VdbeMemSetNull(pOut);
66185   }else{
66186     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
66187   }
66188   break;
66189 }
66190
66191 /* Opcode: Once P1 P2 * * *
66192 **
66193 ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
66194 ** set the flag and fall through to the next instruction.
66195 */
66196 case OP_Once: {             /* jump */
66197   assert( pOp->p1<p->nOnceFlag );
66198   if( p->aOnceFlag[pOp->p1] ){
66199     pc = pOp->p2-1;
66200   }else{
66201     p->aOnceFlag[pOp->p1] = 1;
66202   }
66203   break;
66204 }
66205
66206 /* Opcode: If P1 P2 P3 * *
66207 **
66208 ** Jump to P2 if the value in register P1 is true.  The value
66209 ** is considered true if it is numeric and non-zero.  If the value
66210 ** in P1 is NULL then take the jump if P3 is non-zero.
66211 */
66212 /* Opcode: IfNot P1 P2 P3 * *
66213 **
66214 ** Jump to P2 if the value in register P1 is False.  The value
66215 ** is considered false if it has a numeric value of zero.  If the value
66216 ** in P1 is NULL then take the jump if P3 is zero.
66217 */
66218 case OP_If:                 /* jump, in1 */
66219 case OP_IfNot: {            /* jump, in1 */
66220 #if 0  /* local variables moved into u.an */
66221   int c;
66222 #endif /* local variables moved into u.an */
66223   pIn1 = &aMem[pOp->p1];
66224   if( pIn1->flags & MEM_Null ){
66225     u.an.c = pOp->p3;
66226   }else{
66227 #ifdef SQLITE_OMIT_FLOATING_POINT
66228     u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
66229 #else
66230     u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
66231 #endif
66232     if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
66233   }
66234   if( u.an.c ){
66235     pc = pOp->p2-1;
66236   }
66237   break;
66238 }
66239
66240 /* Opcode: IsNull P1 P2 * * *
66241 **
66242 ** Jump to P2 if the value in register P1 is NULL.
66243 */
66244 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
66245   pIn1 = &aMem[pOp->p1];
66246   if( (pIn1->flags & MEM_Null)!=0 ){
66247     pc = pOp->p2 - 1;
66248   }
66249   break;
66250 }
66251
66252 /* Opcode: NotNull P1 P2 * * *
66253 **
66254 ** Jump to P2 if the value in register P1 is not NULL.  
66255 */
66256 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
66257   pIn1 = &aMem[pOp->p1];
66258   if( (pIn1->flags & MEM_Null)==0 ){
66259     pc = pOp->p2 - 1;
66260   }
66261   break;
66262 }
66263
66264 /* Opcode: Column P1 P2 P3 P4 P5
66265 **
66266 ** Interpret the data that cursor P1 points to as a structure built using
66267 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
66268 ** information about the format of the data.)  Extract the P2-th column
66269 ** from this record.  If there are less that (P2+1) 
66270 ** values in the record, extract a NULL.
66271 **
66272 ** The value extracted is stored in register P3.
66273 **
66274 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
66275 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
66276 ** the result.
66277 **
66278 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
66279 ** then the cache of the cursor is reset prior to extracting the column.
66280 ** The first OP_Column against a pseudo-table after the value of the content
66281 ** register has changed should have this bit set.
66282 **
66283 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
66284 ** the result is guaranteed to only be used as the argument of a length()
66285 ** or typeof() function, respectively.  The loading of large blobs can be
66286 ** skipped for length() and all content loading can be skipped for typeof().
66287 */
66288 case OP_Column: {
66289 #if 0  /* local variables moved into u.ao */
66290   u32 payloadSize;   /* Number of bytes in the record */
66291   i64 payloadSize64; /* Number of bytes in the record */
66292   int p1;            /* P1 value of the opcode */
66293   int p2;            /* column number to retrieve */
66294   VdbeCursor *pC;    /* The VDBE cursor */
66295   char *zRec;        /* Pointer to complete record-data */
66296   BtCursor *pCrsr;   /* The BTree cursor */
66297   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
66298   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
66299   int nField;        /* number of fields in the record */
66300   int len;           /* The length of the serialized data for the column */
66301   int i;             /* Loop counter */
66302   char *zData;       /* Part of the record being decoded */
66303   Mem *pDest;        /* Where to write the extracted value */
66304   Mem sMem;          /* For storing the record being decoded */
66305   u8 *zIdx;          /* Index into header */
66306   u8 *zEndHdr;       /* Pointer to first byte after the header */
66307   u32 offset;        /* Offset into the data */
66308   u32 szField;       /* Number of bytes in the content of a field */
66309   int szHdr;         /* Size of the header size field at start of record */
66310   int avail;         /* Number of bytes of available data */
66311   u32 t;             /* A type code from the record header */
66312   Mem *pReg;         /* PseudoTable input register */
66313 #endif /* local variables moved into u.ao */
66314
66315
66316   u.ao.p1 = pOp->p1;
66317   u.ao.p2 = pOp->p2;
66318   u.ao.pC = 0;
66319   memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
66320   assert( u.ao.p1<p->nCursor );
66321   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66322   u.ao.pDest = &aMem[pOp->p3];
66323   memAboutToChange(p, u.ao.pDest);
66324   u.ao.zRec = 0;
66325
66326   /* This block sets the variable u.ao.payloadSize to be the total number of
66327   ** bytes in the record.
66328   **
66329   ** u.ao.zRec is set to be the complete text of the record if it is available.
66330   ** The complete record text is always available for pseudo-tables
66331   ** If the record is stored in a cursor, the complete record text
66332   ** might be available in the  u.ao.pC->aRow cache.  Or it might not be.
66333   ** If the data is unavailable,  u.ao.zRec is set to NULL.
66334   **
66335   ** We also compute the number of columns in the record.  For cursors,
66336   ** the number of columns is stored in the VdbeCursor.nField element.
66337   */
66338   u.ao.pC = p->apCsr[u.ao.p1];
66339   assert( u.ao.pC!=0 );
66340 #ifndef SQLITE_OMIT_VIRTUALTABLE
66341   assert( u.ao.pC->pVtabCursor==0 );
66342 #endif
66343   u.ao.pCrsr = u.ao.pC->pCursor;
66344   if( u.ao.pCrsr!=0 ){
66345     /* The record is stored in a B-Tree */
66346     rc = sqlite3VdbeCursorMoveto(u.ao.pC);
66347     if( rc ) goto abort_due_to_error;
66348     if( u.ao.pC->nullRow ){
66349       u.ao.payloadSize = 0;
66350     }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
66351       u.ao.payloadSize = u.ao.pC->payloadSize;
66352       u.ao.zRec = (char*)u.ao.pC->aRow;
66353     }else if( u.ao.pC->isIndex ){
66354       assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
66355       VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
66356       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
66357       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
66358       ** payload size, so it is impossible for u.ao.payloadSize64 to be
66359       ** larger than 32 bits. */
66360       assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
66361       u.ao.payloadSize = (u32)u.ao.payloadSize64;
66362     }else{
66363       assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
66364       VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
66365       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
66366     }
66367   }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
66368     u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
66369     if( u.ao.pC->multiPseudo ){
66370       sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
66371       Deephemeralize(u.ao.pDest);
66372       goto op_column_out;
66373     }
66374     assert( u.ao.pReg->flags & MEM_Blob );
66375     assert( memIsValid(u.ao.pReg) );
66376     u.ao.payloadSize = u.ao.pReg->n;
66377     u.ao.zRec = u.ao.pReg->z;
66378     u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
66379     assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
66380   }else{
66381     /* Consider the row to be NULL */
66382     u.ao.payloadSize = 0;
66383   }
66384
66385   /* If u.ao.payloadSize is 0, then just store a NULL.  This can happen because of
66386   ** nullRow or because of a corrupt database. */
66387   if( u.ao.payloadSize==0 ){
66388     MemSetTypeFlag(u.ao.pDest, MEM_Null);
66389     goto op_column_out;
66390   }
66391   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
66392   if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
66393     goto too_big;
66394   }
66395
66396   u.ao.nField = u.ao.pC->nField;
66397   assert( u.ao.p2<u.ao.nField );
66398
66399   /* Read and parse the table header.  Store the results of the parse
66400   ** into the record header cache fields of the cursor.
66401   */
66402   u.ao.aType = u.ao.pC->aType;
66403   if( u.ao.pC->cacheStatus==p->cacheCtr ){
66404     u.ao.aOffset = u.ao.pC->aOffset;
66405   }else{
66406     assert(u.ao.aType);
66407     u.ao.avail = 0;
66408     u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
66409     u.ao.pC->payloadSize = u.ao.payloadSize;
66410     u.ao.pC->cacheStatus = p->cacheCtr;
66411
66412     /* Figure out how many bytes are in the header */
66413     if( u.ao.zRec ){
66414       u.ao.zData = u.ao.zRec;
66415     }else{
66416       if( u.ao.pC->isIndex ){
66417         u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
66418       }else{
66419         u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
66420       }
66421       /* If KeyFetch()/DataFetch() managed to get the entire payload,
66422       ** save the payload in the u.ao.pC->aRow cache.  That will save us from
66423       ** having to make additional calls to fetch the content portion of
66424       ** the record.
66425       */
66426       assert( u.ao.avail>=0 );
66427       if( u.ao.payloadSize <= (u32)u.ao.avail ){
66428         u.ao.zRec = u.ao.zData;
66429         u.ao.pC->aRow = (u8*)u.ao.zData;
66430       }else{
66431         u.ao.pC->aRow = 0;
66432       }
66433     }
66434     /* The following assert is true in all cases except when
66435     ** the database file has been corrupted externally.
66436     **    assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
66437     u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
66438
66439     /* Make sure a corrupt database has not given us an oversize header.
66440     ** Do this now to avoid an oversize memory allocation.
66441     **
66442     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
66443     ** types use so much data space that there can only be 4096 and 32 of
66444     ** them, respectively.  So the maximum header length results from a
66445     ** 3-byte type for each of the maximum of 32768 columns plus three
66446     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
66447     */
66448     if( u.ao.offset > 98307 ){
66449       rc = SQLITE_CORRUPT_BKPT;
66450       goto op_column_out;
66451     }
66452
66453     /* Compute in u.ao.len the number of bytes of data we need to read in order
66454     ** to get u.ao.nField type values.  u.ao.offset is an upper bound on this.  But
66455     ** u.ao.nField might be significantly less than the true number of columns
66456     ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
66457     ** We want to minimize u.ao.len in order to limit the size of the memory
66458     ** allocation, especially if a corrupt database file has caused u.ao.offset
66459     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
66460     ** still exceed Robson memory allocation limits on some configurations.
66461     ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
66462     ** will likely be much smaller since u.ao.nField will likely be less than
66463     ** 20 or so.  This insures that Robson memory allocation limits are
66464     ** not exceeded even for corrupt database files.
66465     */
66466     u.ao.len = u.ao.nField*5 + 3;
66467     if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
66468
66469     /* The KeyFetch() or DataFetch() above are fast and will get the entire
66470     ** record header in most cases.  But they will fail to get the complete
66471     ** record header if the record header does not fit on a single page
66472     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
66473     ** acquire the complete header text.
66474     */
66475     if( !u.ao.zRec && u.ao.avail<u.ao.len ){
66476       u.ao.sMem.flags = 0;
66477       u.ao.sMem.db = 0;
66478       rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
66479       if( rc!=SQLITE_OK ){
66480         goto op_column_out;
66481       }
66482       u.ao.zData = u.ao.sMem.z;
66483     }
66484     u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
66485     u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
66486
66487     /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
66488     ** arrays.  u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
66489     ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
66490     ** of the record to the start of the data for the u.ao.i-th column
66491     */
66492     for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
66493       if( u.ao.zIdx<u.ao.zEndHdr ){
66494         u.ao.aOffset[u.ao.i] = u.ao.offset;
66495         if( u.ao.zIdx[0]<0x80 ){
66496           u.ao.t = u.ao.zIdx[0];
66497           u.ao.zIdx++;
66498         }else{
66499           u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
66500         }
66501         u.ao.aType[u.ao.i] = u.ao.t;
66502         u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
66503         u.ao.offset += u.ao.szField;
66504         if( u.ao.offset<u.ao.szField ){  /* True if u.ao.offset overflows */
66505           u.ao.zIdx = &u.ao.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
66506           break;
66507         }
66508       }else{
66509         /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
66510         ** record than SetNumColumns indicated there are columns in the
66511         ** table. Set the u.ao.offset for any extra columns not present in
66512         ** the record to 0. This tells code below to store the default value
66513         ** for the column instead of deserializing a value from the record.
66514         */
66515         u.ao.aOffset[u.ao.i] = 0;
66516       }
66517     }
66518     sqlite3VdbeMemRelease(&u.ao.sMem);
66519     u.ao.sMem.flags = MEM_Null;
66520
66521     /* If we have read more header data than was contained in the header,
66522     ** or if the end of the last field appears to be past the end of the
66523     ** record, or if the end of the last field appears to be before the end
66524     ** of the record (when all fields present), then we must be dealing
66525     ** with a corrupt database.
66526     */
66527     if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
66528          || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
66529       rc = SQLITE_CORRUPT_BKPT;
66530       goto op_column_out;
66531     }
66532   }
66533
66534   /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
66535   ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
66536   ** then there are not enough fields in the record to satisfy the
66537   ** request.  In this case, set the value NULL or to P4 if P4 is
66538   ** a pointer to a Mem object.
66539   */
66540   if( u.ao.aOffset[u.ao.p2] ){
66541     assert( rc==SQLITE_OK );
66542     if( u.ao.zRec ){
66543       /* This is the common case where the whole row fits on a single page */
66544       VdbeMemRelease(u.ao.pDest);
66545       sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
66546     }else{
66547       /* This branch happens only when the row overflows onto multiple pages */
66548       u.ao.t = u.ao.aType[u.ao.p2];
66549       if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
66550        && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
66551       ){
66552         /* Content is irrelevant for the typeof() function and for
66553         ** the length(X) function if X is a blob.  So we might as well use
66554         ** bogus content rather than reading content from disk.  NULL works
66555         ** for text and blob and whatever is in the u.ao.payloadSize64 variable
66556         ** will work for everything else. */
66557         u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
66558       }else{
66559         u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
66560         sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
66561         rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len,  u.ao.pC->isIndex,
66562                                      &u.ao.sMem);
66563         if( rc!=SQLITE_OK ){
66564           goto op_column_out;
66565         }
66566         u.ao.zData = u.ao.sMem.z;
66567       }
66568       sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
66569     }
66570     u.ao.pDest->enc = encoding;
66571   }else{
66572     if( pOp->p4type==P4_MEM ){
66573       sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
66574     }else{
66575       MemSetTypeFlag(u.ao.pDest, MEM_Null);
66576     }
66577   }
66578
66579   /* If we dynamically allocated space to hold the data (in the
66580   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
66581   ** dynamically allocated space over to the u.ao.pDest structure.
66582   ** This prevents a memory copy.
66583   */
66584   if( u.ao.sMem.zMalloc ){
66585     assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
66586     assert( !(u.ao.pDest->flags & MEM_Dyn) );
66587     assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
66588     u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
66589     u.ao.pDest->flags |= MEM_Term;
66590     u.ao.pDest->z = u.ao.sMem.z;
66591     u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
66592   }
66593
66594   rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
66595
66596 op_column_out:
66597   UPDATE_MAX_BLOBSIZE(u.ao.pDest);
66598   REGISTER_TRACE(pOp->p3, u.ao.pDest);
66599   break;
66600 }
66601
66602 /* Opcode: Affinity P1 P2 * P4 *
66603 **
66604 ** Apply affinities to a range of P2 registers starting with P1.
66605 **
66606 ** P4 is a string that is P2 characters long. The nth character of the
66607 ** string indicates the column affinity that should be used for the nth
66608 ** memory cell in the range.
66609 */
66610 case OP_Affinity: {
66611 #if 0  /* local variables moved into u.ap */
66612   const char *zAffinity;   /* The affinity to be applied */
66613   char cAff;               /* A single character of affinity */
66614 #endif /* local variables moved into u.ap */
66615
66616   u.ap.zAffinity = pOp->p4.z;
66617   assert( u.ap.zAffinity!=0 );
66618   assert( u.ap.zAffinity[pOp->p2]==0 );
66619   pIn1 = &aMem[pOp->p1];
66620   while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
66621     assert( pIn1 <= &p->aMem[p->nMem] );
66622     assert( memIsValid(pIn1) );
66623     ExpandBlob(pIn1);
66624     applyAffinity(pIn1, u.ap.cAff, encoding);
66625     pIn1++;
66626   }
66627   break;
66628 }
66629
66630 /* Opcode: MakeRecord P1 P2 P3 P4 *
66631 **
66632 ** Convert P2 registers beginning with P1 into the [record format]
66633 ** use as a data record in a database table or as a key
66634 ** in an index.  The OP_Column opcode can decode the record later.
66635 **
66636 ** P4 may be a string that is P2 characters long.  The nth character of the
66637 ** string indicates the column affinity that should be used for the nth
66638 ** field of the index key.
66639 **
66640 ** The mapping from character to affinity is given by the SQLITE_AFF_
66641 ** macros defined in sqliteInt.h.
66642 **
66643 ** If P4 is NULL then all index fields have the affinity NONE.
66644 */
66645 case OP_MakeRecord: {
66646 #if 0  /* local variables moved into u.aq */
66647   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
66648   Mem *pRec;             /* The new record */
66649   u64 nData;             /* Number of bytes of data space */
66650   int nHdr;              /* Number of bytes of header space */
66651   i64 nByte;             /* Data space required for this record */
66652   int nZero;             /* Number of zero bytes at the end of the record */
66653   int nVarint;           /* Number of bytes in a varint */
66654   u32 serial_type;       /* Type field */
66655   Mem *pData0;           /* First field to be combined into the record */
66656   Mem *pLast;            /* Last field of the record */
66657   int nField;            /* Number of fields in the record */
66658   char *zAffinity;       /* The affinity string for the record */
66659   int file_format;       /* File format to use for encoding */
66660   int i;                 /* Space used in zNewRecord[] */
66661   int len;               /* Length of a field */
66662 #endif /* local variables moved into u.aq */
66663
66664   /* Assuming the record contains N fields, the record format looks
66665   ** like this:
66666   **
66667   ** ------------------------------------------------------------------------
66668   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
66669   ** ------------------------------------------------------------------------
66670   **
66671   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
66672   ** and so froth.
66673   **
66674   ** Each type field is a varint representing the serial type of the
66675   ** corresponding data element (see sqlite3VdbeSerialType()). The
66676   ** hdr-size field is also a varint which is the offset from the beginning
66677   ** of the record to data0.
66678   */
66679   u.aq.nData = 0;         /* Number of bytes of data space */
66680   u.aq.nHdr = 0;          /* Number of bytes of header space */
66681   u.aq.nZero = 0;         /* Number of zero bytes at the end of the record */
66682   u.aq.nField = pOp->p1;
66683   u.aq.zAffinity = pOp->p4.z;
66684   assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=p->nMem+1 );
66685   u.aq.pData0 = &aMem[u.aq.nField];
66686   u.aq.nField = pOp->p2;
66687   u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
66688   u.aq.file_format = p->minWriteFileFormat;
66689
66690   /* Identify the output register */
66691   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
66692   pOut = &aMem[pOp->p3];
66693   memAboutToChange(p, pOut);
66694
66695   /* Loop through the elements that will make up the record to figure
66696   ** out how much space is required for the new record.
66697   */
66698   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
66699     assert( memIsValid(u.aq.pRec) );
66700     if( u.aq.zAffinity ){
66701       applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
66702     }
66703     if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
66704       sqlite3VdbeMemExpandBlob(u.aq.pRec);
66705     }
66706     u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
66707     u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
66708     u.aq.nData += u.aq.len;
66709     u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
66710     if( u.aq.pRec->flags & MEM_Zero ){
66711       /* Only pure zero-filled BLOBs can be input to this Opcode.
66712       ** We do not allow blobs with a prefix and a zero-filled tail. */
66713       u.aq.nZero += u.aq.pRec->u.nZero;
66714     }else if( u.aq.len ){
66715       u.aq.nZero = 0;
66716     }
66717   }
66718
66719   /* Add the initial header varint and total the size */
66720   u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
66721   if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
66722     u.aq.nHdr++;
66723   }
66724   u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
66725   if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66726     goto too_big;
66727   }
66728
66729   /* Make sure the output register has a buffer large enough to store
66730   ** the new record. The output register (pOp->p3) is not allowed to
66731   ** be one of the input registers (because the following call to
66732   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
66733   */
66734   if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
66735     goto no_mem;
66736   }
66737   u.aq.zNewRecord = (u8 *)pOut->z;
66738
66739   /* Write the record */
66740   u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
66741   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
66742     u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
66743     u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type);      /* serial type */
66744   }
66745   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){  /* serial data */
66746     u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
66747   }
66748   assert( u.aq.i==u.aq.nByte );
66749
66750   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66751   pOut->n = (int)u.aq.nByte;
66752   pOut->flags = MEM_Blob | MEM_Dyn;
66753   pOut->xDel = 0;
66754   if( u.aq.nZero ){
66755     pOut->u.nZero = u.aq.nZero;
66756     pOut->flags |= MEM_Zero;
66757   }
66758   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
66759   REGISTER_TRACE(pOp->p3, pOut);
66760   UPDATE_MAX_BLOBSIZE(pOut);
66761   break;
66762 }
66763
66764 /* Opcode: Count P1 P2 * * *
66765 **
66766 ** Store the number of entries (an integer value) in the table or index 
66767 ** opened by cursor P1 in register P2
66768 */
66769 #ifndef SQLITE_OMIT_BTREECOUNT
66770 case OP_Count: {         /* out2-prerelease */
66771 #if 0  /* local variables moved into u.ar */
66772   i64 nEntry;
66773   BtCursor *pCrsr;
66774 #endif /* local variables moved into u.ar */
66775
66776   u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
66777   if( ALWAYS(u.ar.pCrsr) ){
66778     rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
66779   }else{
66780     u.ar.nEntry = 0;
66781   }
66782   pOut->u.i = u.ar.nEntry;
66783   break;
66784 }
66785 #endif
66786
66787 /* Opcode: Savepoint P1 * * P4 *
66788 **
66789 ** Open, release or rollback the savepoint named by parameter P4, depending
66790 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
66791 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
66792 */
66793 case OP_Savepoint: {
66794 #if 0  /* local variables moved into u.as */
66795   int p1;                         /* Value of P1 operand */
66796   char *zName;                    /* Name of savepoint */
66797   int nName;
66798   Savepoint *pNew;
66799   Savepoint *pSavepoint;
66800   Savepoint *pTmp;
66801   int iSavepoint;
66802   int ii;
66803 #endif /* local variables moved into u.as */
66804
66805   u.as.p1 = pOp->p1;
66806   u.as.zName = pOp->p4.z;
66807
66808   /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
66809   ** transaction, then there cannot be any savepoints.
66810   */
66811   assert( db->pSavepoint==0 || db->autoCommit==0 );
66812   assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
66813   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
66814   assert( checkSavepointCount(db) );
66815
66816   if( u.as.p1==SAVEPOINT_BEGIN ){
66817     if( db->writeVdbeCnt>0 ){
66818       /* A new savepoint cannot be created if there are active write
66819       ** statements (i.e. open read/write incremental blob handles).
66820       */
66821       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
66822         "SQL statements in progress");
66823       rc = SQLITE_BUSY;
66824     }else{
66825       u.as.nName = sqlite3Strlen30(u.as.zName);
66826
66827 #ifndef SQLITE_OMIT_VIRTUALTABLE
66828       /* This call is Ok even if this savepoint is actually a transaction
66829       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
66830       ** If this is a transaction savepoint being opened, it is guaranteed
66831       ** that the db->aVTrans[] array is empty.  */
66832       assert( db->autoCommit==0 || db->nVTrans==0 );
66833       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
66834                                 db->nStatement+db->nSavepoint);
66835       if( rc!=SQLITE_OK ) goto abort_due_to_error;
66836 #endif
66837
66838       /* Create a new savepoint structure. */
66839       u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
66840       if( u.as.pNew ){
66841         u.as.pNew->zName = (char *)&u.as.pNew[1];
66842         memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
66843
66844         /* If there is no open transaction, then mark this as a special
66845         ** "transaction savepoint". */
66846         if( db->autoCommit ){
66847           db->autoCommit = 0;
66848           db->isTransactionSavepoint = 1;
66849         }else{
66850           db->nSavepoint++;
66851         }
66852
66853         /* Link the new savepoint into the database handle's list. */
66854         u.as.pNew->pNext = db->pSavepoint;
66855         db->pSavepoint = u.as.pNew;
66856         u.as.pNew->nDeferredCons = db->nDeferredCons;
66857       }
66858     }
66859   }else{
66860     u.as.iSavepoint = 0;
66861
66862     /* Find the named savepoint. If there is no such savepoint, then an
66863     ** an error is returned to the user.  */
66864     for(
66865       u.as.pSavepoint = db->pSavepoint;
66866       u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
66867       u.as.pSavepoint = u.as.pSavepoint->pNext
66868     ){
66869       u.as.iSavepoint++;
66870     }
66871     if( !u.as.pSavepoint ){
66872       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
66873       rc = SQLITE_ERROR;
66874     }else if( db->writeVdbeCnt>0 && u.as.p1==SAVEPOINT_RELEASE ){
66875       /* It is not possible to release (commit) a savepoint if there are
66876       ** active write statements.
66877       */
66878       sqlite3SetString(&p->zErrMsg, db,
66879         "cannot release savepoint - SQL statements in progress"
66880       );
66881       rc = SQLITE_BUSY;
66882     }else{
66883
66884       /* Determine whether or not this is a transaction savepoint. If so,
66885       ** and this is a RELEASE command, then the current transaction
66886       ** is committed.
66887       */
66888       int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
66889       if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
66890         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
66891           goto vdbe_return;
66892         }
66893         db->autoCommit = 1;
66894         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
66895           p->pc = pc;
66896           db->autoCommit = 0;
66897           p->rc = rc = SQLITE_BUSY;
66898           goto vdbe_return;
66899         }
66900         db->isTransactionSavepoint = 0;
66901         rc = p->rc;
66902       }else{
66903         u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
66904         if( u.as.p1==SAVEPOINT_ROLLBACK ){
66905           for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
66906             sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
66907           }
66908         }
66909         for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
66910           rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
66911           if( rc!=SQLITE_OK ){
66912             goto abort_due_to_error;
66913           }
66914         }
66915         if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
66916           sqlite3ExpirePreparedStatements(db);
66917           sqlite3ResetAllSchemasOfConnection(db);
66918           db->flags = (db->flags | SQLITE_InternChanges);
66919         }
66920       }
66921
66922       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
66923       ** savepoints nested inside of the savepoint being operated on. */
66924       while( db->pSavepoint!=u.as.pSavepoint ){
66925         u.as.pTmp = db->pSavepoint;
66926         db->pSavepoint = u.as.pTmp->pNext;
66927         sqlite3DbFree(db, u.as.pTmp);
66928         db->nSavepoint--;
66929       }
66930
66931       /* If it is a RELEASE, then destroy the savepoint being operated on
66932       ** too. If it is a ROLLBACK TO, then set the number of deferred
66933       ** constraint violations present in the database to the value stored
66934       ** when the savepoint was created.  */
66935       if( u.as.p1==SAVEPOINT_RELEASE ){
66936         assert( u.as.pSavepoint==db->pSavepoint );
66937         db->pSavepoint = u.as.pSavepoint->pNext;
66938         sqlite3DbFree(db, u.as.pSavepoint);
66939         if( !isTransaction ){
66940           db->nSavepoint--;
66941         }
66942       }else{
66943         db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
66944       }
66945
66946       if( !isTransaction ){
66947         rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
66948         if( rc!=SQLITE_OK ) goto abort_due_to_error;
66949       }
66950     }
66951   }
66952
66953   break;
66954 }
66955
66956 /* Opcode: AutoCommit P1 P2 * * *
66957 **
66958 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
66959 ** back any currently active btree transactions. If there are any active
66960 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
66961 ** there are active writing VMs or active VMs that use shared cache.
66962 **
66963 ** This instruction causes the VM to halt.
66964 */
66965 case OP_AutoCommit: {
66966 #if 0  /* local variables moved into u.at */
66967   int desiredAutoCommit;
66968   int iRollback;
66969   int turnOnAC;
66970 #endif /* local variables moved into u.at */
66971
66972   u.at.desiredAutoCommit = pOp->p1;
66973   u.at.iRollback = pOp->p2;
66974   u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
66975   assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
66976   assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
66977   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
66978
66979 #if 0
66980   if( u.at.turnOnAC && u.at.iRollback && db->activeVdbeCnt>1 ){
66981     /* If this instruction implements a ROLLBACK and other VMs are
66982     ** still running, and a transaction is active, return an error indicating
66983     ** that the other VMs must complete first.
66984     */
66985     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
66986         "SQL statements in progress");
66987     rc = SQLITE_BUSY;
66988   }else
66989 #endif
66990   if( u.at.turnOnAC && !u.at.iRollback && db->writeVdbeCnt>0 ){
66991     /* If this instruction implements a COMMIT and other VMs are writing
66992     ** return an error indicating that the other VMs must complete first.
66993     */
66994     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
66995         "SQL statements in progress");
66996     rc = SQLITE_BUSY;
66997   }else if( u.at.desiredAutoCommit!=db->autoCommit ){
66998     if( u.at.iRollback ){
66999       assert( u.at.desiredAutoCommit==1 );
67000       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
67001       db->autoCommit = 1;
67002     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
67003       goto vdbe_return;
67004     }else{
67005       db->autoCommit = (u8)u.at.desiredAutoCommit;
67006       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
67007         p->pc = pc;
67008         db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
67009         p->rc = rc = SQLITE_BUSY;
67010         goto vdbe_return;
67011       }
67012     }
67013     assert( db->nStatement==0 );
67014     sqlite3CloseSavepoints(db);
67015     if( p->rc==SQLITE_OK ){
67016       rc = SQLITE_DONE;
67017     }else{
67018       rc = SQLITE_ERROR;
67019     }
67020     goto vdbe_return;
67021   }else{
67022     sqlite3SetString(&p->zErrMsg, db,
67023         (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
67024         (u.at.iRollback)?"cannot rollback - no transaction is active":
67025                    "cannot commit - no transaction is active"));
67026
67027     rc = SQLITE_ERROR;
67028   }
67029   break;
67030 }
67031
67032 /* Opcode: Transaction P1 P2 * * *
67033 **
67034 ** Begin a transaction.  The transaction ends when a Commit or Rollback
67035 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
67036 ** transaction might also be rolled back if an error is encountered.
67037 **
67038 ** P1 is the index of the database file on which the transaction is
67039 ** started.  Index 0 is the main database file and index 1 is the
67040 ** file used for temporary tables.  Indices of 2 or more are used for
67041 ** attached databases.
67042 **
67043 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
67044 ** obtained on the database file when a write-transaction is started.  No
67045 ** other process can start another write transaction while this transaction is
67046 ** underway.  Starting a write transaction also creates a rollback journal. A
67047 ** write transaction must be started before any changes can be made to the
67048 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
67049 ** on the file.
67050 **
67051 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
67052 ** true (this flag is set if the Vdbe may modify more than one row and may
67053 ** throw an ABORT exception), a statement transaction may also be opened.
67054 ** More specifically, a statement transaction is opened iff the database
67055 ** connection is currently not in autocommit mode, or if there are other
67056 ** active statements. A statement transaction allows the changes made by this
67057 ** VDBE to be rolled back after an error without having to roll back the
67058 ** entire transaction. If no error is encountered, the statement transaction
67059 ** will automatically commit when the VDBE halts.
67060 **
67061 ** If P2 is zero, then a read-lock is obtained on the database file.
67062 */
67063 case OP_Transaction: {
67064 #if 0  /* local variables moved into u.au */
67065   Btree *pBt;
67066 #endif /* local variables moved into u.au */
67067
67068   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67069   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67070   u.au.pBt = db->aDb[pOp->p1].pBt;
67071
67072   if( u.au.pBt ){
67073     rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
67074     if( rc==SQLITE_BUSY ){
67075       p->pc = pc;
67076       p->rc = rc = SQLITE_BUSY;
67077       goto vdbe_return;
67078     }
67079     if( rc!=SQLITE_OK ){
67080       goto abort_due_to_error;
67081     }
67082
67083     if( pOp->p2 && p->usesStmtJournal
67084      && (db->autoCommit==0 || db->activeVdbeCnt>1)
67085     ){
67086       assert( sqlite3BtreeIsInTrans(u.au.pBt) );
67087       if( p->iStatement==0 ){
67088         assert( db->nStatement>=0 && db->nSavepoint>=0 );
67089         db->nStatement++;
67090         p->iStatement = db->nSavepoint + db->nStatement;
67091       }
67092
67093       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
67094       if( rc==SQLITE_OK ){
67095         rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
67096       }
67097
67098       /* Store the current value of the database handles deferred constraint
67099       ** counter. If the statement transaction needs to be rolled back,
67100       ** the value of this counter needs to be restored too.  */
67101       p->nStmtDefCons = db->nDeferredCons;
67102     }
67103   }
67104   break;
67105 }
67106
67107 /* Opcode: ReadCookie P1 P2 P3 * *
67108 **
67109 ** Read cookie number P3 from database P1 and write it into register P2.
67110 ** P3==1 is the schema version.  P3==2 is the database format.
67111 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
67112 ** the main database file and P1==1 is the database file used to store
67113 ** temporary tables.
67114 **
67115 ** There must be a read-lock on the database (either a transaction
67116 ** must be started or there must be an open cursor) before
67117 ** executing this instruction.
67118 */
67119 case OP_ReadCookie: {               /* out2-prerelease */
67120 #if 0  /* local variables moved into u.av */
67121   int iMeta;
67122   int iDb;
67123   int iCookie;
67124 #endif /* local variables moved into u.av */
67125
67126   u.av.iDb = pOp->p1;
67127   u.av.iCookie = pOp->p3;
67128   assert( pOp->p3<SQLITE_N_BTREE_META );
67129   assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
67130   assert( db->aDb[u.av.iDb].pBt!=0 );
67131   assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
67132
67133   sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
67134   pOut->u.i = u.av.iMeta;
67135   break;
67136 }
67137
67138 /* Opcode: SetCookie P1 P2 P3 * *
67139 **
67140 ** Write the content of register P3 (interpreted as an integer)
67141 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
67142 ** P2==2 is the database format. P2==3 is the recommended pager cache 
67143 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
67144 ** database file used to store temporary tables.
67145 **
67146 ** A transaction must be started before executing this opcode.
67147 */
67148 case OP_SetCookie: {       /* in3 */
67149 #if 0  /* local variables moved into u.aw */
67150   Db *pDb;
67151 #endif /* local variables moved into u.aw */
67152   assert( pOp->p2<SQLITE_N_BTREE_META );
67153   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67154   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67155   u.aw.pDb = &db->aDb[pOp->p1];
67156   assert( u.aw.pDb->pBt!=0 );
67157   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
67158   pIn3 = &aMem[pOp->p3];
67159   sqlite3VdbeMemIntegerify(pIn3);
67160   /* See note about index shifting on OP_ReadCookie */
67161   rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
67162   if( pOp->p2==BTREE_SCHEMA_VERSION ){
67163     /* When the schema cookie changes, record the new cookie internally */
67164     u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
67165     db->flags |= SQLITE_InternChanges;
67166   }else if( pOp->p2==BTREE_FILE_FORMAT ){
67167     /* Record changes in the file format */
67168     u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
67169   }
67170   if( pOp->p1==1 ){
67171     /* Invalidate all prepared statements whenever the TEMP database
67172     ** schema is changed.  Ticket #1644 */
67173     sqlite3ExpirePreparedStatements(db);
67174     p->expired = 0;
67175   }
67176   break;
67177 }
67178
67179 /* Opcode: VerifyCookie P1 P2 P3 * *
67180 **
67181 ** Check the value of global database parameter number 0 (the
67182 ** schema version) and make sure it is equal to P2 and that the
67183 ** generation counter on the local schema parse equals P3.
67184 **
67185 ** P1 is the database number which is 0 for the main database file
67186 ** and 1 for the file holding temporary tables and some higher number
67187 ** for auxiliary databases.
67188 **
67189 ** The cookie changes its value whenever the database schema changes.
67190 ** This operation is used to detect when that the cookie has changed
67191 ** and that the current process needs to reread the schema.
67192 **
67193 ** Either a transaction needs to have been started or an OP_Open needs
67194 ** to be executed (to establish a read lock) before this opcode is
67195 ** invoked.
67196 */
67197 case OP_VerifyCookie: {
67198 #if 0  /* local variables moved into u.ax */
67199   int iMeta;
67200   int iGen;
67201   Btree *pBt;
67202 #endif /* local variables moved into u.ax */
67203
67204   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67205   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67206   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
67207   u.ax.pBt = db->aDb[pOp->p1].pBt;
67208   if( u.ax.pBt ){
67209     sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
67210     u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
67211   }else{
67212     u.ax.iGen = u.ax.iMeta = 0;
67213   }
67214   if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
67215     sqlite3DbFree(db, p->zErrMsg);
67216     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
67217     /* If the schema-cookie from the database file matches the cookie
67218     ** stored with the in-memory representation of the schema, do
67219     ** not reload the schema from the database file.
67220     **
67221     ** If virtual-tables are in use, this is not just an optimization.
67222     ** Often, v-tables store their data in other SQLite tables, which
67223     ** are queried from within xNext() and other v-table methods using
67224     ** prepared queries. If such a query is out-of-date, we do not want to
67225     ** discard the database schema, as the user code implementing the
67226     ** v-table would have to be ready for the sqlite3_vtab structure itself
67227     ** to be invalidated whenever sqlite3_step() is called from within
67228     ** a v-table method.
67229     */
67230     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
67231       sqlite3ResetOneSchema(db, pOp->p1);
67232     }
67233
67234     p->expired = 1;
67235     rc = SQLITE_SCHEMA;
67236   }
67237   break;
67238 }
67239
67240 /* Opcode: OpenRead P1 P2 P3 P4 P5
67241 **
67242 ** Open a read-only cursor for the database table whose root page is
67243 ** P2 in a database file.  The database file is determined by P3. 
67244 ** P3==0 means the main database, P3==1 means the database used for 
67245 ** temporary tables, and P3>1 means used the corresponding attached
67246 ** database.  Give the new cursor an identifier of P1.  The P1
67247 ** values need not be contiguous but all P1 values should be small integers.
67248 ** It is an error for P1 to be negative.
67249 **
67250 ** If P5!=0 then use the content of register P2 as the root page, not
67251 ** the value of P2 itself.
67252 **
67253 ** There will be a read lock on the database whenever there is an
67254 ** open cursor.  If the database was unlocked prior to this instruction
67255 ** then a read lock is acquired as part of this instruction.  A read
67256 ** lock allows other processes to read the database but prohibits
67257 ** any other process from modifying the database.  The read lock is
67258 ** released when all cursors are closed.  If this instruction attempts
67259 ** to get a read lock but fails, the script terminates with an
67260 ** SQLITE_BUSY error code.
67261 **
67262 ** The P4 value may be either an integer (P4_INT32) or a pointer to
67263 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
67264 ** structure, then said structure defines the content and collating 
67265 ** sequence of the index being opened. Otherwise, if P4 is an integer 
67266 ** value, it is set to the number of columns in the table.
67267 **
67268 ** See also OpenWrite.
67269 */
67270 /* Opcode: OpenWrite P1 P2 P3 P4 P5
67271 **
67272 ** Open a read/write cursor named P1 on the table or index whose root
67273 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
67274 ** root page.
67275 **
67276 ** The P4 value may be either an integer (P4_INT32) or a pointer to
67277 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
67278 ** structure, then said structure defines the content and collating 
67279 ** sequence of the index being opened. Otherwise, if P4 is an integer 
67280 ** value, it is set to the number of columns in the table, or to the
67281 ** largest index of any column of the table that is actually used.
67282 **
67283 ** This instruction works just like OpenRead except that it opens the cursor
67284 ** in read/write mode.  For a given table, there can be one or more read-only
67285 ** cursors or a single read/write cursor but not both.
67286 **
67287 ** See also OpenRead.
67288 */
67289 case OP_OpenRead:
67290 case OP_OpenWrite: {
67291 #if 0  /* local variables moved into u.ay */
67292   int nField;
67293   KeyInfo *pKeyInfo;
67294   int p2;
67295   int iDb;
67296   int wrFlag;
67297   Btree *pX;
67298   VdbeCursor *pCur;
67299   Db *pDb;
67300 #endif /* local variables moved into u.ay */
67301
67302   assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
67303   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
67304
67305   if( p->expired ){
67306     rc = SQLITE_ABORT;
67307     break;
67308   }
67309
67310   u.ay.nField = 0;
67311   u.ay.pKeyInfo = 0;
67312   u.ay.p2 = pOp->p2;
67313   u.ay.iDb = pOp->p3;
67314   assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
67315   assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
67316   u.ay.pDb = &db->aDb[u.ay.iDb];
67317   u.ay.pX = u.ay.pDb->pBt;
67318   assert( u.ay.pX!=0 );
67319   if( pOp->opcode==OP_OpenWrite ){
67320     u.ay.wrFlag = 1;
67321     assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
67322     if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
67323       p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
67324     }
67325   }else{
67326     u.ay.wrFlag = 0;
67327   }
67328   if( pOp->p5 & OPFLAG_P2ISREG ){
67329     assert( u.ay.p2>0 );
67330     assert( u.ay.p2<=p->nMem );
67331     pIn2 = &aMem[u.ay.p2];
67332     assert( memIsValid(pIn2) );
67333     assert( (pIn2->flags & MEM_Int)!=0 );
67334     sqlite3VdbeMemIntegerify(pIn2);
67335     u.ay.p2 = (int)pIn2->u.i;
67336     /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
67337     ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
67338     ** If there were a failure, the prepared statement would have halted
67339     ** before reaching this instruction. */
67340     if( NEVER(u.ay.p2<2) ) {
67341       rc = SQLITE_CORRUPT_BKPT;
67342       goto abort_due_to_error;
67343     }
67344   }
67345   if( pOp->p4type==P4_KEYINFO ){
67346     u.ay.pKeyInfo = pOp->p4.pKeyInfo;
67347     u.ay.pKeyInfo->enc = ENC(p->db);
67348     u.ay.nField = u.ay.pKeyInfo->nField+1;
67349   }else if( pOp->p4type==P4_INT32 ){
67350     u.ay.nField = pOp->p4.i;
67351   }
67352   assert( pOp->p1>=0 );
67353   u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
67354   if( u.ay.pCur==0 ) goto no_mem;
67355   u.ay.pCur->nullRow = 1;
67356   u.ay.pCur->isOrdered = 1;
67357   rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
67358   u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
67359   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
67360   sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
67361
67362   /* Since it performs no memory allocation or IO, the only value that
67363   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
67364   assert( rc==SQLITE_OK );
67365
67366   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
67367   ** SQLite used to check if the root-page flags were sane at this point
67368   ** and report database corruption if they were not, but this check has
67369   ** since moved into the btree layer.  */
67370   u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
67371   u.ay.pCur->isIndex = !u.ay.pCur->isTable;
67372   break;
67373 }
67374
67375 /* Opcode: OpenEphemeral P1 P2 * P4 P5
67376 **
67377 ** Open a new cursor P1 to a transient table.
67378 ** The cursor is always opened read/write even if 
67379 ** the main database is read-only.  The ephemeral
67380 ** table is deleted automatically when the cursor is closed.
67381 **
67382 ** P2 is the number of columns in the ephemeral table.
67383 ** The cursor points to a BTree table if P4==0 and to a BTree index
67384 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
67385 ** that defines the format of keys in the index.
67386 **
67387 ** This opcode was once called OpenTemp.  But that created
67388 ** confusion because the term "temp table", might refer either
67389 ** to a TEMP table at the SQL level, or to a table opened by
67390 ** this opcode.  Then this opcode was call OpenVirtual.  But
67391 ** that created confusion with the whole virtual-table idea.
67392 **
67393 ** The P5 parameter can be a mask of the BTREE_* flags defined
67394 ** in btree.h.  These flags control aspects of the operation of
67395 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
67396 ** added automatically.
67397 */
67398 /* Opcode: OpenAutoindex P1 P2 * P4 *
67399 **
67400 ** This opcode works the same as OP_OpenEphemeral.  It has a
67401 ** different name to distinguish its use.  Tables created using
67402 ** by this opcode will be used for automatically created transient
67403 ** indices in joins.
67404 */
67405 case OP_OpenAutoindex: 
67406 case OP_OpenEphemeral: {
67407 #if 0  /* local variables moved into u.az */
67408   VdbeCursor *pCx;
67409 #endif /* local variables moved into u.az */
67410   static const int vfsFlags =
67411       SQLITE_OPEN_READWRITE |
67412       SQLITE_OPEN_CREATE |
67413       SQLITE_OPEN_EXCLUSIVE |
67414       SQLITE_OPEN_DELETEONCLOSE |
67415       SQLITE_OPEN_TRANSIENT_DB;
67416
67417   assert( pOp->p1>=0 );
67418   u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
67419   if( u.az.pCx==0 ) goto no_mem;
67420   u.az.pCx->nullRow = 1;
67421   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
67422                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
67423   if( rc==SQLITE_OK ){
67424     rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
67425   }
67426   if( rc==SQLITE_OK ){
67427     /* If a transient index is required, create it by calling
67428     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
67429     ** opening it. If a transient table is required, just use the
67430     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
67431     */
67432     if( pOp->p4.pKeyInfo ){
67433       int pgno;
67434       assert( pOp->p4type==P4_KEYINFO );
67435       rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
67436       if( rc==SQLITE_OK ){
67437         assert( pgno==MASTER_ROOT+1 );
67438         rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
67439                                 (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
67440         u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
67441         u.az.pCx->pKeyInfo->enc = ENC(p->db);
67442       }
67443       u.az.pCx->isTable = 0;
67444     }else{
67445       rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
67446       u.az.pCx->isTable = 1;
67447     }
67448   }
67449   u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
67450   u.az.pCx->isIndex = !u.az.pCx->isTable;
67451   break;
67452 }
67453
67454 /* Opcode: SorterOpen P1 P2 * P4 *
67455 **
67456 ** This opcode works like OP_OpenEphemeral except that it opens
67457 ** a transient index that is specifically designed to sort large
67458 ** tables using an external merge-sort algorithm.
67459 */
67460 case OP_SorterOpen: {
67461 #if 0  /* local variables moved into u.ba */
67462   VdbeCursor *pCx;
67463 #endif /* local variables moved into u.ba */
67464
67465   u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
67466   if( u.ba.pCx==0 ) goto no_mem;
67467   u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
67468   u.ba.pCx->pKeyInfo->enc = ENC(p->db);
67469   u.ba.pCx->isSorter = 1;
67470   rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
67471   break;
67472 }
67473
67474 /* Opcode: OpenPseudo P1 P2 P3 * P5
67475 **
67476 ** Open a new cursor that points to a fake table that contains a single
67477 ** row of data.  The content of that one row in the content of memory
67478 ** register P2 when P5==0.  In other words, cursor P1 becomes an alias for the 
67479 ** MEM_Blob content contained in register P2.  When P5==1, then the
67480 ** row is represented by P3 consecutive registers beginning with P2.
67481 **
67482 ** A pseudo-table created by this opcode is used to hold a single
67483 ** row output from the sorter so that the row can be decomposed into
67484 ** individual columns using the OP_Column opcode.  The OP_Column opcode
67485 ** is the only cursor opcode that works with a pseudo-table.
67486 **
67487 ** P3 is the number of fields in the records that will be stored by
67488 ** the pseudo-table.
67489 */
67490 case OP_OpenPseudo: {
67491 #if 0  /* local variables moved into u.bb */
67492   VdbeCursor *pCx;
67493 #endif /* local variables moved into u.bb */
67494
67495   assert( pOp->p1>=0 );
67496   u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
67497   if( u.bb.pCx==0 ) goto no_mem;
67498   u.bb.pCx->nullRow = 1;
67499   u.bb.pCx->pseudoTableReg = pOp->p2;
67500   u.bb.pCx->isTable = 1;
67501   u.bb.pCx->isIndex = 0;
67502   u.bb.pCx->multiPseudo = pOp->p5;
67503   break;
67504 }
67505
67506 /* Opcode: Close P1 * * * *
67507 **
67508 ** Close a cursor previously opened as P1.  If P1 is not
67509 ** currently open, this instruction is a no-op.
67510 */
67511 case OP_Close: {
67512   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67513   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
67514   p->apCsr[pOp->p1] = 0;
67515   break;
67516 }
67517
67518 /* Opcode: SeekGe P1 P2 P3 P4 *
67519 **
67520 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
67521 ** use the value in register P3 as the key.  If cursor P1 refers 
67522 ** to an SQL index, then P3 is the first in an array of P4 registers 
67523 ** that are used as an unpacked index key. 
67524 **
67525 ** Reposition cursor P1 so that  it points to the smallest entry that 
67526 ** is greater than or equal to the key value. If there are no records 
67527 ** greater than or equal to the key and P2 is not zero, then jump to P2.
67528 **
67529 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
67530 */
67531 /* Opcode: SeekGt P1 P2 P3 P4 *
67532 **
67533 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
67534 ** use the value in register P3 as a key. If cursor P1 refers 
67535 ** to an SQL index, then P3 is the first in an array of P4 registers 
67536 ** that are used as an unpacked index key. 
67537 **
67538 ** Reposition cursor P1 so that  it points to the smallest entry that 
67539 ** is greater than the key value. If there are no records greater than 
67540 ** the key and P2 is not zero, then jump to P2.
67541 **
67542 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
67543 */
67544 /* Opcode: SeekLt P1 P2 P3 P4 * 
67545 **
67546 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
67547 ** use the value in register P3 as a key. If cursor P1 refers 
67548 ** to an SQL index, then P3 is the first in an array of P4 registers 
67549 ** that are used as an unpacked index key. 
67550 **
67551 ** Reposition cursor P1 so that  it points to the largest entry that 
67552 ** is less than the key value. If there are no records less than 
67553 ** the key and P2 is not zero, then jump to P2.
67554 **
67555 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
67556 */
67557 /* Opcode: SeekLe P1 P2 P3 P4 *
67558 **
67559 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
67560 ** use the value in register P3 as a key. If cursor P1 refers 
67561 ** to an SQL index, then P3 is the first in an array of P4 registers 
67562 ** that are used as an unpacked index key. 
67563 **
67564 ** Reposition cursor P1 so that it points to the largest entry that 
67565 ** is less than or equal to the key value. If there are no records 
67566 ** less than or equal to the key and P2 is not zero, then jump to P2.
67567 **
67568 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
67569 */
67570 case OP_SeekLt:         /* jump, in3 */
67571 case OP_SeekLe:         /* jump, in3 */
67572 case OP_SeekGe:         /* jump, in3 */
67573 case OP_SeekGt: {       /* jump, in3 */
67574 #if 0  /* local variables moved into u.bc */
67575   int res;
67576   int oc;
67577   VdbeCursor *pC;
67578   UnpackedRecord r;
67579   int nField;
67580   i64 iKey;      /* The rowid we are to seek to */
67581 #endif /* local variables moved into u.bc */
67582
67583   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67584   assert( pOp->p2!=0 );
67585   u.bc.pC = p->apCsr[pOp->p1];
67586   assert( u.bc.pC!=0 );
67587   assert( u.bc.pC->pseudoTableReg==0 );
67588   assert( OP_SeekLe == OP_SeekLt+1 );
67589   assert( OP_SeekGe == OP_SeekLt+2 );
67590   assert( OP_SeekGt == OP_SeekLt+3 );
67591   assert( u.bc.pC->isOrdered );
67592   if( ALWAYS(u.bc.pC->pCursor!=0) ){
67593     u.bc.oc = pOp->opcode;
67594     u.bc.pC->nullRow = 0;
67595     if( u.bc.pC->isTable ){
67596       /* The input value in P3 might be of any type: integer, real, string,
67597       ** blob, or NULL.  But it needs to be an integer before we can do
67598       ** the seek, so covert it. */
67599       pIn3 = &aMem[pOp->p3];
67600       applyNumericAffinity(pIn3);
67601       u.bc.iKey = sqlite3VdbeIntValue(pIn3);
67602       u.bc.pC->rowidIsValid = 0;
67603
67604       /* If the P3 value could not be converted into an integer without
67605       ** loss of information, then special processing is required... */
67606       if( (pIn3->flags & MEM_Int)==0 ){
67607         if( (pIn3->flags & MEM_Real)==0 ){
67608           /* If the P3 value cannot be converted into any kind of a number,
67609           ** then the seek is not possible, so jump to P2 */
67610           pc = pOp->p2 - 1;
67611           break;
67612         }
67613         /* If we reach this point, then the P3 value must be a floating
67614         ** point number. */
67615         assert( (pIn3->flags & MEM_Real)!=0 );
67616
67617         if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
67618           /* The P3 value is too large in magnitude to be expressed as an
67619           ** integer. */
67620           u.bc.res = 1;
67621           if( pIn3->r<0 ){
67622             if( u.bc.oc>=OP_SeekGe ){  assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
67623               rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
67624               if( rc!=SQLITE_OK ) goto abort_due_to_error;
67625             }
67626           }else{
67627             if( u.bc.oc<=OP_SeekLe ){  assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
67628               rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
67629               if( rc!=SQLITE_OK ) goto abort_due_to_error;
67630             }
67631           }
67632           if( u.bc.res ){
67633             pc = pOp->p2 - 1;
67634           }
67635           break;
67636         }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
67637           /* Use the ceiling() function to convert real->int */
67638           if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
67639         }else{
67640           /* Use the floor() function to convert real->int */
67641           assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
67642           if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
67643         }
67644       }
67645       rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
67646       if( rc!=SQLITE_OK ){
67647         goto abort_due_to_error;
67648       }
67649       if( u.bc.res==0 ){
67650         u.bc.pC->rowidIsValid = 1;
67651         u.bc.pC->lastRowid = u.bc.iKey;
67652       }
67653     }else{
67654       u.bc.nField = pOp->p4.i;
67655       assert( pOp->p4type==P4_INT32 );
67656       assert( u.bc.nField>0 );
67657       u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
67658       u.bc.r.nField = (u16)u.bc.nField;
67659
67660       /* The next line of code computes as follows, only faster:
67661       **   if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
67662       **     u.bc.r.flags = UNPACKED_INCRKEY;
67663       **   }else{
67664       **     u.bc.r.flags = 0;
67665       **   }
67666       */
67667       u.bc.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
67668       assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
67669       assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
67670       assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
67671       assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
67672
67673       u.bc.r.aMem = &aMem[pOp->p3];
67674 #ifdef SQLITE_DEBUG
67675       { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
67676 #endif
67677       ExpandBlob(u.bc.r.aMem);
67678       rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
67679       if( rc!=SQLITE_OK ){
67680         goto abort_due_to_error;
67681       }
67682       u.bc.pC->rowidIsValid = 0;
67683     }
67684     u.bc.pC->deferredMoveto = 0;
67685     u.bc.pC->cacheStatus = CACHE_STALE;
67686 #ifdef SQLITE_TEST
67687     sqlite3_search_count++;
67688 #endif
67689     if( u.bc.oc>=OP_SeekGe ){  assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
67690       if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
67691         rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
67692         if( rc!=SQLITE_OK ) goto abort_due_to_error;
67693         u.bc.pC->rowidIsValid = 0;
67694       }else{
67695         u.bc.res = 0;
67696       }
67697     }else{
67698       assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
67699       if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
67700         rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
67701         if( rc!=SQLITE_OK ) goto abort_due_to_error;
67702         u.bc.pC->rowidIsValid = 0;
67703       }else{
67704         /* u.bc.res might be negative because the table is empty.  Check to
67705         ** see if this is the case.
67706         */
67707         u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
67708       }
67709     }
67710     assert( pOp->p2>0 );
67711     if( u.bc.res ){
67712       pc = pOp->p2 - 1;
67713     }
67714   }else{
67715     /* This happens when attempting to open the sqlite3_master table
67716     ** for read access returns SQLITE_EMPTY. In this case always
67717     ** take the jump (since there are no records in the table).
67718     */
67719     pc = pOp->p2 - 1;
67720   }
67721   break;
67722 }
67723
67724 /* Opcode: Seek P1 P2 * * *
67725 **
67726 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
67727 ** for P1 to move so that it points to the rowid given by P2.
67728 **
67729 ** This is actually a deferred seek.  Nothing actually happens until
67730 ** the cursor is used to read a record.  That way, if no reads
67731 ** occur, no unnecessary I/O happens.
67732 */
67733 case OP_Seek: {    /* in2 */
67734 #if 0  /* local variables moved into u.bd */
67735   VdbeCursor *pC;
67736 #endif /* local variables moved into u.bd */
67737
67738   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67739   u.bd.pC = p->apCsr[pOp->p1];
67740   assert( u.bd.pC!=0 );
67741   if( ALWAYS(u.bd.pC->pCursor!=0) ){
67742     assert( u.bd.pC->isTable );
67743     u.bd.pC->nullRow = 0;
67744     pIn2 = &aMem[pOp->p2];
67745     u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
67746     u.bd.pC->rowidIsValid = 0;
67747     u.bd.pC->deferredMoveto = 1;
67748   }
67749   break;
67750 }
67751   
67752
67753 /* Opcode: Found P1 P2 P3 P4 *
67754 **
67755 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
67756 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
67757 ** record.
67758 **
67759 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
67760 ** is a prefix of any entry in P1 then a jump is made to P2 and
67761 ** P1 is left pointing at the matching entry.
67762 */
67763 /* Opcode: NotFound P1 P2 P3 P4 *
67764 **
67765 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
67766 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
67767 ** record.
67768 ** 
67769 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
67770 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
67771 ** does contain an entry whose prefix matches the P3/P4 record then control
67772 ** falls through to the next instruction and P1 is left pointing at the
67773 ** matching entry.
67774 **
67775 ** See also: Found, NotExists, IsUnique
67776 */
67777 case OP_NotFound:       /* jump, in3 */
67778 case OP_Found: {        /* jump, in3 */
67779 #if 0  /* local variables moved into u.be */
67780   int alreadyExists;
67781   VdbeCursor *pC;
67782   int res;
67783   char *pFree;
67784   UnpackedRecord *pIdxKey;
67785   UnpackedRecord r;
67786   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
67787 #endif /* local variables moved into u.be */
67788
67789 #ifdef SQLITE_TEST
67790   sqlite3_found_count++;
67791 #endif
67792
67793   u.be.alreadyExists = 0;
67794   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67795   assert( pOp->p4type==P4_INT32 );
67796   u.be.pC = p->apCsr[pOp->p1];
67797   assert( u.be.pC!=0 );
67798   pIn3 = &aMem[pOp->p3];
67799   if( ALWAYS(u.be.pC->pCursor!=0) ){
67800
67801     assert( u.be.pC->isTable==0 );
67802     if( pOp->p4.i>0 ){
67803       u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
67804       u.be.r.nField = (u16)pOp->p4.i;
67805       u.be.r.aMem = pIn3;
67806 #ifdef SQLITE_DEBUG
67807       { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
67808 #endif
67809       u.be.r.flags = UNPACKED_PREFIX_MATCH;
67810       u.be.pIdxKey = &u.be.r;
67811     }else{
67812       u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
67813           u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
67814       );
67815       if( u.be.pIdxKey==0 ) goto no_mem;
67816       assert( pIn3->flags & MEM_Blob );
67817       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
67818       sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
67819       u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
67820     }
67821     rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
67822     if( pOp->p4.i==0 ){
67823       sqlite3DbFree(db, u.be.pFree);
67824     }
67825     if( rc!=SQLITE_OK ){
67826       break;
67827     }
67828     u.be.alreadyExists = (u.be.res==0);
67829     u.be.pC->deferredMoveto = 0;
67830     u.be.pC->cacheStatus = CACHE_STALE;
67831   }
67832   if( pOp->opcode==OP_Found ){
67833     if( u.be.alreadyExists ) pc = pOp->p2 - 1;
67834   }else{
67835     if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
67836   }
67837   break;
67838 }
67839
67840 /* Opcode: IsUnique P1 P2 P3 P4 *
67841 **
67842 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
67843 ** no data and where the key are records generated by OP_MakeRecord with
67844 ** the list field being the integer ROWID of the entry that the index
67845 ** entry refers to.
67846 **
67847 ** The P3 register contains an integer record number. Call this record 
67848 ** number R. Register P4 is the first in a set of N contiguous registers
67849 ** that make up an unpacked index key that can be used with cursor P1.
67850 ** The value of N can be inferred from the cursor. N includes the rowid
67851 ** value appended to the end of the index record. This rowid value may
67852 ** or may not be the same as R.
67853 **
67854 ** If any of the N registers beginning with register P4 contains a NULL
67855 ** value, jump immediately to P2.
67856 **
67857 ** Otherwise, this instruction checks if cursor P1 contains an entry
67858 ** where the first (N-1) fields match but the rowid value at the end
67859 ** of the index entry is not R. If there is no such entry, control jumps
67860 ** to instruction P2. Otherwise, the rowid of the conflicting index
67861 ** entry is copied to register P3 and control falls through to the next
67862 ** instruction.
67863 **
67864 ** See also: NotFound, NotExists, Found
67865 */
67866 case OP_IsUnique: {        /* jump, in3 */
67867 #if 0  /* local variables moved into u.bf */
67868   u16 ii;
67869   VdbeCursor *pCx;
67870   BtCursor *pCrsr;
67871   u16 nField;
67872   Mem *aMx;
67873   UnpackedRecord r;                  /* B-Tree index search key */
67874   i64 R;                             /* Rowid stored in register P3 */
67875 #endif /* local variables moved into u.bf */
67876
67877   pIn3 = &aMem[pOp->p3];
67878   u.bf.aMx = &aMem[pOp->p4.i];
67879   /* Assert that the values of parameters P1 and P4 are in range. */
67880   assert( pOp->p4type==P4_INT32 );
67881   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
67882   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67883
67884   /* Find the index cursor. */
67885   u.bf.pCx = p->apCsr[pOp->p1];
67886   assert( u.bf.pCx->deferredMoveto==0 );
67887   u.bf.pCx->seekResult = 0;
67888   u.bf.pCx->cacheStatus = CACHE_STALE;
67889   u.bf.pCrsr = u.bf.pCx->pCursor;
67890
67891   /* If any of the values are NULL, take the jump. */
67892   u.bf.nField = u.bf.pCx->pKeyInfo->nField;
67893   for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
67894     if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
67895       pc = pOp->p2 - 1;
67896       u.bf.pCrsr = 0;
67897       break;
67898     }
67899   }
67900   assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
67901
67902   if( u.bf.pCrsr!=0 ){
67903     /* Populate the index search key. */
67904     u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
67905     u.bf.r.nField = u.bf.nField + 1;
67906     u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
67907     u.bf.r.aMem = u.bf.aMx;
67908 #ifdef SQLITE_DEBUG
67909     { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
67910 #endif
67911
67912     /* Extract the value of u.bf.R from register P3. */
67913     sqlite3VdbeMemIntegerify(pIn3);
67914     u.bf.R = pIn3->u.i;
67915
67916     /* Search the B-Tree index. If no conflicting record is found, jump
67917     ** to P2. Otherwise, copy the rowid of the conflicting record to
67918     ** register P3 and fall through to the next instruction.  */
67919     rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
67920     if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
67921       pc = pOp->p2 - 1;
67922     }else{
67923       pIn3->u.i = u.bf.r.rowid;
67924     }
67925   }
67926   break;
67927 }
67928
67929 /* Opcode: NotExists P1 P2 P3 * *
67930 **
67931 ** Use the content of register P3 as an integer key.  If a record 
67932 ** with that key does not exist in table of P1, then jump to P2. 
67933 ** If the record does exist, then fall through.  The cursor is left 
67934 ** pointing to the record if it exists.
67935 **
67936 ** The difference between this operation and NotFound is that this
67937 ** operation assumes the key is an integer and that P1 is a table whereas
67938 ** NotFound assumes key is a blob constructed from MakeRecord and
67939 ** P1 is an index.
67940 **
67941 ** See also: Found, NotFound, IsUnique
67942 */
67943 case OP_NotExists: {        /* jump, in3 */
67944 #if 0  /* local variables moved into u.bg */
67945   VdbeCursor *pC;
67946   BtCursor *pCrsr;
67947   int res;
67948   u64 iKey;
67949 #endif /* local variables moved into u.bg */
67950
67951   pIn3 = &aMem[pOp->p3];
67952   assert( pIn3->flags & MEM_Int );
67953   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67954   u.bg.pC = p->apCsr[pOp->p1];
67955   assert( u.bg.pC!=0 );
67956   assert( u.bg.pC->isTable );
67957   assert( u.bg.pC->pseudoTableReg==0 );
67958   u.bg.pCrsr = u.bg.pC->pCursor;
67959   if( ALWAYS(u.bg.pCrsr!=0) ){
67960     u.bg.res = 0;
67961     u.bg.iKey = pIn3->u.i;
67962     rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
67963     u.bg.pC->lastRowid = pIn3->u.i;
67964     u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
67965     u.bg.pC->nullRow = 0;
67966     u.bg.pC->cacheStatus = CACHE_STALE;
67967     u.bg.pC->deferredMoveto = 0;
67968     if( u.bg.res!=0 ){
67969       pc = pOp->p2 - 1;
67970       assert( u.bg.pC->rowidIsValid==0 );
67971     }
67972     u.bg.pC->seekResult = u.bg.res;
67973   }else{
67974     /* This happens when an attempt to open a read cursor on the
67975     ** sqlite_master table returns SQLITE_EMPTY.
67976     */
67977     pc = pOp->p2 - 1;
67978     assert( u.bg.pC->rowidIsValid==0 );
67979     u.bg.pC->seekResult = 0;
67980   }
67981   break;
67982 }
67983
67984 /* Opcode: Sequence P1 P2 * * *
67985 **
67986 ** Find the next available sequence number for cursor P1.
67987 ** Write the sequence number into register P2.
67988 ** The sequence number on the cursor is incremented after this
67989 ** instruction.  
67990 */
67991 case OP_Sequence: {           /* out2-prerelease */
67992   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67993   assert( p->apCsr[pOp->p1]!=0 );
67994   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
67995   break;
67996 }
67997
67998
67999 /* Opcode: NewRowid P1 P2 P3 * *
68000 **
68001 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
68002 ** The record number is not previously used as a key in the database
68003 ** table that cursor P1 points to.  The new record number is written
68004 ** written to register P2.
68005 **
68006 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
68007 ** the largest previously generated record number. No new record numbers are
68008 ** allowed to be less than this value. When this value reaches its maximum, 
68009 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
68010 ** generated record number. This P3 mechanism is used to help implement the
68011 ** AUTOINCREMENT feature.
68012 */
68013 case OP_NewRowid: {           /* out2-prerelease */
68014 #if 0  /* local variables moved into u.bh */
68015   i64 v;                 /* The new rowid */
68016   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
68017   int res;               /* Result of an sqlite3BtreeLast() */
68018   int cnt;               /* Counter to limit the number of searches */
68019   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
68020   VdbeFrame *pFrame;     /* Root frame of VDBE */
68021 #endif /* local variables moved into u.bh */
68022
68023   u.bh.v = 0;
68024   u.bh.res = 0;
68025   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68026   u.bh.pC = p->apCsr[pOp->p1];
68027   assert( u.bh.pC!=0 );
68028   if( NEVER(u.bh.pC->pCursor==0) ){
68029     /* The zero initialization above is all that is needed */
68030   }else{
68031     /* The next rowid or record number (different terms for the same
68032     ** thing) is obtained in a two-step algorithm.
68033     **
68034     ** First we attempt to find the largest existing rowid and add one
68035     ** to that.  But if the largest existing rowid is already the maximum
68036     ** positive integer, we have to fall through to the second
68037     ** probabilistic algorithm
68038     **
68039     ** The second algorithm is to select a rowid at random and see if
68040     ** it already exists in the table.  If it does not exist, we have
68041     ** succeeded.  If the random rowid does exist, we select a new one
68042     ** and try again, up to 100 times.
68043     */
68044     assert( u.bh.pC->isTable );
68045
68046 #ifdef SQLITE_32BIT_ROWID
68047 #   define MAX_ROWID 0x7fffffff
68048 #else
68049     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
68050     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
68051     ** to provide the constant while making all compilers happy.
68052     */
68053 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
68054 #endif
68055
68056     if( !u.bh.pC->useRandomRowid ){
68057       u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
68058       if( u.bh.v==0 ){
68059         rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
68060         if( rc!=SQLITE_OK ){
68061           goto abort_due_to_error;
68062         }
68063         if( u.bh.res ){
68064           u.bh.v = 1;   /* IMP: R-61914-48074 */
68065         }else{
68066           assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
68067           rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
68068           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
68069           if( u.bh.v>=MAX_ROWID ){
68070             u.bh.pC->useRandomRowid = 1;
68071           }else{
68072             u.bh.v++;   /* IMP: R-29538-34987 */
68073           }
68074         }
68075       }
68076
68077 #ifndef SQLITE_OMIT_AUTOINCREMENT
68078       if( pOp->p3 ){
68079         /* Assert that P3 is a valid memory cell. */
68080         assert( pOp->p3>0 );
68081         if( p->pFrame ){
68082           for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
68083           /* Assert that P3 is a valid memory cell. */
68084           assert( pOp->p3<=u.bh.pFrame->nMem );
68085           u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
68086         }else{
68087           /* Assert that P3 is a valid memory cell. */
68088           assert( pOp->p3<=p->nMem );
68089           u.bh.pMem = &aMem[pOp->p3];
68090           memAboutToChange(p, u.bh.pMem);
68091         }
68092         assert( memIsValid(u.bh.pMem) );
68093
68094         REGISTER_TRACE(pOp->p3, u.bh.pMem);
68095         sqlite3VdbeMemIntegerify(u.bh.pMem);
68096         assert( (u.bh.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
68097         if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
68098           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
68099           goto abort_due_to_error;
68100         }
68101         if( u.bh.v<u.bh.pMem->u.i+1 ){
68102           u.bh.v = u.bh.pMem->u.i + 1;
68103         }
68104         u.bh.pMem->u.i = u.bh.v;
68105       }
68106 #endif
68107
68108       sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
68109     }
68110     if( u.bh.pC->useRandomRowid ){
68111       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
68112       ** largest possible integer (9223372036854775807) then the database
68113       ** engine starts picking positive candidate ROWIDs at random until
68114       ** it finds one that is not previously used. */
68115       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
68116                              ** an AUTOINCREMENT table. */
68117       /* on the first attempt, simply do one more than previous */
68118       u.bh.v = lastRowid;
68119       u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
68120       u.bh.v++; /* ensure non-zero */
68121       u.bh.cnt = 0;
68122       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
68123                                                  0, &u.bh.res))==SQLITE_OK)
68124             && (u.bh.res==0)
68125             && (++u.bh.cnt<100)){
68126         /* collision - try another random rowid */
68127         sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
68128         if( u.bh.cnt<5 ){
68129           /* try "small" random rowids for the initial attempts */
68130           u.bh.v &= 0xffffff;
68131         }else{
68132           u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
68133         }
68134         u.bh.v++; /* ensure non-zero */
68135       }
68136       if( rc==SQLITE_OK && u.bh.res==0 ){
68137         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
68138         goto abort_due_to_error;
68139       }
68140       assert( u.bh.v>0 );  /* EV: R-40812-03570 */
68141     }
68142     u.bh.pC->rowidIsValid = 0;
68143     u.bh.pC->deferredMoveto = 0;
68144     u.bh.pC->cacheStatus = CACHE_STALE;
68145   }
68146   pOut->u.i = u.bh.v;
68147   break;
68148 }
68149
68150 /* Opcode: Insert P1 P2 P3 P4 P5
68151 **
68152 ** Write an entry into the table of cursor P1.  A new entry is
68153 ** created if it doesn't already exist or the data for an existing
68154 ** entry is overwritten.  The data is the value MEM_Blob stored in register
68155 ** number P2. The key is stored in register P3. The key must
68156 ** be a MEM_Int.
68157 **
68158 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
68159 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
68160 ** then rowid is stored for subsequent return by the
68161 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
68162 **
68163 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
68164 ** the last seek operation (OP_NotExists) was a success, then this
68165 ** operation will not attempt to find the appropriate row before doing
68166 ** the insert but will instead overwrite the row that the cursor is
68167 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
68168 ** has already positioned the cursor correctly.  This is an optimization
68169 ** that boosts performance by avoiding redundant seeks.
68170 **
68171 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
68172 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
68173 ** is part of an INSERT operation.  The difference is only important to
68174 ** the update hook.
68175 **
68176 ** Parameter P4 may point to a string containing the table-name, or
68177 ** may be NULL. If it is not NULL, then the update-hook 
68178 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
68179 **
68180 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
68181 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
68182 ** and register P2 becomes ephemeral.  If the cursor is changed, the
68183 ** value of register P2 will then change.  Make sure this does not
68184 ** cause any problems.)
68185 **
68186 ** This instruction only works on tables.  The equivalent instruction
68187 ** for indices is OP_IdxInsert.
68188 */
68189 /* Opcode: InsertInt P1 P2 P3 P4 P5
68190 **
68191 ** This works exactly like OP_Insert except that the key is the
68192 ** integer value P3, not the value of the integer stored in register P3.
68193 */
68194 case OP_Insert: 
68195 case OP_InsertInt: {
68196 #if 0  /* local variables moved into u.bi */
68197   Mem *pData;       /* MEM cell holding data for the record to be inserted */
68198   Mem *pKey;        /* MEM cell holding key  for the record */
68199   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
68200   VdbeCursor *pC;   /* Cursor to table into which insert is written */
68201   int nZero;        /* Number of zero-bytes to append */
68202   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
68203   const char *zDb;  /* database name - used by the update hook */
68204   const char *zTbl; /* Table name - used by the opdate hook */
68205   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
68206 #endif /* local variables moved into u.bi */
68207
68208   u.bi.pData = &aMem[pOp->p2];
68209   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68210   assert( memIsValid(u.bi.pData) );
68211   u.bi.pC = p->apCsr[pOp->p1];
68212   assert( u.bi.pC!=0 );
68213   assert( u.bi.pC->pCursor!=0 );
68214   assert( u.bi.pC->pseudoTableReg==0 );
68215   assert( u.bi.pC->isTable );
68216   REGISTER_TRACE(pOp->p2, u.bi.pData);
68217
68218   if( pOp->opcode==OP_Insert ){
68219     u.bi.pKey = &aMem[pOp->p3];
68220     assert( u.bi.pKey->flags & MEM_Int );
68221     assert( memIsValid(u.bi.pKey) );
68222     REGISTER_TRACE(pOp->p3, u.bi.pKey);
68223     u.bi.iKey = u.bi.pKey->u.i;
68224   }else{
68225     assert( pOp->opcode==OP_InsertInt );
68226     u.bi.iKey = pOp->p3;
68227   }
68228
68229   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
68230   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
68231   if( u.bi.pData->flags & MEM_Null ){
68232     u.bi.pData->z = 0;
68233     u.bi.pData->n = 0;
68234   }else{
68235     assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
68236   }
68237   u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
68238   if( u.bi.pData->flags & MEM_Zero ){
68239     u.bi.nZero = u.bi.pData->u.nZero;
68240   }else{
68241     u.bi.nZero = 0;
68242   }
68243   sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
68244   rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
68245                           u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
68246                           pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
68247   );
68248   u.bi.pC->rowidIsValid = 0;
68249   u.bi.pC->deferredMoveto = 0;
68250   u.bi.pC->cacheStatus = CACHE_STALE;
68251
68252   /* Invoke the update-hook if required. */
68253   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
68254     u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
68255     u.bi.zTbl = pOp->p4.z;
68256     u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
68257     assert( u.bi.pC->isTable );
68258     db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
68259     assert( u.bi.pC->iDb>=0 );
68260   }
68261   break;
68262 }
68263
68264 /* Opcode: Delete P1 P2 * P4 *
68265 **
68266 ** Delete the record at which the P1 cursor is currently pointing.
68267 **
68268 ** The cursor will be left pointing at either the next or the previous
68269 ** record in the table. If it is left pointing at the next record, then
68270 ** the next Next instruction will be a no-op.  Hence it is OK to delete
68271 ** a record from within an Next loop.
68272 **
68273 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
68274 ** incremented (otherwise not).
68275 **
68276 ** P1 must not be pseudo-table.  It has to be a real table with
68277 ** multiple rows.
68278 **
68279 ** If P4 is not NULL, then it is the name of the table that P1 is
68280 ** pointing to.  The update hook will be invoked, if it exists.
68281 ** If P4 is not NULL then the P1 cursor must have been positioned
68282 ** using OP_NotFound prior to invoking this opcode.
68283 */
68284 case OP_Delete: {
68285 #if 0  /* local variables moved into u.bj */
68286   i64 iKey;
68287   VdbeCursor *pC;
68288 #endif /* local variables moved into u.bj */
68289
68290   u.bj.iKey = 0;
68291   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68292   u.bj.pC = p->apCsr[pOp->p1];
68293   assert( u.bj.pC!=0 );
68294   assert( u.bj.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
68295
68296   /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
68297   ** row being deleted.
68298   */
68299   if( db->xUpdateCallback && pOp->p4.z ){
68300     assert( u.bj.pC->isTable );
68301     assert( u.bj.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
68302     u.bj.iKey = u.bj.pC->lastRowid;
68303   }
68304
68305   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
68306   ** OP_Column on the same table without any intervening operations that
68307   ** might move or invalidate the cursor.  Hence cursor u.bj.pC is always pointing
68308   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
68309   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
68310   ** to guard against future changes to the code generator.
68311   **/
68312   assert( u.bj.pC->deferredMoveto==0 );
68313   rc = sqlite3VdbeCursorMoveto(u.bj.pC);
68314   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
68315
68316   sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
68317   rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
68318   u.bj.pC->cacheStatus = CACHE_STALE;
68319
68320   /* Invoke the update-hook if required. */
68321   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
68322     const char *zDb = db->aDb[u.bj.pC->iDb].zName;
68323     const char *zTbl = pOp->p4.z;
68324     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
68325     assert( u.bj.pC->iDb>=0 );
68326   }
68327   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
68328   break;
68329 }
68330 /* Opcode: ResetCount * * * * *
68331 **
68332 ** The value of the change counter is copied to the database handle
68333 ** change counter (returned by subsequent calls to sqlite3_changes()).
68334 ** Then the VMs internal change counter resets to 0.
68335 ** This is used by trigger programs.
68336 */
68337 case OP_ResetCount: {
68338   sqlite3VdbeSetChanges(db, p->nChange);
68339   p->nChange = 0;
68340   break;
68341 }
68342
68343 /* Opcode: SorterCompare P1 P2 P3
68344 **
68345 ** P1 is a sorter cursor. This instruction compares the record blob in 
68346 ** register P3 with the entry that the sorter cursor currently points to.
68347 ** If, excluding the rowid fields at the end, the two records are a match,
68348 ** fall through to the next instruction. Otherwise, jump to instruction P2.
68349 */
68350 case OP_SorterCompare: {
68351 #if 0  /* local variables moved into u.bk */
68352   VdbeCursor *pC;
68353   int res;
68354 #endif /* local variables moved into u.bk */
68355
68356   u.bk.pC = p->apCsr[pOp->p1];
68357   assert( isSorter(u.bk.pC) );
68358   pIn3 = &aMem[pOp->p3];
68359   rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
68360   if( u.bk.res ){
68361     pc = pOp->p2-1;
68362   }
68363   break;
68364 };
68365
68366 /* Opcode: SorterData P1 P2 * * *
68367 **
68368 ** Write into register P2 the current sorter data for sorter cursor P1.
68369 */
68370 case OP_SorterData: {
68371 #if 0  /* local variables moved into u.bl */
68372   VdbeCursor *pC;
68373 #endif /* local variables moved into u.bl */
68374
68375   pOut = &aMem[pOp->p2];
68376   u.bl.pC = p->apCsr[pOp->p1];
68377   assert( u.bl.pC->isSorter );
68378   rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
68379   break;
68380 }
68381
68382 /* Opcode: RowData P1 P2 * * *
68383 **
68384 ** Write into register P2 the complete row data for cursor P1.
68385 ** There is no interpretation of the data.  
68386 ** It is just copied onto the P2 register exactly as 
68387 ** it is found in the database file.
68388 **
68389 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
68390 ** of a real table, not a pseudo-table.
68391 */
68392 /* Opcode: RowKey P1 P2 * * *
68393 **
68394 ** Write into register P2 the complete row key for cursor P1.
68395 ** There is no interpretation of the data.  
68396 ** The key is copied onto the P3 register exactly as 
68397 ** it is found in the database file.
68398 **
68399 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
68400 ** of a real table, not a pseudo-table.
68401 */
68402 case OP_RowKey:
68403 case OP_RowData: {
68404 #if 0  /* local variables moved into u.bm */
68405   VdbeCursor *pC;
68406   BtCursor *pCrsr;
68407   u32 n;
68408   i64 n64;
68409 #endif /* local variables moved into u.bm */
68410
68411   pOut = &aMem[pOp->p2];
68412   memAboutToChange(p, pOut);
68413
68414   /* Note that RowKey and RowData are really exactly the same instruction */
68415   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68416   u.bm.pC = p->apCsr[pOp->p1];
68417   assert( u.bm.pC->isSorter==0 );
68418   assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
68419   assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
68420   assert( u.bm.pC!=0 );
68421   assert( u.bm.pC->nullRow==0 );
68422   assert( u.bm.pC->pseudoTableReg==0 );
68423   assert( u.bm.pC->pCursor!=0 );
68424   u.bm.pCrsr = u.bm.pC->pCursor;
68425   assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
68426
68427   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
68428   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
68429   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
68430   ** a no-op and can never fail.  But we leave it in place as a safety.
68431   */
68432   assert( u.bm.pC->deferredMoveto==0 );
68433   rc = sqlite3VdbeCursorMoveto(u.bm.pC);
68434   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
68435
68436   if( u.bm.pC->isIndex ){
68437     assert( !u.bm.pC->isTable );
68438     VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
68439     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
68440     if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
68441       goto too_big;
68442     }
68443     u.bm.n = (u32)u.bm.n64;
68444   }else{
68445     VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
68446     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
68447     if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
68448       goto too_big;
68449     }
68450   }
68451   if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
68452     goto no_mem;
68453   }
68454   pOut->n = u.bm.n;
68455   MemSetTypeFlag(pOut, MEM_Blob);
68456   if( u.bm.pC->isIndex ){
68457     rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
68458   }else{
68459     rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
68460   }
68461   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
68462   UPDATE_MAX_BLOBSIZE(pOut);
68463   break;
68464 }
68465
68466 /* Opcode: Rowid P1 P2 * * *
68467 **
68468 ** Store in register P2 an integer which is the key of the table entry that
68469 ** P1 is currently point to.
68470 **
68471 ** P1 can be either an ordinary table or a virtual table.  There used to
68472 ** be a separate OP_VRowid opcode for use with virtual tables, but this
68473 ** one opcode now works for both table types.
68474 */
68475 case OP_Rowid: {                 /* out2-prerelease */
68476 #if 0  /* local variables moved into u.bn */
68477   VdbeCursor *pC;
68478   i64 v;
68479   sqlite3_vtab *pVtab;
68480   const sqlite3_module *pModule;
68481 #endif /* local variables moved into u.bn */
68482
68483   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68484   u.bn.pC = p->apCsr[pOp->p1];
68485   assert( u.bn.pC!=0 );
68486   assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
68487   if( u.bn.pC->nullRow ){
68488     pOut->flags = MEM_Null;
68489     break;
68490   }else if( u.bn.pC->deferredMoveto ){
68491     u.bn.v = u.bn.pC->movetoTarget;
68492 #ifndef SQLITE_OMIT_VIRTUALTABLE
68493   }else if( u.bn.pC->pVtabCursor ){
68494     u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
68495     u.bn.pModule = u.bn.pVtab->pModule;
68496     assert( u.bn.pModule->xRowid );
68497     rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
68498     importVtabErrMsg(p, u.bn.pVtab);
68499 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68500   }else{
68501     assert( u.bn.pC->pCursor!=0 );
68502     rc = sqlite3VdbeCursorMoveto(u.bn.pC);
68503     if( rc ) goto abort_due_to_error;
68504     if( u.bn.pC->rowidIsValid ){
68505       u.bn.v = u.bn.pC->lastRowid;
68506     }else{
68507       rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
68508       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
68509     }
68510   }
68511   pOut->u.i = u.bn.v;
68512   break;
68513 }
68514
68515 /* Opcode: NullRow P1 * * * *
68516 **
68517 ** Move the cursor P1 to a null row.  Any OP_Column operations
68518 ** that occur while the cursor is on the null row will always
68519 ** write a NULL.
68520 */
68521 case OP_NullRow: {
68522 #if 0  /* local variables moved into u.bo */
68523   VdbeCursor *pC;
68524 #endif /* local variables moved into u.bo */
68525
68526   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68527   u.bo.pC = p->apCsr[pOp->p1];
68528   assert( u.bo.pC!=0 );
68529   u.bo.pC->nullRow = 1;
68530   u.bo.pC->rowidIsValid = 0;
68531   assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
68532   if( u.bo.pC->pCursor ){
68533     sqlite3BtreeClearCursor(u.bo.pC->pCursor);
68534   }
68535   break;
68536 }
68537
68538 /* Opcode: Last P1 P2 * * *
68539 **
68540 ** The next use of the Rowid or Column or Next instruction for P1 
68541 ** will refer to the last entry in the database table or index.
68542 ** If the table or index is empty and P2>0, then jump immediately to P2.
68543 ** If P2 is 0 or if the table or index is not empty, fall through
68544 ** to the following instruction.
68545 */
68546 case OP_Last: {        /* jump */
68547 #if 0  /* local variables moved into u.bp */
68548   VdbeCursor *pC;
68549   BtCursor *pCrsr;
68550   int res;
68551 #endif /* local variables moved into u.bp */
68552
68553   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68554   u.bp.pC = p->apCsr[pOp->p1];
68555   assert( u.bp.pC!=0 );
68556   u.bp.pCrsr = u.bp.pC->pCursor;
68557   u.bp.res = 0;
68558   if( ALWAYS(u.bp.pCrsr!=0) ){
68559     rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
68560   }
68561   u.bp.pC->nullRow = (u8)u.bp.res;
68562   u.bp.pC->deferredMoveto = 0;
68563   u.bp.pC->rowidIsValid = 0;
68564   u.bp.pC->cacheStatus = CACHE_STALE;
68565   if( pOp->p2>0 && u.bp.res ){
68566     pc = pOp->p2 - 1;
68567   }
68568   break;
68569 }
68570
68571
68572 /* Opcode: Sort P1 P2 * * *
68573 **
68574 ** This opcode does exactly the same thing as OP_Rewind except that
68575 ** it increments an undocumented global variable used for testing.
68576 **
68577 ** Sorting is accomplished by writing records into a sorting index,
68578 ** then rewinding that index and playing it back from beginning to
68579 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
68580 ** rewinding so that the global variable will be incremented and
68581 ** regression tests can determine whether or not the optimizer is
68582 ** correctly optimizing out sorts.
68583 */
68584 case OP_SorterSort:    /* jump */
68585 case OP_Sort: {        /* jump */
68586 #ifdef SQLITE_TEST
68587   sqlite3_sort_count++;
68588   sqlite3_search_count--;
68589 #endif
68590   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
68591   /* Fall through into OP_Rewind */
68592 }
68593 /* Opcode: Rewind P1 P2 * * *
68594 **
68595 ** The next use of the Rowid or Column or Next instruction for P1 
68596 ** will refer to the first entry in the database table or index.
68597 ** If the table or index is empty and P2>0, then jump immediately to P2.
68598 ** If P2 is 0 or if the table or index is not empty, fall through
68599 ** to the following instruction.
68600 */
68601 case OP_Rewind: {        /* jump */
68602 #if 0  /* local variables moved into u.bq */
68603   VdbeCursor *pC;
68604   BtCursor *pCrsr;
68605   int res;
68606 #endif /* local variables moved into u.bq */
68607
68608   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68609   u.bq.pC = p->apCsr[pOp->p1];
68610   assert( u.bq.pC!=0 );
68611   assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
68612   u.bq.res = 1;
68613   if( isSorter(u.bq.pC) ){
68614     rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
68615   }else{
68616     u.bq.pCrsr = u.bq.pC->pCursor;
68617     assert( u.bq.pCrsr );
68618     rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
68619     u.bq.pC->atFirst = u.bq.res==0 ?1:0;
68620     u.bq.pC->deferredMoveto = 0;
68621     u.bq.pC->cacheStatus = CACHE_STALE;
68622     u.bq.pC->rowidIsValid = 0;
68623   }
68624   u.bq.pC->nullRow = (u8)u.bq.res;
68625   assert( pOp->p2>0 && pOp->p2<p->nOp );
68626   if( u.bq.res ){
68627     pc = pOp->p2 - 1;
68628   }
68629   break;
68630 }
68631
68632 /* Opcode: Next P1 P2 * P4 P5
68633 **
68634 ** Advance cursor P1 so that it points to the next key/data pair in its
68635 ** table or index.  If there are no more key/value pairs then fall through
68636 ** to the following instruction.  But if the cursor advance was successful,
68637 ** jump immediately to P2.
68638 **
68639 ** The P1 cursor must be for a real table, not a pseudo-table.
68640 **
68641 ** P4 is always of type P4_ADVANCE. The function pointer points to
68642 ** sqlite3BtreeNext().
68643 **
68644 ** If P5 is positive and the jump is taken, then event counter
68645 ** number P5-1 in the prepared statement is incremented.
68646 **
68647 ** See also: Prev
68648 */
68649 /* Opcode: Prev P1 P2 * * P5
68650 **
68651 ** Back up cursor P1 so that it points to the previous key/data pair in its
68652 ** table or index.  If there is no previous key/value pairs then fall through
68653 ** to the following instruction.  But if the cursor backup was successful,
68654 ** jump immediately to P2.
68655 **
68656 ** The P1 cursor must be for a real table, not a pseudo-table.
68657 **
68658 ** P4 is always of type P4_ADVANCE. The function pointer points to
68659 ** sqlite3BtreePrevious().
68660 **
68661 ** If P5 is positive and the jump is taken, then event counter
68662 ** number P5-1 in the prepared statement is incremented.
68663 */
68664 case OP_SorterNext:    /* jump */
68665 case OP_Prev:          /* jump */
68666 case OP_Next: {        /* jump */
68667 #if 0  /* local variables moved into u.br */
68668   VdbeCursor *pC;
68669   int res;
68670 #endif /* local variables moved into u.br */
68671
68672   CHECK_FOR_INTERRUPT;
68673   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68674   assert( pOp->p5<=ArraySize(p->aCounter) );
68675   u.br.pC = p->apCsr[pOp->p1];
68676   if( u.br.pC==0 ){
68677     break;  /* See ticket #2273 */
68678   }
68679   assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
68680   if( isSorter(u.br.pC) ){
68681     assert( pOp->opcode==OP_SorterNext );
68682     rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
68683   }else{
68684     u.br.res = 1;
68685     assert( u.br.pC->deferredMoveto==0 );
68686     assert( u.br.pC->pCursor );
68687     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
68688     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
68689     rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
68690   }
68691   u.br.pC->nullRow = (u8)u.br.res;
68692   u.br.pC->cacheStatus = CACHE_STALE;
68693   if( u.br.res==0 ){
68694     pc = pOp->p2 - 1;
68695     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
68696 #ifdef SQLITE_TEST
68697     sqlite3_search_count++;
68698 #endif
68699   }
68700   u.br.pC->rowidIsValid = 0;
68701   break;
68702 }
68703
68704 /* Opcode: IdxInsert P1 P2 P3 * P5
68705 **
68706 ** Register P2 holds an SQL index key made using the
68707 ** MakeRecord instructions.  This opcode writes that key
68708 ** into the index P1.  Data for the entry is nil.
68709 **
68710 ** P3 is a flag that provides a hint to the b-tree layer that this
68711 ** insert is likely to be an append.
68712 **
68713 ** This instruction only works for indices.  The equivalent instruction
68714 ** for tables is OP_Insert.
68715 */
68716 case OP_SorterInsert:       /* in2 */
68717 case OP_IdxInsert: {        /* in2 */
68718 #if 0  /* local variables moved into u.bs */
68719   VdbeCursor *pC;
68720   BtCursor *pCrsr;
68721   int nKey;
68722   const char *zKey;
68723 #endif /* local variables moved into u.bs */
68724
68725   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68726   u.bs.pC = p->apCsr[pOp->p1];
68727   assert( u.bs.pC!=0 );
68728   assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
68729   pIn2 = &aMem[pOp->p2];
68730   assert( pIn2->flags & MEM_Blob );
68731   u.bs.pCrsr = u.bs.pC->pCursor;
68732   if( ALWAYS(u.bs.pCrsr!=0) ){
68733     assert( u.bs.pC->isTable==0 );
68734     rc = ExpandBlob(pIn2);
68735     if( rc==SQLITE_OK ){
68736       if( isSorter(u.bs.pC) ){
68737         rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
68738       }else{
68739         u.bs.nKey = pIn2->n;
68740         u.bs.zKey = pIn2->z;
68741         rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
68742             ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
68743             );
68744         assert( u.bs.pC->deferredMoveto==0 );
68745         u.bs.pC->cacheStatus = CACHE_STALE;
68746       }
68747     }
68748   }
68749   break;
68750 }
68751
68752 /* Opcode: IdxDelete P1 P2 P3 * *
68753 **
68754 ** The content of P3 registers starting at register P2 form
68755 ** an unpacked index key. This opcode removes that entry from the 
68756 ** index opened by cursor P1.
68757 */
68758 case OP_IdxDelete: {
68759 #if 0  /* local variables moved into u.bt */
68760   VdbeCursor *pC;
68761   BtCursor *pCrsr;
68762   int res;
68763   UnpackedRecord r;
68764 #endif /* local variables moved into u.bt */
68765
68766   assert( pOp->p3>0 );
68767   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
68768   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68769   u.bt.pC = p->apCsr[pOp->p1];
68770   assert( u.bt.pC!=0 );
68771   u.bt.pCrsr = u.bt.pC->pCursor;
68772   if( ALWAYS(u.bt.pCrsr!=0) ){
68773     u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
68774     u.bt.r.nField = (u16)pOp->p3;
68775     u.bt.r.flags = 0;
68776     u.bt.r.aMem = &aMem[pOp->p2];
68777 #ifdef SQLITE_DEBUG
68778     { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
68779 #endif
68780     rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
68781     if( rc==SQLITE_OK && u.bt.res==0 ){
68782       rc = sqlite3BtreeDelete(u.bt.pCrsr);
68783     }
68784     assert( u.bt.pC->deferredMoveto==0 );
68785     u.bt.pC->cacheStatus = CACHE_STALE;
68786   }
68787   break;
68788 }
68789
68790 /* Opcode: IdxRowid P1 P2 * * *
68791 **
68792 ** Write into register P2 an integer which is the last entry in the record at
68793 ** the end of the index key pointed to by cursor P1.  This integer should be
68794 ** the rowid of the table entry to which this index entry points.
68795 **
68796 ** See also: Rowid, MakeRecord.
68797 */
68798 case OP_IdxRowid: {              /* out2-prerelease */
68799 #if 0  /* local variables moved into u.bu */
68800   BtCursor *pCrsr;
68801   VdbeCursor *pC;
68802   i64 rowid;
68803 #endif /* local variables moved into u.bu */
68804
68805   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68806   u.bu.pC = p->apCsr[pOp->p1];
68807   assert( u.bu.pC!=0 );
68808   u.bu.pCrsr = u.bu.pC->pCursor;
68809   pOut->flags = MEM_Null;
68810   if( ALWAYS(u.bu.pCrsr!=0) ){
68811     rc = sqlite3VdbeCursorMoveto(u.bu.pC);
68812     if( NEVER(rc) ) goto abort_due_to_error;
68813     assert( u.bu.pC->deferredMoveto==0 );
68814     assert( u.bu.pC->isTable==0 );
68815     if( !u.bu.pC->nullRow ){
68816       rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
68817       if( rc!=SQLITE_OK ){
68818         goto abort_due_to_error;
68819       }
68820       pOut->u.i = u.bu.rowid;
68821       pOut->flags = MEM_Int;
68822     }
68823   }
68824   break;
68825 }
68826
68827 /* Opcode: IdxGE P1 P2 P3 P4 P5
68828 **
68829 ** The P4 register values beginning with P3 form an unpacked index 
68830 ** key that omits the ROWID.  Compare this key value against the index 
68831 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
68832 **
68833 ** If the P1 index entry is greater than or equal to the key value
68834 ** then jump to P2.  Otherwise fall through to the next instruction.
68835 **
68836 ** If P5 is non-zero then the key value is increased by an epsilon 
68837 ** prior to the comparison.  This make the opcode work like IdxGT except
68838 ** that if the key from register P3 is a prefix of the key in the cursor,
68839 ** the result is false whereas it would be true with IdxGT.
68840 */
68841 /* Opcode: IdxLT P1 P2 P3 P4 P5
68842 **
68843 ** The P4 register values beginning with P3 form an unpacked index 
68844 ** key that omits the ROWID.  Compare this key value against the index 
68845 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
68846 **
68847 ** If the P1 index entry is less than the key value then jump to P2.
68848 ** Otherwise fall through to the next instruction.
68849 **
68850 ** If P5 is non-zero then the key value is increased by an epsilon prior 
68851 ** to the comparison.  This makes the opcode work like IdxLE.
68852 */
68853 case OP_IdxLT:          /* jump */
68854 case OP_IdxGE: {        /* jump */
68855 #if 0  /* local variables moved into u.bv */
68856   VdbeCursor *pC;
68857   int res;
68858   UnpackedRecord r;
68859 #endif /* local variables moved into u.bv */
68860
68861   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68862   u.bv.pC = p->apCsr[pOp->p1];
68863   assert( u.bv.pC!=0 );
68864   assert( u.bv.pC->isOrdered );
68865   if( ALWAYS(u.bv.pC->pCursor!=0) ){
68866     assert( u.bv.pC->deferredMoveto==0 );
68867     assert( pOp->p5==0 || pOp->p5==1 );
68868     assert( pOp->p4type==P4_INT32 );
68869     u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
68870     u.bv.r.nField = (u16)pOp->p4.i;
68871     if( pOp->p5 ){
68872       u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
68873     }else{
68874       u.bv.r.flags = UNPACKED_PREFIX_MATCH;
68875     }
68876     u.bv.r.aMem = &aMem[pOp->p3];
68877 #ifdef SQLITE_DEBUG
68878     { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
68879 #endif
68880     rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
68881     if( pOp->opcode==OP_IdxLT ){
68882       u.bv.res = -u.bv.res;
68883     }else{
68884       assert( pOp->opcode==OP_IdxGE );
68885       u.bv.res++;
68886     }
68887     if( u.bv.res>0 ){
68888       pc = pOp->p2 - 1 ;
68889     }
68890   }
68891   break;
68892 }
68893
68894 /* Opcode: Destroy P1 P2 P3 * *
68895 **
68896 ** Delete an entire database table or index whose root page in the database
68897 ** file is given by P1.
68898 **
68899 ** The table being destroyed is in the main database file if P3==0.  If
68900 ** P3==1 then the table to be clear is in the auxiliary database file
68901 ** that is used to store tables create using CREATE TEMPORARY TABLE.
68902 **
68903 ** If AUTOVACUUM is enabled then it is possible that another root page
68904 ** might be moved into the newly deleted root page in order to keep all
68905 ** root pages contiguous at the beginning of the database.  The former
68906 ** value of the root page that moved - its value before the move occurred -
68907 ** is stored in register P2.  If no page 
68908 ** movement was required (because the table being dropped was already 
68909 ** the last one in the database) then a zero is stored in register P2.
68910 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
68911 **
68912 ** See also: Clear
68913 */
68914 case OP_Destroy: {     /* out2-prerelease */
68915 #if 0  /* local variables moved into u.bw */
68916   int iMoved;
68917   int iCnt;
68918   Vdbe *pVdbe;
68919   int iDb;
68920 #endif /* local variables moved into u.bw */
68921
68922 #ifndef SQLITE_OMIT_VIRTUALTABLE
68923   u.bw.iCnt = 0;
68924   for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
68925     if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0 ){
68926       u.bw.iCnt++;
68927     }
68928   }
68929 #else
68930   u.bw.iCnt = db->activeVdbeCnt;
68931 #endif
68932   pOut->flags = MEM_Null;
68933   if( u.bw.iCnt>1 ){
68934     rc = SQLITE_LOCKED;
68935     p->errorAction = OE_Abort;
68936   }else{
68937     u.bw.iDb = pOp->p3;
68938     assert( u.bw.iCnt==1 );
68939     assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
68940     rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
68941     pOut->flags = MEM_Int;
68942     pOut->u.i = u.bw.iMoved;
68943 #ifndef SQLITE_OMIT_AUTOVACUUM
68944     if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
68945       sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
68946       /* All OP_Destroy operations occur on the same btree */
68947       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
68948       resetSchemaOnFault = u.bw.iDb+1;
68949     }
68950 #endif
68951   }
68952   break;
68953 }
68954
68955 /* Opcode: Clear P1 P2 P3
68956 **
68957 ** Delete all contents of the database table or index whose root page
68958 ** in the database file is given by P1.  But, unlike Destroy, do not
68959 ** remove the table or index from the database file.
68960 **
68961 ** The table being clear is in the main database file if P2==0.  If
68962 ** P2==1 then the table to be clear is in the auxiliary database file
68963 ** that is used to store tables create using CREATE TEMPORARY TABLE.
68964 **
68965 ** If the P3 value is non-zero, then the table referred to must be an
68966 ** intkey table (an SQL table, not an index). In this case the row change 
68967 ** count is incremented by the number of rows in the table being cleared. 
68968 ** If P3 is greater than zero, then the value stored in register P3 is
68969 ** also incremented by the number of rows in the table being cleared.
68970 **
68971 ** See also: Destroy
68972 */
68973 case OP_Clear: {
68974 #if 0  /* local variables moved into u.bx */
68975   int nChange;
68976 #endif /* local variables moved into u.bx */
68977
68978   u.bx.nChange = 0;
68979   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
68980   rc = sqlite3BtreeClearTable(
68981       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
68982   );
68983   if( pOp->p3 ){
68984     p->nChange += u.bx.nChange;
68985     if( pOp->p3>0 ){
68986       assert( memIsValid(&aMem[pOp->p3]) );
68987       memAboutToChange(p, &aMem[pOp->p3]);
68988       aMem[pOp->p3].u.i += u.bx.nChange;
68989     }
68990   }
68991   break;
68992 }
68993
68994 /* Opcode: CreateTable P1 P2 * * *
68995 **
68996 ** Allocate a new table in the main database file if P1==0 or in the
68997 ** auxiliary database file if P1==1 or in an attached database if
68998 ** P1>1.  Write the root page number of the new table into
68999 ** register P2
69000 **
69001 ** The difference between a table and an index is this:  A table must
69002 ** have a 4-byte integer key and can have arbitrary data.  An index
69003 ** has an arbitrary key but no data.
69004 **
69005 ** See also: CreateIndex
69006 */
69007 /* Opcode: CreateIndex P1 P2 * * *
69008 **
69009 ** Allocate a new index in the main database file if P1==0 or in the
69010 ** auxiliary database file if P1==1 or in an attached database if
69011 ** P1>1.  Write the root page number of the new table into
69012 ** register P2.
69013 **
69014 ** See documentation on OP_CreateTable for additional information.
69015 */
69016 case OP_CreateIndex:            /* out2-prerelease */
69017 case OP_CreateTable: {          /* out2-prerelease */
69018 #if 0  /* local variables moved into u.by */
69019   int pgno;
69020   int flags;
69021   Db *pDb;
69022 #endif /* local variables moved into u.by */
69023
69024   u.by.pgno = 0;
69025   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69026   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69027   u.by.pDb = &db->aDb[pOp->p1];
69028   assert( u.by.pDb->pBt!=0 );
69029   if( pOp->opcode==OP_CreateTable ){
69030     /* u.by.flags = BTREE_INTKEY; */
69031     u.by.flags = BTREE_INTKEY;
69032   }else{
69033     u.by.flags = BTREE_BLOBKEY;
69034   }
69035   rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
69036   pOut->u.i = u.by.pgno;
69037   break;
69038 }
69039
69040 /* Opcode: ParseSchema P1 * * P4 *
69041 **
69042 ** Read and parse all entries from the SQLITE_MASTER table of database P1
69043 ** that match the WHERE clause P4. 
69044 **
69045 ** This opcode invokes the parser to create a new virtual machine,
69046 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
69047 */
69048 case OP_ParseSchema: {
69049 #if 0  /* local variables moved into u.bz */
69050   int iDb;
69051   const char *zMaster;
69052   char *zSql;
69053   InitData initData;
69054 #endif /* local variables moved into u.bz */
69055
69056   /* Any prepared statement that invokes this opcode will hold mutexes
69057   ** on every btree.  This is a prerequisite for invoking
69058   ** sqlite3InitCallback().
69059   */
69060 #ifdef SQLITE_DEBUG
69061   for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
69062     assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
69063   }
69064 #endif
69065
69066   u.bz.iDb = pOp->p1;
69067   assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
69068   assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
69069   /* Used to be a conditional */ {
69070     u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
69071     u.bz.initData.db = db;
69072     u.bz.initData.iDb = pOp->p1;
69073     u.bz.initData.pzErrMsg = &p->zErrMsg;
69074     u.bz.zSql = sqlite3MPrintf(db,
69075        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
69076        db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
69077     if( u.bz.zSql==0 ){
69078       rc = SQLITE_NOMEM;
69079     }else{
69080       assert( db->init.busy==0 );
69081       db->init.busy = 1;
69082       u.bz.initData.rc = SQLITE_OK;
69083       assert( !db->mallocFailed );
69084       rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
69085       if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
69086       sqlite3DbFree(db, u.bz.zSql);
69087       db->init.busy = 0;
69088     }
69089   }
69090   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
69091   if( rc==SQLITE_NOMEM ){
69092     goto no_mem;
69093   }
69094   break;
69095 }
69096
69097 #if !defined(SQLITE_OMIT_ANALYZE)
69098 /* Opcode: LoadAnalysis P1 * * * *
69099 **
69100 ** Read the sqlite_stat1 table for database P1 and load the content
69101 ** of that table into the internal index hash table.  This will cause
69102 ** the analysis to be used when preparing all subsequent queries.
69103 */
69104 case OP_LoadAnalysis: {
69105   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69106   rc = sqlite3AnalysisLoad(db, pOp->p1);
69107   break;  
69108 }
69109 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
69110
69111 /* Opcode: DropTable P1 * * P4 *
69112 **
69113 ** Remove the internal (in-memory) data structures that describe
69114 ** the table named P4 in database P1.  This is called after a table
69115 ** is dropped in order to keep the internal representation of the
69116 ** schema consistent with what is on disk.
69117 */
69118 case OP_DropTable: {
69119   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
69120   break;
69121 }
69122
69123 /* Opcode: DropIndex P1 * * P4 *
69124 **
69125 ** Remove the internal (in-memory) data structures that describe
69126 ** the index named P4 in database P1.  This is called after an index
69127 ** is dropped in order to keep the internal representation of the
69128 ** schema consistent with what is on disk.
69129 */
69130 case OP_DropIndex: {
69131   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
69132   break;
69133 }
69134
69135 /* Opcode: DropTrigger P1 * * P4 *
69136 **
69137 ** Remove the internal (in-memory) data structures that describe
69138 ** the trigger named P4 in database P1.  This is called after a trigger
69139 ** is dropped in order to keep the internal representation of the
69140 ** schema consistent with what is on disk.
69141 */
69142 case OP_DropTrigger: {
69143   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
69144   break;
69145 }
69146
69147
69148 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
69149 /* Opcode: IntegrityCk P1 P2 P3 * P5
69150 **
69151 ** Do an analysis of the currently open database.  Store in
69152 ** register P1 the text of an error message describing any problems.
69153 ** If no problems are found, store a NULL in register P1.
69154 **
69155 ** The register P3 contains the maximum number of allowed errors.
69156 ** At most reg(P3) errors will be reported.
69157 ** In other words, the analysis stops as soon as reg(P1) errors are 
69158 ** seen.  Reg(P1) is updated with the number of errors remaining.
69159 **
69160 ** The root page numbers of all tables in the database are integer
69161 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
69162 ** total.
69163 **
69164 ** If P5 is not zero, the check is done on the auxiliary database
69165 ** file, not the main database file.
69166 **
69167 ** This opcode is used to implement the integrity_check pragma.
69168 */
69169 case OP_IntegrityCk: {
69170 #if 0  /* local variables moved into u.ca */
69171   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
69172   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
69173   int j;          /* Loop counter */
69174   int nErr;       /* Number of errors reported */
69175   char *z;        /* Text of the error report */
69176   Mem *pnErr;     /* Register keeping track of errors remaining */
69177 #endif /* local variables moved into u.ca */
69178
69179   u.ca.nRoot = pOp->p2;
69180   assert( u.ca.nRoot>0 );
69181   u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
69182   if( u.ca.aRoot==0 ) goto no_mem;
69183   assert( pOp->p3>0 && pOp->p3<=p->nMem );
69184   u.ca.pnErr = &aMem[pOp->p3];
69185   assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
69186   assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
69187   pIn1 = &aMem[pOp->p1];
69188   for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
69189     u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
69190   }
69191   u.ca.aRoot[u.ca.j] = 0;
69192   assert( pOp->p5<db->nDb );
69193   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
69194   u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
69195                                  (int)u.ca.pnErr->u.i, &u.ca.nErr);
69196   sqlite3DbFree(db, u.ca.aRoot);
69197   u.ca.pnErr->u.i -= u.ca.nErr;
69198   sqlite3VdbeMemSetNull(pIn1);
69199   if( u.ca.nErr==0 ){
69200     assert( u.ca.z==0 );
69201   }else if( u.ca.z==0 ){
69202     goto no_mem;
69203   }else{
69204     sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
69205   }
69206   UPDATE_MAX_BLOBSIZE(pIn1);
69207   sqlite3VdbeChangeEncoding(pIn1, encoding);
69208   break;
69209 }
69210 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
69211
69212 /* Opcode: RowSetAdd P1 P2 * * *
69213 **
69214 ** Insert the integer value held by register P2 into a boolean index
69215 ** held in register P1.
69216 **
69217 ** An assertion fails if P2 is not an integer.
69218 */
69219 case OP_RowSetAdd: {       /* in1, in2 */
69220   pIn1 = &aMem[pOp->p1];
69221   pIn2 = &aMem[pOp->p2];
69222   assert( (pIn2->flags & MEM_Int)!=0 );
69223   if( (pIn1->flags & MEM_RowSet)==0 ){
69224     sqlite3VdbeMemSetRowSet(pIn1);
69225     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69226   }
69227   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
69228   break;
69229 }
69230
69231 /* Opcode: RowSetRead P1 P2 P3 * *
69232 **
69233 ** Extract the smallest value from boolean index P1 and put that value into
69234 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
69235 ** unchanged and jump to instruction P2.
69236 */
69237 case OP_RowSetRead: {       /* jump, in1, out3 */
69238 #if 0  /* local variables moved into u.cb */
69239   i64 val;
69240 #endif /* local variables moved into u.cb */
69241   CHECK_FOR_INTERRUPT;
69242   pIn1 = &aMem[pOp->p1];
69243   if( (pIn1->flags & MEM_RowSet)==0
69244    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
69245   ){
69246     /* The boolean index is empty */
69247     sqlite3VdbeMemSetNull(pIn1);
69248     pc = pOp->p2 - 1;
69249   }else{
69250     /* A value was pulled from the index */
69251     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
69252   }
69253   break;
69254 }
69255
69256 /* Opcode: RowSetTest P1 P2 P3 P4
69257 **
69258 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
69259 ** contains a RowSet object and that RowSet object contains
69260 ** the value held in P3, jump to register P2. Otherwise, insert the
69261 ** integer in P3 into the RowSet and continue on to the
69262 ** next opcode.
69263 **
69264 ** The RowSet object is optimized for the case where successive sets
69265 ** of integers, where each set contains no duplicates. Each set
69266 ** of values is identified by a unique P4 value. The first set
69267 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
69268 ** non-negative.  For non-negative values of P4 only the lower 4
69269 ** bits are significant.
69270 **
69271 ** This allows optimizations: (a) when P4==0 there is no need to test
69272 ** the rowset object for P3, as it is guaranteed not to contain it,
69273 ** (b) when P4==-1 there is no need to insert the value, as it will
69274 ** never be tested for, and (c) when a value that is part of set X is
69275 ** inserted, there is no need to search to see if the same value was
69276 ** previously inserted as part of set X (only if it was previously
69277 ** inserted as part of some other set).
69278 */
69279 case OP_RowSetTest: {                     /* jump, in1, in3 */
69280 #if 0  /* local variables moved into u.cc */
69281   int iSet;
69282   int exists;
69283 #endif /* local variables moved into u.cc */
69284
69285   pIn1 = &aMem[pOp->p1];
69286   pIn3 = &aMem[pOp->p3];
69287   u.cc.iSet = pOp->p4.i;
69288   assert( pIn3->flags&MEM_Int );
69289
69290   /* If there is anything other than a rowset object in memory cell P1,
69291   ** delete it now and initialize P1 with an empty rowset
69292   */
69293   if( (pIn1->flags & MEM_RowSet)==0 ){
69294     sqlite3VdbeMemSetRowSet(pIn1);
69295     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69296   }
69297
69298   assert( pOp->p4type==P4_INT32 );
69299   assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
69300   if( u.cc.iSet ){
69301     u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
69302                                (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
69303                                pIn3->u.i);
69304     if( u.cc.exists ){
69305       pc = pOp->p2 - 1;
69306       break;
69307     }
69308   }
69309   if( u.cc.iSet>=0 ){
69310     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
69311   }
69312   break;
69313 }
69314
69315
69316 #ifndef SQLITE_OMIT_TRIGGER
69317
69318 /* Opcode: Program P1 P2 P3 P4 *
69319 **
69320 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
69321 **
69322 ** P1 contains the address of the memory cell that contains the first memory 
69323 ** cell in an array of values used as arguments to the sub-program. P2 
69324 ** contains the address to jump to if the sub-program throws an IGNORE 
69325 ** exception using the RAISE() function. Register P3 contains the address 
69326 ** of a memory cell in this (the parent) VM that is used to allocate the 
69327 ** memory required by the sub-vdbe at runtime.
69328 **
69329 ** P4 is a pointer to the VM containing the trigger program.
69330 */
69331 case OP_Program: {        /* jump */
69332 #if 0  /* local variables moved into u.cd */
69333   int nMem;               /* Number of memory registers for sub-program */
69334   int nByte;              /* Bytes of runtime space required for sub-program */
69335   Mem *pRt;               /* Register to allocate runtime space */
69336   Mem *pMem;              /* Used to iterate through memory cells */
69337   Mem *pEnd;              /* Last memory cell in new array */
69338   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
69339   SubProgram *pProgram;   /* Sub-program to execute */
69340   void *t;                /* Token identifying trigger */
69341 #endif /* local variables moved into u.cd */
69342
69343   u.cd.pProgram = pOp->p4.pProgram;
69344   u.cd.pRt = &aMem[pOp->p3];
69345   assert( u.cd.pProgram->nOp>0 );
69346
69347   /* If the p5 flag is clear, then recursive invocation of triggers is
69348   ** disabled for backwards compatibility (p5 is set if this sub-program
69349   ** is really a trigger, not a foreign key action, and the flag set
69350   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
69351   **
69352   ** It is recursive invocation of triggers, at the SQL level, that is
69353   ** disabled. In some cases a single trigger may generate more than one
69354   ** SubProgram (if the trigger may be executed with more than one different
69355   ** ON CONFLICT algorithm). SubProgram structures associated with a
69356   ** single trigger all have the same value for the SubProgram.token
69357   ** variable.  */
69358   if( pOp->p5 ){
69359     u.cd.t = u.cd.pProgram->token;
69360     for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
69361     if( u.cd.pFrame ) break;
69362   }
69363
69364   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
69365     rc = SQLITE_ERROR;
69366     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
69367     break;
69368   }
69369
69370   /* Register u.cd.pRt is used to store the memory required to save the state
69371   ** of the current program, and the memory required at runtime to execute
69372   ** the trigger program. If this trigger has been fired before, then u.cd.pRt
69373   ** is already allocated. Otherwise, it must be initialized.  */
69374   if( (u.cd.pRt->flags&MEM_Frame)==0 ){
69375     /* SubProgram.nMem is set to the number of memory cells used by the
69376     ** program stored in SubProgram.aOp. As well as these, one memory
69377     ** cell is required for each cursor used by the program. Set local
69378     ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
69379     */
69380     u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
69381     u.cd.nByte = ROUND8(sizeof(VdbeFrame))
69382               + u.cd.nMem * sizeof(Mem)
69383               + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
69384               + u.cd.pProgram->nOnce * sizeof(u8);
69385     u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
69386     if( !u.cd.pFrame ){
69387       goto no_mem;
69388     }
69389     sqlite3VdbeMemRelease(u.cd.pRt);
69390     u.cd.pRt->flags = MEM_Frame;
69391     u.cd.pRt->u.pFrame = u.cd.pFrame;
69392
69393     u.cd.pFrame->v = p;
69394     u.cd.pFrame->nChildMem = u.cd.nMem;
69395     u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
69396     u.cd.pFrame->pc = pc;
69397     u.cd.pFrame->aMem = p->aMem;
69398     u.cd.pFrame->nMem = p->nMem;
69399     u.cd.pFrame->apCsr = p->apCsr;
69400     u.cd.pFrame->nCursor = p->nCursor;
69401     u.cd.pFrame->aOp = p->aOp;
69402     u.cd.pFrame->nOp = p->nOp;
69403     u.cd.pFrame->token = u.cd.pProgram->token;
69404     u.cd.pFrame->aOnceFlag = p->aOnceFlag;
69405     u.cd.pFrame->nOnceFlag = p->nOnceFlag;
69406
69407     u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
69408     for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
69409       u.cd.pMem->flags = MEM_Invalid;
69410       u.cd.pMem->db = db;
69411     }
69412   }else{
69413     u.cd.pFrame = u.cd.pRt->u.pFrame;
69414     assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
69415     assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
69416     assert( pc==u.cd.pFrame->pc );
69417   }
69418
69419   p->nFrame++;
69420   u.cd.pFrame->pParent = p->pFrame;
69421   u.cd.pFrame->lastRowid = lastRowid;
69422   u.cd.pFrame->nChange = p->nChange;
69423   p->nChange = 0;
69424   p->pFrame = u.cd.pFrame;
69425   p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
69426   p->nMem = u.cd.pFrame->nChildMem;
69427   p->nCursor = (u16)u.cd.pFrame->nChildCsr;
69428   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
69429   p->aOp = aOp = u.cd.pProgram->aOp;
69430   p->nOp = u.cd.pProgram->nOp;
69431   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
69432   p->nOnceFlag = u.cd.pProgram->nOnce;
69433   pc = -1;
69434   memset(p->aOnceFlag, 0, p->nOnceFlag);
69435
69436   break;
69437 }
69438
69439 /* Opcode: Param P1 P2 * * *
69440 **
69441 ** This opcode is only ever present in sub-programs called via the 
69442 ** OP_Program instruction. Copy a value currently stored in a memory 
69443 ** cell of the calling (parent) frame to cell P2 in the current frames 
69444 ** address space. This is used by trigger programs to access the new.* 
69445 ** and old.* values.
69446 **
69447 ** The address of the cell in the parent frame is determined by adding
69448 ** the value of the P1 argument to the value of the P1 argument to the
69449 ** calling OP_Program instruction.
69450 */
69451 case OP_Param: {           /* out2-prerelease */
69452 #if 0  /* local variables moved into u.ce */
69453   VdbeFrame *pFrame;
69454   Mem *pIn;
69455 #endif /* local variables moved into u.ce */
69456   u.ce.pFrame = p->pFrame;
69457   u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
69458   sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
69459   break;
69460 }
69461
69462 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
69463
69464 #ifndef SQLITE_OMIT_FOREIGN_KEY
69465 /* Opcode: FkCounter P1 P2 * * *
69466 **
69467 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
69468 ** If P1 is non-zero, the database constraint counter is incremented 
69469 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
69470 ** statement counter is incremented (immediate foreign key constraints).
69471 */
69472 case OP_FkCounter: {
69473   if( pOp->p1 ){
69474     db->nDeferredCons += pOp->p2;
69475   }else{
69476     p->nFkConstraint += pOp->p2;
69477   }
69478   break;
69479 }
69480
69481 /* Opcode: FkIfZero P1 P2 * * *
69482 **
69483 ** This opcode tests if a foreign key constraint-counter is currently zero.
69484 ** If so, jump to instruction P2. Otherwise, fall through to the next 
69485 ** instruction.
69486 **
69487 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
69488 ** is zero (the one that counts deferred constraint violations). If P1 is
69489 ** zero, the jump is taken if the statement constraint-counter is zero
69490 ** (immediate foreign key constraint violations).
69491 */
69492 case OP_FkIfZero: {         /* jump */
69493   if( pOp->p1 ){
69494     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
69495   }else{
69496     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
69497   }
69498   break;
69499 }
69500 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
69501
69502 #ifndef SQLITE_OMIT_AUTOINCREMENT
69503 /* Opcode: MemMax P1 P2 * * *
69504 **
69505 ** P1 is a register in the root frame of this VM (the root frame is
69506 ** different from the current frame if this instruction is being executed
69507 ** within a sub-program). Set the value of register P1 to the maximum of 
69508 ** its current value and the value in register P2.
69509 **
69510 ** This instruction throws an error if the memory cell is not initially
69511 ** an integer.
69512 */
69513 case OP_MemMax: {        /* in2 */
69514 #if 0  /* local variables moved into u.cf */
69515   Mem *pIn1;
69516   VdbeFrame *pFrame;
69517 #endif /* local variables moved into u.cf */
69518   if( p->pFrame ){
69519     for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
69520     u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
69521   }else{
69522     u.cf.pIn1 = &aMem[pOp->p1];
69523   }
69524   assert( memIsValid(u.cf.pIn1) );
69525   sqlite3VdbeMemIntegerify(u.cf.pIn1);
69526   pIn2 = &aMem[pOp->p2];
69527   sqlite3VdbeMemIntegerify(pIn2);
69528   if( u.cf.pIn1->u.i<pIn2->u.i){
69529     u.cf.pIn1->u.i = pIn2->u.i;
69530   }
69531   break;
69532 }
69533 #endif /* SQLITE_OMIT_AUTOINCREMENT */
69534
69535 /* Opcode: IfPos P1 P2 * * *
69536 **
69537 ** If the value of register P1 is 1 or greater, jump to P2.
69538 **
69539 ** It is illegal to use this instruction on a register that does
69540 ** not contain an integer.  An assertion fault will result if you try.
69541 */
69542 case OP_IfPos: {        /* jump, in1 */
69543   pIn1 = &aMem[pOp->p1];
69544   assert( pIn1->flags&MEM_Int );
69545   if( pIn1->u.i>0 ){
69546      pc = pOp->p2 - 1;
69547   }
69548   break;
69549 }
69550
69551 /* Opcode: IfNeg P1 P2 * * *
69552 **
69553 ** If the value of register P1 is less than zero, jump to P2. 
69554 **
69555 ** It is illegal to use this instruction on a register that does
69556 ** not contain an integer.  An assertion fault will result if you try.
69557 */
69558 case OP_IfNeg: {        /* jump, in1 */
69559   pIn1 = &aMem[pOp->p1];
69560   assert( pIn1->flags&MEM_Int );
69561   if( pIn1->u.i<0 ){
69562      pc = pOp->p2 - 1;
69563   }
69564   break;
69565 }
69566
69567 /* Opcode: IfZero P1 P2 P3 * *
69568 **
69569 ** The register P1 must contain an integer.  Add literal P3 to the
69570 ** value in register P1.  If the result is exactly 0, jump to P2. 
69571 **
69572 ** It is illegal to use this instruction on a register that does
69573 ** not contain an integer.  An assertion fault will result if you try.
69574 */
69575 case OP_IfZero: {        /* jump, in1 */
69576   pIn1 = &aMem[pOp->p1];
69577   assert( pIn1->flags&MEM_Int );
69578   pIn1->u.i += pOp->p3;
69579   if( pIn1->u.i==0 ){
69580      pc = pOp->p2 - 1;
69581   }
69582   break;
69583 }
69584
69585 /* Opcode: AggStep * P2 P3 P4 P5
69586 **
69587 ** Execute the step function for an aggregate.  The
69588 ** function has P5 arguments.   P4 is a pointer to the FuncDef
69589 ** structure that specifies the function.  Use register
69590 ** P3 as the accumulator.
69591 **
69592 ** The P5 arguments are taken from register P2 and its
69593 ** successors.
69594 */
69595 case OP_AggStep: {
69596 #if 0  /* local variables moved into u.cg */
69597   int n;
69598   int i;
69599   Mem *pMem;
69600   Mem *pRec;
69601   sqlite3_context ctx;
69602   sqlite3_value **apVal;
69603 #endif /* local variables moved into u.cg */
69604
69605   u.cg.n = pOp->p5;
69606   assert( u.cg.n>=0 );
69607   u.cg.pRec = &aMem[pOp->p2];
69608   u.cg.apVal = p->apArg;
69609   assert( u.cg.apVal || u.cg.n==0 );
69610   for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
69611     assert( memIsValid(u.cg.pRec) );
69612     u.cg.apVal[u.cg.i] = u.cg.pRec;
69613     memAboutToChange(p, u.cg.pRec);
69614     sqlite3VdbeMemStoreType(u.cg.pRec);
69615   }
69616   u.cg.ctx.pFunc = pOp->p4.pFunc;
69617   assert( pOp->p3>0 && pOp->p3<=p->nMem );
69618   u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
69619   u.cg.pMem->n++;
69620   u.cg.ctx.s.flags = MEM_Null;
69621   u.cg.ctx.s.z = 0;
69622   u.cg.ctx.s.zMalloc = 0;
69623   u.cg.ctx.s.xDel = 0;
69624   u.cg.ctx.s.db = db;
69625   u.cg.ctx.isError = 0;
69626   u.cg.ctx.pColl = 0;
69627   u.cg.ctx.skipFlag = 0;
69628   if( u.cg.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
69629     assert( pOp>p->aOp );
69630     assert( pOp[-1].p4type==P4_COLLSEQ );
69631     assert( pOp[-1].opcode==OP_CollSeq );
69632     u.cg.ctx.pColl = pOp[-1].p4.pColl;
69633   }
69634   (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
69635   if( u.cg.ctx.isError ){
69636     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
69637     rc = u.cg.ctx.isError;
69638   }
69639   if( u.cg.ctx.skipFlag ){
69640     assert( pOp[-1].opcode==OP_CollSeq );
69641     u.cg.i = pOp[-1].p1;
69642     if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
69643   }
69644
69645   sqlite3VdbeMemRelease(&u.cg.ctx.s);
69646
69647   break;
69648 }
69649
69650 /* Opcode: AggFinal P1 P2 * P4 *
69651 **
69652 ** Execute the finalizer function for an aggregate.  P1 is
69653 ** the memory location that is the accumulator for the aggregate.
69654 **
69655 ** P2 is the number of arguments that the step function takes and
69656 ** P4 is a pointer to the FuncDef for this function.  The P2
69657 ** argument is not used by this opcode.  It is only there to disambiguate
69658 ** functions that can take varying numbers of arguments.  The
69659 ** P4 argument is only needed for the degenerate case where
69660 ** the step function was not previously called.
69661 */
69662 case OP_AggFinal: {
69663 #if 0  /* local variables moved into u.ch */
69664   Mem *pMem;
69665 #endif /* local variables moved into u.ch */
69666   assert( pOp->p1>0 && pOp->p1<=p->nMem );
69667   u.ch.pMem = &aMem[pOp->p1];
69668   assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
69669   rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
69670   if( rc ){
69671     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
69672   }
69673   sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
69674   UPDATE_MAX_BLOBSIZE(u.ch.pMem);
69675   if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
69676     goto too_big;
69677   }
69678   break;
69679 }
69680
69681 #ifndef SQLITE_OMIT_WAL
69682 /* Opcode: Checkpoint P1 P2 P3 * *
69683 **
69684 ** Checkpoint database P1. This is a no-op if P1 is not currently in
69685 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
69686 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
69687 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
69688 ** WAL after the checkpoint into mem[P3+1] and the number of pages
69689 ** in the WAL that have been checkpointed after the checkpoint
69690 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
69691 ** mem[P3+2] are initialized to -1.
69692 */
69693 case OP_Checkpoint: {
69694 #if 0  /* local variables moved into u.ci */
69695   int i;                          /* Loop counter */
69696   int aRes[3];                    /* Results */
69697   Mem *pMem;                      /* Write results here */
69698 #endif /* local variables moved into u.ci */
69699
69700   u.ci.aRes[0] = 0;
69701   u.ci.aRes[1] = u.ci.aRes[2] = -1;
69702   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
69703        || pOp->p2==SQLITE_CHECKPOINT_FULL
69704        || pOp->p2==SQLITE_CHECKPOINT_RESTART
69705   );
69706   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
69707   if( rc==SQLITE_BUSY ){
69708     rc = SQLITE_OK;
69709     u.ci.aRes[0] = 1;
69710   }
69711   for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
69712     sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
69713   }
69714   break;
69715 };  
69716 #endif
69717
69718 #ifndef SQLITE_OMIT_PRAGMA
69719 /* Opcode: JournalMode P1 P2 P3 * P5
69720 **
69721 ** Change the journal mode of database P1 to P3. P3 must be one of the
69722 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
69723 ** modes (delete, truncate, persist, off and memory), this is a simple
69724 ** operation. No IO is required.
69725 **
69726 ** If changing into or out of WAL mode the procedure is more complicated.
69727 **
69728 ** Write a string containing the final journal-mode to register P2.
69729 */
69730 case OP_JournalMode: {    /* out2-prerelease */
69731 #if 0  /* local variables moved into u.cj */
69732   Btree *pBt;                     /* Btree to change journal mode of */
69733   Pager *pPager;                  /* Pager associated with pBt */
69734   int eNew;                       /* New journal mode */
69735   int eOld;                       /* The old journal mode */
69736 #ifndef SQLITE_OMIT_WAL
69737   const char *zFilename;          /* Name of database file for pPager */
69738 #endif
69739 #endif /* local variables moved into u.cj */
69740
69741   u.cj.eNew = pOp->p3;
69742   assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
69743        || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
69744        || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
69745        || u.cj.eNew==PAGER_JOURNALMODE_OFF
69746        || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
69747        || u.cj.eNew==PAGER_JOURNALMODE_WAL
69748        || u.cj.eNew==PAGER_JOURNALMODE_QUERY
69749   );
69750   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69751
69752   u.cj.pBt = db->aDb[pOp->p1].pBt;
69753   u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
69754   u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
69755   if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
69756   if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
69757
69758 #ifndef SQLITE_OMIT_WAL
69759   u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
69760
69761   /* Do not allow a transition to journal_mode=WAL for a database
69762   ** in temporary storage or if the VFS does not support shared memory
69763   */
69764   if( u.cj.eNew==PAGER_JOURNALMODE_WAL
69765    && (sqlite3Strlen30(u.cj.zFilename)==0           /* Temp file */
69766        || !sqlite3PagerWalSupported(u.cj.pPager))   /* No shared-memory support */
69767   ){
69768     u.cj.eNew = u.cj.eOld;
69769   }
69770
69771   if( (u.cj.eNew!=u.cj.eOld)
69772    && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
69773   ){
69774     if( !db->autoCommit || db->activeVdbeCnt>1 ){
69775       rc = SQLITE_ERROR;
69776       sqlite3SetString(&p->zErrMsg, db,
69777           "cannot change %s wal mode from within a transaction",
69778           (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
69779       );
69780       break;
69781     }else{
69782
69783       if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
69784         /* If leaving WAL mode, close the log file. If successful, the call
69785         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
69786         ** file. An EXCLUSIVE lock may still be held on the database file
69787         ** after a successful return.
69788         */
69789         rc = sqlite3PagerCloseWal(u.cj.pPager);
69790         if( rc==SQLITE_OK ){
69791           sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
69792         }
69793       }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
69794         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
69795         ** as an intermediate */
69796         sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
69797       }
69798
69799       /* Open a transaction on the database file. Regardless of the journal
69800       ** mode, this transaction always uses a rollback journal.
69801       */
69802       assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
69803       if( rc==SQLITE_OK ){
69804         rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
69805       }
69806     }
69807   }
69808 #endif /* ifndef SQLITE_OMIT_WAL */
69809
69810   if( rc ){
69811     u.cj.eNew = u.cj.eOld;
69812   }
69813   u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
69814
69815   pOut = &aMem[pOp->p2];
69816   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
69817   pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
69818   pOut->n = sqlite3Strlen30(pOut->z);
69819   pOut->enc = SQLITE_UTF8;
69820   sqlite3VdbeChangeEncoding(pOut, encoding);
69821   break;
69822 };
69823 #endif /* SQLITE_OMIT_PRAGMA */
69824
69825 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
69826 /* Opcode: Vacuum * * * * *
69827 **
69828 ** Vacuum the entire database.  This opcode will cause other virtual
69829 ** machines to be created and run.  It may not be called from within
69830 ** a transaction.
69831 */
69832 case OP_Vacuum: {
69833   rc = sqlite3RunVacuum(&p->zErrMsg, db);
69834   break;
69835 }
69836 #endif
69837
69838 #if !defined(SQLITE_OMIT_AUTOVACUUM)
69839 /* Opcode: IncrVacuum P1 P2 * * *
69840 **
69841 ** Perform a single step of the incremental vacuum procedure on
69842 ** the P1 database. If the vacuum has finished, jump to instruction
69843 ** P2. Otherwise, fall through to the next instruction.
69844 */
69845 case OP_IncrVacuum: {        /* jump */
69846 #if 0  /* local variables moved into u.ck */
69847   Btree *pBt;
69848 #endif /* local variables moved into u.ck */
69849
69850   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69851   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69852   u.ck.pBt = db->aDb[pOp->p1].pBt;
69853   rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
69854   if( rc==SQLITE_DONE ){
69855     pc = pOp->p2 - 1;
69856     rc = SQLITE_OK;
69857   }
69858   break;
69859 }
69860 #endif
69861
69862 /* Opcode: Expire P1 * * * *
69863 **
69864 ** Cause precompiled statements to become expired. An expired statement
69865 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
69866 ** (via sqlite3_step()).
69867 ** 
69868 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
69869 ** then only the currently executing statement is affected. 
69870 */
69871 case OP_Expire: {
69872   if( !pOp->p1 ){
69873     sqlite3ExpirePreparedStatements(db);
69874   }else{
69875     p->expired = 1;
69876   }
69877   break;
69878 }
69879
69880 #ifndef SQLITE_OMIT_SHARED_CACHE
69881 /* Opcode: TableLock P1 P2 P3 P4 *
69882 **
69883 ** Obtain a lock on a particular table. This instruction is only used when
69884 ** the shared-cache feature is enabled. 
69885 **
69886 ** P1 is the index of the database in sqlite3.aDb[] of the database
69887 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
69888 ** a write lock if P3==1.
69889 **
69890 ** P2 contains the root-page of the table to lock.
69891 **
69892 ** P4 contains a pointer to the name of the table being locked. This is only
69893 ** used to generate an error message if the lock cannot be obtained.
69894 */
69895 case OP_TableLock: {
69896   u8 isWriteLock = (u8)pOp->p3;
69897   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
69898     int p1 = pOp->p1; 
69899     assert( p1>=0 && p1<db->nDb );
69900     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
69901     assert( isWriteLock==0 || isWriteLock==1 );
69902     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
69903     if( (rc&0xFF)==SQLITE_LOCKED ){
69904       const char *z = pOp->p4.z;
69905       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
69906     }
69907   }
69908   break;
69909 }
69910 #endif /* SQLITE_OMIT_SHARED_CACHE */
69911
69912 #ifndef SQLITE_OMIT_VIRTUALTABLE
69913 /* Opcode: VBegin * * * P4 *
69914 **
69915 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
69916 ** xBegin method for that table.
69917 **
69918 ** Also, whether or not P4 is set, check that this is not being called from
69919 ** within a callback to a virtual table xSync() method. If it is, the error
69920 ** code will be set to SQLITE_LOCKED.
69921 */
69922 case OP_VBegin: {
69923 #if 0  /* local variables moved into u.cl */
69924   VTable *pVTab;
69925 #endif /* local variables moved into u.cl */
69926   u.cl.pVTab = pOp->p4.pVtab;
69927   rc = sqlite3VtabBegin(db, u.cl.pVTab);
69928   if( u.cl.pVTab ) importVtabErrMsg(p, u.cl.pVTab->pVtab);
69929   break;
69930 }
69931 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69932
69933 #ifndef SQLITE_OMIT_VIRTUALTABLE
69934 /* Opcode: VCreate P1 * * P4 *
69935 **
69936 ** P4 is the name of a virtual table in database P1. Call the xCreate method
69937 ** for that table.
69938 */
69939 case OP_VCreate: {
69940   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
69941   break;
69942 }
69943 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69944
69945 #ifndef SQLITE_OMIT_VIRTUALTABLE
69946 /* Opcode: VDestroy P1 * * P4 *
69947 **
69948 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
69949 ** of that table.
69950 */
69951 case OP_VDestroy: {
69952   p->inVtabMethod = 2;
69953   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
69954   p->inVtabMethod = 0;
69955   break;
69956 }
69957 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69958
69959 #ifndef SQLITE_OMIT_VIRTUALTABLE
69960 /* Opcode: VOpen P1 * * P4 *
69961 **
69962 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
69963 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
69964 ** table and stores that cursor in P1.
69965 */
69966 case OP_VOpen: {
69967 #if 0  /* local variables moved into u.cm */
69968   VdbeCursor *pCur;
69969   sqlite3_vtab_cursor *pVtabCursor;
69970   sqlite3_vtab *pVtab;
69971   sqlite3_module *pModule;
69972 #endif /* local variables moved into u.cm */
69973
69974   u.cm.pCur = 0;
69975   u.cm.pVtabCursor = 0;
69976   u.cm.pVtab = pOp->p4.pVtab->pVtab;
69977   u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
69978   assert(u.cm.pVtab && u.cm.pModule);
69979   rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
69980   importVtabErrMsg(p, u.cm.pVtab);
69981   if( SQLITE_OK==rc ){
69982     /* Initialize sqlite3_vtab_cursor base class */
69983     u.cm.pVtabCursor->pVtab = u.cm.pVtab;
69984
69985     /* Initialize vdbe cursor object */
69986     u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
69987     if( u.cm.pCur ){
69988       u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
69989       u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
69990     }else{
69991       db->mallocFailed = 1;
69992       u.cm.pModule->xClose(u.cm.pVtabCursor);
69993     }
69994   }
69995   break;
69996 }
69997 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69998
69999 #ifndef SQLITE_OMIT_VIRTUALTABLE
70000 /* Opcode: VFilter P1 P2 P3 P4 *
70001 **
70002 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
70003 ** the filtered result set is empty.
70004 **
70005 ** P4 is either NULL or a string that was generated by the xBestIndex
70006 ** method of the module.  The interpretation of the P4 string is left
70007 ** to the module implementation.
70008 **
70009 ** This opcode invokes the xFilter method on the virtual table specified
70010 ** by P1.  The integer query plan parameter to xFilter is stored in register
70011 ** P3. Register P3+1 stores the argc parameter to be passed to the
70012 ** xFilter method. Registers P3+2..P3+1+argc are the argc
70013 ** additional parameters which are passed to
70014 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
70015 **
70016 ** A jump is made to P2 if the result set after filtering would be empty.
70017 */
70018 case OP_VFilter: {   /* jump */
70019 #if 0  /* local variables moved into u.cn */
70020   int nArg;
70021   int iQuery;
70022   const sqlite3_module *pModule;
70023   Mem *pQuery;
70024   Mem *pArgc;
70025   sqlite3_vtab_cursor *pVtabCursor;
70026   sqlite3_vtab *pVtab;
70027   VdbeCursor *pCur;
70028   int res;
70029   int i;
70030   Mem **apArg;
70031 #endif /* local variables moved into u.cn */
70032
70033   u.cn.pQuery = &aMem[pOp->p3];
70034   u.cn.pArgc = &u.cn.pQuery[1];
70035   u.cn.pCur = p->apCsr[pOp->p1];
70036   assert( memIsValid(u.cn.pQuery) );
70037   REGISTER_TRACE(pOp->p3, u.cn.pQuery);
70038   assert( u.cn.pCur->pVtabCursor );
70039   u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
70040   u.cn.pVtab = u.cn.pVtabCursor->pVtab;
70041   u.cn.pModule = u.cn.pVtab->pModule;
70042
70043   /* Grab the index number and argc parameters */
70044   assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
70045   u.cn.nArg = (int)u.cn.pArgc->u.i;
70046   u.cn.iQuery = (int)u.cn.pQuery->u.i;
70047
70048   /* Invoke the xFilter method */
70049   {
70050     u.cn.res = 0;
70051     u.cn.apArg = p->apArg;
70052     for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
70053       u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
70054       sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
70055     }
70056
70057     p->inVtabMethod = 1;
70058     rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
70059     p->inVtabMethod = 0;
70060     importVtabErrMsg(p, u.cn.pVtab);
70061     if( rc==SQLITE_OK ){
70062       u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
70063     }
70064
70065     if( u.cn.res ){
70066       pc = pOp->p2 - 1;
70067     }
70068   }
70069   u.cn.pCur->nullRow = 0;
70070
70071   break;
70072 }
70073 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70074
70075 #ifndef SQLITE_OMIT_VIRTUALTABLE
70076 /* Opcode: VColumn P1 P2 P3 * *
70077 **
70078 ** Store the value of the P2-th column of
70079 ** the row of the virtual-table that the 
70080 ** P1 cursor is pointing to into register P3.
70081 */
70082 case OP_VColumn: {
70083 #if 0  /* local variables moved into u.co */
70084   sqlite3_vtab *pVtab;
70085   const sqlite3_module *pModule;
70086   Mem *pDest;
70087   sqlite3_context sContext;
70088 #endif /* local variables moved into u.co */
70089
70090   VdbeCursor *pCur = p->apCsr[pOp->p1];
70091   assert( pCur->pVtabCursor );
70092   assert( pOp->p3>0 && pOp->p3<=p->nMem );
70093   u.co.pDest = &aMem[pOp->p3];
70094   memAboutToChange(p, u.co.pDest);
70095   if( pCur->nullRow ){
70096     sqlite3VdbeMemSetNull(u.co.pDest);
70097     break;
70098   }
70099   u.co.pVtab = pCur->pVtabCursor->pVtab;
70100   u.co.pModule = u.co.pVtab->pModule;
70101   assert( u.co.pModule->xColumn );
70102   memset(&u.co.sContext, 0, sizeof(u.co.sContext));
70103
70104   /* The output cell may already have a buffer allocated. Move
70105   ** the current contents to u.co.sContext.s so in case the user-function
70106   ** can use the already allocated buffer instead of allocating a
70107   ** new one.
70108   */
70109   sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
70110   MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
70111
70112   rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
70113   importVtabErrMsg(p, u.co.pVtab);
70114   if( u.co.sContext.isError ){
70115     rc = u.co.sContext.isError;
70116   }
70117
70118   /* Copy the result of the function to the P3 register. We
70119   ** do this regardless of whether or not an error occurred to ensure any
70120   ** dynamic allocation in u.co.sContext.s (a Mem struct) is  released.
70121   */
70122   sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
70123   sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
70124   REGISTER_TRACE(pOp->p3, u.co.pDest);
70125   UPDATE_MAX_BLOBSIZE(u.co.pDest);
70126
70127   if( sqlite3VdbeMemTooBig(u.co.pDest) ){
70128     goto too_big;
70129   }
70130   break;
70131 }
70132 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70133
70134 #ifndef SQLITE_OMIT_VIRTUALTABLE
70135 /* Opcode: VNext P1 P2 * * *
70136 **
70137 ** Advance virtual table P1 to the next row in its result set and
70138 ** jump to instruction P2.  Or, if the virtual table has reached
70139 ** the end of its result set, then fall through to the next instruction.
70140 */
70141 case OP_VNext: {   /* jump */
70142 #if 0  /* local variables moved into u.cp */
70143   sqlite3_vtab *pVtab;
70144   const sqlite3_module *pModule;
70145   int res;
70146   VdbeCursor *pCur;
70147 #endif /* local variables moved into u.cp */
70148
70149   u.cp.res = 0;
70150   u.cp.pCur = p->apCsr[pOp->p1];
70151   assert( u.cp.pCur->pVtabCursor );
70152   if( u.cp.pCur->nullRow ){
70153     break;
70154   }
70155   u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
70156   u.cp.pModule = u.cp.pVtab->pModule;
70157   assert( u.cp.pModule->xNext );
70158
70159   /* Invoke the xNext() method of the module. There is no way for the
70160   ** underlying implementation to return an error if one occurs during
70161   ** xNext(). Instead, if an error occurs, true is returned (indicating that
70162   ** data is available) and the error code returned when xColumn or
70163   ** some other method is next invoked on the save virtual table cursor.
70164   */
70165   p->inVtabMethod = 1;
70166   rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
70167   p->inVtabMethod = 0;
70168   importVtabErrMsg(p, u.cp.pVtab);
70169   if( rc==SQLITE_OK ){
70170     u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
70171   }
70172
70173   if( !u.cp.res ){
70174     /* If there is data, jump to P2 */
70175     pc = pOp->p2 - 1;
70176   }
70177   break;
70178 }
70179 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70180
70181 #ifndef SQLITE_OMIT_VIRTUALTABLE
70182 /* Opcode: VRename P1 * * P4 *
70183 **
70184 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
70185 ** This opcode invokes the corresponding xRename method. The value
70186 ** in register P1 is passed as the zName argument to the xRename method.
70187 */
70188 case OP_VRename: {
70189 #if 0  /* local variables moved into u.cq */
70190   sqlite3_vtab *pVtab;
70191   Mem *pName;
70192 #endif /* local variables moved into u.cq */
70193
70194   u.cq.pVtab = pOp->p4.pVtab->pVtab;
70195   u.cq.pName = &aMem[pOp->p1];
70196   assert( u.cq.pVtab->pModule->xRename );
70197   assert( memIsValid(u.cq.pName) );
70198   REGISTER_TRACE(pOp->p1, u.cq.pName);
70199   assert( u.cq.pName->flags & MEM_Str );
70200   testcase( u.cq.pName->enc==SQLITE_UTF8 );
70201   testcase( u.cq.pName->enc==SQLITE_UTF16BE );
70202   testcase( u.cq.pName->enc==SQLITE_UTF16LE );
70203   rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
70204   if( rc==SQLITE_OK ){
70205     rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
70206     importVtabErrMsg(p, u.cq.pVtab);
70207     p->expired = 0;
70208   }
70209   break;
70210 }
70211 #endif
70212
70213 #ifndef SQLITE_OMIT_VIRTUALTABLE
70214 /* Opcode: VUpdate P1 P2 P3 P4 *
70215 **
70216 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
70217 ** This opcode invokes the corresponding xUpdate method. P2 values
70218 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
70219 ** invocation. The value in register (P3+P2-1) corresponds to the 
70220 ** p2th element of the argv array passed to xUpdate.
70221 **
70222 ** The xUpdate method will do a DELETE or an INSERT or both.
70223 ** The argv[0] element (which corresponds to memory cell P3)
70224 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
70225 ** deletion occurs.  The argv[1] element is the rowid of the new 
70226 ** row.  This can be NULL to have the virtual table select the new 
70227 ** rowid for itself.  The subsequent elements in the array are 
70228 ** the values of columns in the new row.
70229 **
70230 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
70231 ** a row to delete.
70232 **
70233 ** P1 is a boolean flag. If it is set to true and the xUpdate call
70234 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
70235 ** is set to the value of the rowid for the row just inserted.
70236 */
70237 case OP_VUpdate: {
70238 #if 0  /* local variables moved into u.cr */
70239   sqlite3_vtab *pVtab;
70240   sqlite3_module *pModule;
70241   int nArg;
70242   int i;
70243   sqlite_int64 rowid;
70244   Mem **apArg;
70245   Mem *pX;
70246 #endif /* local variables moved into u.cr */
70247
70248   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
70249        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
70250   );
70251   u.cr.pVtab = pOp->p4.pVtab->pVtab;
70252   u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
70253   u.cr.nArg = pOp->p2;
70254   assert( pOp->p4type==P4_VTAB );
70255   if( ALWAYS(u.cr.pModule->xUpdate) ){
70256     u8 vtabOnConflict = db->vtabOnConflict;
70257     u.cr.apArg = p->apArg;
70258     u.cr.pX = &aMem[pOp->p3];
70259     for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
70260       assert( memIsValid(u.cr.pX) );
70261       memAboutToChange(p, u.cr.pX);
70262       sqlite3VdbeMemStoreType(u.cr.pX);
70263       u.cr.apArg[u.cr.i] = u.cr.pX;
70264       u.cr.pX++;
70265     }
70266     db->vtabOnConflict = pOp->p5;
70267     rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
70268     db->vtabOnConflict = vtabOnConflict;
70269     importVtabErrMsg(p, u.cr.pVtab);
70270     if( rc==SQLITE_OK && pOp->p1 ){
70271       assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
70272       db->lastRowid = lastRowid = u.cr.rowid;
70273     }
70274     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
70275       if( pOp->p5==OE_Ignore ){
70276         rc = SQLITE_OK;
70277       }else{
70278         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
70279       }
70280     }else{
70281       p->nChange++;
70282     }
70283   }
70284   break;
70285 }
70286 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70287
70288 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
70289 /* Opcode: Pagecount P1 P2 * * *
70290 **
70291 ** Write the current number of pages in database P1 to memory cell P2.
70292 */
70293 case OP_Pagecount: {            /* out2-prerelease */
70294   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
70295   break;
70296 }
70297 #endif
70298
70299
70300 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
70301 /* Opcode: MaxPgcnt P1 P2 P3 * *
70302 **
70303 ** Try to set the maximum page count for database P1 to the value in P3.
70304 ** Do not let the maximum page count fall below the current page count and
70305 ** do not change the maximum page count value if P3==0.
70306 **
70307 ** Store the maximum page count after the change in register P2.
70308 */
70309 case OP_MaxPgcnt: {            /* out2-prerelease */
70310   unsigned int newMax;
70311   Btree *pBt;
70312
70313   pBt = db->aDb[pOp->p1].pBt;
70314   newMax = 0;
70315   if( pOp->p3 ){
70316     newMax = sqlite3BtreeLastPage(pBt);
70317     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
70318   }
70319   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
70320   break;
70321 }
70322 #endif
70323
70324
70325 #ifndef SQLITE_OMIT_TRACE
70326 /* Opcode: Trace * * * P4 *
70327 **
70328 ** If tracing is enabled (by the sqlite3_trace()) interface, then
70329 ** the UTF-8 string contained in P4 is emitted on the trace callback.
70330 */
70331 case OP_Trace: {
70332 #if 0  /* local variables moved into u.cs */
70333   char *zTrace;
70334   char *z;
70335 #endif /* local variables moved into u.cs */
70336
70337   if( db->xTrace
70338    && !p->doingRerun
70339    && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
70340   ){
70341     u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
70342     db->xTrace(db->pTraceArg, u.cs.z);
70343     sqlite3DbFree(db, u.cs.z);
70344   }
70345 #ifdef SQLITE_DEBUG
70346   if( (db->flags & SQLITE_SqlTrace)!=0
70347    && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
70348   ){
70349     sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
70350   }
70351 #endif /* SQLITE_DEBUG */
70352   break;
70353 }
70354 #endif
70355
70356
70357 /* Opcode: Noop * * * * *
70358 **
70359 ** Do nothing.  This instruction is often useful as a jump
70360 ** destination.
70361 */
70362 /*
70363 ** The magic Explain opcode are only inserted when explain==2 (which
70364 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
70365 ** This opcode records information from the optimizer.  It is the
70366 ** the same as a no-op.  This opcodesnever appears in a real VM program.
70367 */
70368 default: {          /* This is really OP_Noop and OP_Explain */
70369   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
70370   break;
70371 }
70372
70373 /*****************************************************************************
70374 ** The cases of the switch statement above this line should all be indented
70375 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
70376 ** readability.  From this point on down, the normal indentation rules are
70377 ** restored.
70378 *****************************************************************************/
70379     }
70380
70381 #ifdef VDBE_PROFILE
70382     {
70383       u64 elapsed = sqlite3Hwtime() - start;
70384       pOp->cycles += elapsed;
70385       pOp->cnt++;
70386 #if 0
70387         fprintf(stdout, "%10llu ", elapsed);
70388         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
70389 #endif
70390     }
70391 #endif
70392
70393     /* The following code adds nothing to the actual functionality
70394     ** of the program.  It is only here for testing and debugging.
70395     ** On the other hand, it does burn CPU cycles every time through
70396     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
70397     */
70398 #ifndef NDEBUG
70399     assert( pc>=-1 && pc<p->nOp );
70400
70401 #ifdef SQLITE_DEBUG
70402     if( p->trace ){
70403       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
70404       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
70405         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
70406       }
70407       if( pOp->opflags & OPFLG_OUT3 ){
70408         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
70409       }
70410     }
70411 #endif  /* SQLITE_DEBUG */
70412 #endif  /* NDEBUG */
70413   }  /* The end of the for(;;) loop the loops through opcodes */
70414
70415   /* If we reach this point, it means that execution is finished with
70416   ** an error of some kind.
70417   */
70418 vdbe_error_halt:
70419   assert( rc );
70420   p->rc = rc;
70421   testcase( sqlite3GlobalConfig.xLog!=0 );
70422   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
70423                    pc, p->zSql, p->zErrMsg);
70424   sqlite3VdbeHalt(p);
70425   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
70426   rc = SQLITE_ERROR;
70427   if( resetSchemaOnFault>0 ){
70428     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
70429   }
70430
70431   /* This is the only way out of this procedure.  We have to
70432   ** release the mutexes on btrees that were acquired at the
70433   ** top. */
70434 vdbe_return:
70435   db->lastRowid = lastRowid;
70436   sqlite3VdbeLeave(p);
70437   return rc;
70438
70439   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
70440   ** is encountered.
70441   */
70442 too_big:
70443   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
70444   rc = SQLITE_TOOBIG;
70445   goto vdbe_error_halt;
70446
70447   /* Jump to here if a malloc() fails.
70448   */
70449 no_mem:
70450   db->mallocFailed = 1;
70451   sqlite3SetString(&p->zErrMsg, db, "out of memory");
70452   rc = SQLITE_NOMEM;
70453   goto vdbe_error_halt;
70454
70455   /* Jump to here for any other kind of fatal error.  The "rc" variable
70456   ** should hold the error number.
70457   */
70458 abort_due_to_error:
70459   assert( p->zErrMsg==0 );
70460   if( db->mallocFailed ) rc = SQLITE_NOMEM;
70461   if( rc!=SQLITE_IOERR_NOMEM ){
70462     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
70463   }
70464   goto vdbe_error_halt;
70465
70466   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
70467   ** flag.
70468   */
70469 abort_due_to_interrupt:
70470   assert( db->u1.isInterrupted );
70471   rc = SQLITE_INTERRUPT;
70472   p->rc = rc;
70473   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
70474   goto vdbe_error_halt;
70475 }
70476
70477 /************** End of vdbe.c ************************************************/
70478 /************** Begin file vdbeblob.c ****************************************/
70479 /*
70480 ** 2007 May 1
70481 **
70482 ** The author disclaims copyright to this source code.  In place of
70483 ** a legal notice, here is a blessing:
70484 **
70485 **    May you do good and not evil.
70486 **    May you find forgiveness for yourself and forgive others.
70487 **    May you share freely, never taking more than you give.
70488 **
70489 *************************************************************************
70490 **
70491 ** This file contains code used to implement incremental BLOB I/O.
70492 */
70493
70494
70495 #ifndef SQLITE_OMIT_INCRBLOB
70496
70497 /*
70498 ** Valid sqlite3_blob* handles point to Incrblob structures.
70499 */
70500 typedef struct Incrblob Incrblob;
70501 struct Incrblob {
70502   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
70503   int nByte;              /* Size of open blob, in bytes */
70504   int iOffset;            /* Byte offset of blob in cursor data */
70505   int iCol;               /* Table column this handle is open on */
70506   BtCursor *pCsr;         /* Cursor pointing at blob row */
70507   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
70508   sqlite3 *db;            /* The associated database */
70509 };
70510
70511
70512 /*
70513 ** This function is used by both blob_open() and blob_reopen(). It seeks
70514 ** the b-tree cursor associated with blob handle p to point to row iRow.
70515 ** If successful, SQLITE_OK is returned and subsequent calls to
70516 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
70517 **
70518 ** If an error occurs, or if the specified row does not exist or does not
70519 ** contain a value of type TEXT or BLOB in the column nominated when the
70520 ** blob handle was opened, then an error code is returned and *pzErr may
70521 ** be set to point to a buffer containing an error message. It is the
70522 ** responsibility of the caller to free the error message buffer using
70523 ** sqlite3DbFree().
70524 **
70525 ** If an error does occur, then the b-tree cursor is closed. All subsequent
70526 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
70527 ** immediately return SQLITE_ABORT.
70528 */
70529 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
70530   int rc;                         /* Error code */
70531   char *zErr = 0;                 /* Error message */
70532   Vdbe *v = (Vdbe *)p->pStmt;
70533
70534   /* Set the value of the SQL statements only variable to integer iRow. 
70535   ** This is done directly instead of using sqlite3_bind_int64() to avoid 
70536   ** triggering asserts related to mutexes.
70537   */
70538   assert( v->aVar[0].flags&MEM_Int );
70539   v->aVar[0].u.i = iRow;
70540
70541   rc = sqlite3_step(p->pStmt);
70542   if( rc==SQLITE_ROW ){
70543     u32 type = v->apCsr[0]->aType[p->iCol];
70544     if( type<12 ){
70545       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
70546           type==0?"null": type==7?"real": "integer"
70547       );
70548       rc = SQLITE_ERROR;
70549       sqlite3_finalize(p->pStmt);
70550       p->pStmt = 0;
70551     }else{
70552       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
70553       p->nByte = sqlite3VdbeSerialTypeLen(type);
70554       p->pCsr =  v->apCsr[0]->pCursor;
70555       sqlite3BtreeEnterCursor(p->pCsr);
70556       sqlite3BtreeCacheOverflow(p->pCsr);
70557       sqlite3BtreeLeaveCursor(p->pCsr);
70558     }
70559   }
70560
70561   if( rc==SQLITE_ROW ){
70562     rc = SQLITE_OK;
70563   }else if( p->pStmt ){
70564     rc = sqlite3_finalize(p->pStmt);
70565     p->pStmt = 0;
70566     if( rc==SQLITE_OK ){
70567       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
70568       rc = SQLITE_ERROR;
70569     }else{
70570       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
70571     }
70572   }
70573
70574   assert( rc!=SQLITE_OK || zErr==0 );
70575   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
70576
70577   *pzErr = zErr;
70578   return rc;
70579 }
70580
70581 /*
70582 ** Open a blob handle.
70583 */
70584 SQLITE_API int sqlite3_blob_open(
70585   sqlite3* db,            /* The database connection */
70586   const char *zDb,        /* The attached database containing the blob */
70587   const char *zTable,     /* The table containing the blob */
70588   const char *zColumn,    /* The column containing the blob */
70589   sqlite_int64 iRow,      /* The row containing the glob */
70590   int flags,              /* True -> read/write access, false -> read-only */
70591   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
70592 ){
70593   int nAttempt = 0;
70594   int iCol;               /* Index of zColumn in row-record */
70595
70596   /* This VDBE program seeks a btree cursor to the identified 
70597   ** db/table/row entry. The reason for using a vdbe program instead
70598   ** of writing code to use the b-tree layer directly is that the
70599   ** vdbe program will take advantage of the various transaction,
70600   ** locking and error handling infrastructure built into the vdbe.
70601   **
70602   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
70603   ** Code external to the Vdbe then "borrows" the b-tree cursor and
70604   ** uses it to implement the blob_read(), blob_write() and 
70605   ** blob_bytes() functions.
70606   **
70607   ** The sqlite3_blob_close() function finalizes the vdbe program,
70608   ** which closes the b-tree cursor and (possibly) commits the 
70609   ** transaction.
70610   */
70611   static const VdbeOpList openBlob[] = {
70612     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
70613     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
70614     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
70615
70616     /* One of the following two instructions is replaced by an OP_Noop. */
70617     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
70618     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
70619
70620     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
70621     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
70622     {OP_Column, 0, 0, 1},          /* 7  */
70623     {OP_ResultRow, 1, 0, 0},       /* 8  */
70624     {OP_Goto, 0, 5, 0},            /* 9  */
70625     {OP_Close, 0, 0, 0},           /* 10 */
70626     {OP_Halt, 0, 0, 0},            /* 11 */
70627   };
70628
70629   int rc = SQLITE_OK;
70630   char *zErr = 0;
70631   Table *pTab;
70632   Parse *pParse = 0;
70633   Incrblob *pBlob = 0;
70634
70635   flags = !!flags;                /* flags = (flags ? 1 : 0); */
70636   *ppBlob = 0;
70637
70638   sqlite3_mutex_enter(db->mutex);
70639
70640   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
70641   if( !pBlob ) goto blob_open_out;
70642   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
70643   if( !pParse ) goto blob_open_out;
70644
70645   do {
70646     memset(pParse, 0, sizeof(Parse));
70647     pParse->db = db;
70648     sqlite3DbFree(db, zErr);
70649     zErr = 0;
70650
70651     sqlite3BtreeEnterAll(db);
70652     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
70653     if( pTab && IsVirtual(pTab) ){
70654       pTab = 0;
70655       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
70656     }
70657 #ifndef SQLITE_OMIT_VIEW
70658     if( pTab && pTab->pSelect ){
70659       pTab = 0;
70660       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
70661     }
70662 #endif
70663     if( !pTab ){
70664       if( pParse->zErrMsg ){
70665         sqlite3DbFree(db, zErr);
70666         zErr = pParse->zErrMsg;
70667         pParse->zErrMsg = 0;
70668       }
70669       rc = SQLITE_ERROR;
70670       sqlite3BtreeLeaveAll(db);
70671       goto blob_open_out;
70672     }
70673
70674     /* Now search pTab for the exact column. */
70675     for(iCol=0; iCol<pTab->nCol; iCol++) {
70676       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
70677         break;
70678       }
70679     }
70680     if( iCol==pTab->nCol ){
70681       sqlite3DbFree(db, zErr);
70682       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
70683       rc = SQLITE_ERROR;
70684       sqlite3BtreeLeaveAll(db);
70685       goto blob_open_out;
70686     }
70687
70688     /* If the value is being opened for writing, check that the
70689     ** column is not indexed, and that it is not part of a foreign key. 
70690     ** It is against the rules to open a column to which either of these
70691     ** descriptions applies for writing.  */
70692     if( flags ){
70693       const char *zFault = 0;
70694       Index *pIdx;
70695 #ifndef SQLITE_OMIT_FOREIGN_KEY
70696       if( db->flags&SQLITE_ForeignKeys ){
70697         /* Check that the column is not part of an FK child key definition. It
70698         ** is not necessary to check if it is part of a parent key, as parent
70699         ** key columns must be indexed. The check below will pick up this 
70700         ** case.  */
70701         FKey *pFKey;
70702         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
70703           int j;
70704           for(j=0; j<pFKey->nCol; j++){
70705             if( pFKey->aCol[j].iFrom==iCol ){
70706               zFault = "foreign key";
70707             }
70708           }
70709         }
70710       }
70711 #endif
70712       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70713         int j;
70714         for(j=0; j<pIdx->nColumn; j++){
70715           if( pIdx->aiColumn[j]==iCol ){
70716             zFault = "indexed";
70717           }
70718         }
70719       }
70720       if( zFault ){
70721         sqlite3DbFree(db, zErr);
70722         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
70723         rc = SQLITE_ERROR;
70724         sqlite3BtreeLeaveAll(db);
70725         goto blob_open_out;
70726       }
70727     }
70728
70729     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
70730     assert( pBlob->pStmt || db->mallocFailed );
70731     if( pBlob->pStmt ){
70732       Vdbe *v = (Vdbe *)pBlob->pStmt;
70733       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70734
70735       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
70736
70737
70738       /* Configure the OP_Transaction */
70739       sqlite3VdbeChangeP1(v, 0, iDb);
70740       sqlite3VdbeChangeP2(v, 0, flags);
70741
70742       /* Configure the OP_VerifyCookie */
70743       sqlite3VdbeChangeP1(v, 1, iDb);
70744       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
70745       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
70746
70747       /* Make sure a mutex is held on the table to be accessed */
70748       sqlite3VdbeUsesBtree(v, iDb); 
70749
70750       /* Configure the OP_TableLock instruction */
70751 #ifdef SQLITE_OMIT_SHARED_CACHE
70752       sqlite3VdbeChangeToNoop(v, 2);
70753 #else
70754       sqlite3VdbeChangeP1(v, 2, iDb);
70755       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
70756       sqlite3VdbeChangeP3(v, 2, flags);
70757       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
70758 #endif
70759
70760       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
70761       ** parameter of the other to pTab->tnum.  */
70762       sqlite3VdbeChangeToNoop(v, 4 - flags);
70763       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
70764       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
70765
70766       /* Configure the number of columns. Configure the cursor to
70767       ** think that the table has one more column than it really
70768       ** does. An OP_Column to retrieve this imaginary column will
70769       ** always return an SQL NULL. This is useful because it means
70770       ** we can invoke OP_Column to fill in the vdbe cursors type 
70771       ** and offset cache without causing any IO.
70772       */
70773       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
70774       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
70775       if( !db->mallocFailed ){
70776         pParse->nVar = 1;
70777         pParse->nMem = 1;
70778         pParse->nTab = 1;
70779         sqlite3VdbeMakeReady(v, pParse);
70780       }
70781     }
70782    
70783     pBlob->flags = flags;
70784     pBlob->iCol = iCol;
70785     pBlob->db = db;
70786     sqlite3BtreeLeaveAll(db);
70787     if( db->mallocFailed ){
70788       goto blob_open_out;
70789     }
70790     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
70791     rc = blobSeekToRow(pBlob, iRow, &zErr);
70792   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
70793
70794 blob_open_out:
70795   if( rc==SQLITE_OK && db->mallocFailed==0 ){
70796     *ppBlob = (sqlite3_blob *)pBlob;
70797   }else{
70798     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
70799     sqlite3DbFree(db, pBlob);
70800   }
70801   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
70802   sqlite3DbFree(db, zErr);
70803   sqlite3StackFree(db, pParse);
70804   rc = sqlite3ApiExit(db, rc);
70805   sqlite3_mutex_leave(db->mutex);
70806   return rc;
70807 }
70808
70809 /*
70810 ** Close a blob handle that was previously created using
70811 ** sqlite3_blob_open().
70812 */
70813 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
70814   Incrblob *p = (Incrblob *)pBlob;
70815   int rc;
70816   sqlite3 *db;
70817
70818   if( p ){
70819     db = p->db;
70820     sqlite3_mutex_enter(db->mutex);
70821     rc = sqlite3_finalize(p->pStmt);
70822     sqlite3DbFree(db, p);
70823     sqlite3_mutex_leave(db->mutex);
70824   }else{
70825     rc = SQLITE_OK;
70826   }
70827   return rc;
70828 }
70829
70830 /*
70831 ** Perform a read or write operation on a blob
70832 */
70833 static int blobReadWrite(
70834   sqlite3_blob *pBlob, 
70835   void *z, 
70836   int n, 
70837   int iOffset, 
70838   int (*xCall)(BtCursor*, u32, u32, void*)
70839 ){
70840   int rc;
70841   Incrblob *p = (Incrblob *)pBlob;
70842   Vdbe *v;
70843   sqlite3 *db;
70844
70845   if( p==0 ) return SQLITE_MISUSE_BKPT;
70846   db = p->db;
70847   sqlite3_mutex_enter(db->mutex);
70848   v = (Vdbe*)p->pStmt;
70849
70850   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
70851     /* Request is out of range. Return a transient error. */
70852     rc = SQLITE_ERROR;
70853     sqlite3Error(db, SQLITE_ERROR, 0);
70854   }else if( v==0 ){
70855     /* If there is no statement handle, then the blob-handle has
70856     ** already been invalidated. Return SQLITE_ABORT in this case.
70857     */
70858     rc = SQLITE_ABORT;
70859   }else{
70860     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
70861     ** returned, clean-up the statement handle.
70862     */
70863     assert( db == v->db );
70864     sqlite3BtreeEnterCursor(p->pCsr);
70865     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
70866     sqlite3BtreeLeaveCursor(p->pCsr);
70867     if( rc==SQLITE_ABORT ){
70868       sqlite3VdbeFinalize(v);
70869       p->pStmt = 0;
70870     }else{
70871       db->errCode = rc;
70872       v->rc = rc;
70873     }
70874   }
70875   rc = sqlite3ApiExit(db, rc);
70876   sqlite3_mutex_leave(db->mutex);
70877   return rc;
70878 }
70879
70880 /*
70881 ** Read data from a blob handle.
70882 */
70883 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
70884   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
70885 }
70886
70887 /*
70888 ** Write data to a blob handle.
70889 */
70890 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
70891   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
70892 }
70893
70894 /*
70895 ** Query a blob handle for the size of the data.
70896 **
70897 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
70898 ** so no mutex is required for access.
70899 */
70900 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
70901   Incrblob *p = (Incrblob *)pBlob;
70902   return (p && p->pStmt) ? p->nByte : 0;
70903 }
70904
70905 /*
70906 ** Move an existing blob handle to point to a different row of the same
70907 ** database table.
70908 **
70909 ** If an error occurs, or if the specified row does not exist or does not
70910 ** contain a blob or text value, then an error code is returned and the
70911 ** database handle error code and message set. If this happens, then all 
70912 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
70913 ** immediately return SQLITE_ABORT.
70914 */
70915 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
70916   int rc;
70917   Incrblob *p = (Incrblob *)pBlob;
70918   sqlite3 *db;
70919
70920   if( p==0 ) return SQLITE_MISUSE_BKPT;
70921   db = p->db;
70922   sqlite3_mutex_enter(db->mutex);
70923
70924   if( p->pStmt==0 ){
70925     /* If there is no statement handle, then the blob-handle has
70926     ** already been invalidated. Return SQLITE_ABORT in this case.
70927     */
70928     rc = SQLITE_ABORT;
70929   }else{
70930     char *zErr;
70931     rc = blobSeekToRow(p, iRow, &zErr);
70932     if( rc!=SQLITE_OK ){
70933       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
70934       sqlite3DbFree(db, zErr);
70935     }
70936     assert( rc!=SQLITE_SCHEMA );
70937   }
70938
70939   rc = sqlite3ApiExit(db, rc);
70940   assert( rc==SQLITE_OK || p->pStmt==0 );
70941   sqlite3_mutex_leave(db->mutex);
70942   return rc;
70943 }
70944
70945 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
70946
70947 /************** End of vdbeblob.c ********************************************/
70948 /************** Begin file vdbesort.c ****************************************/
70949 /*
70950 ** 2011 July 9
70951 **
70952 ** The author disclaims copyright to this source code.  In place of
70953 ** a legal notice, here is a blessing:
70954 **
70955 **    May you do good and not evil.
70956 **    May you find forgiveness for yourself and forgive others.
70957 **    May you share freely, never taking more than you give.
70958 **
70959 *************************************************************************
70960 ** This file contains code for the VdbeSorter object, used in concert with
70961 ** a VdbeCursor to sort large numbers of keys (as may be required, for
70962 ** example, by CREATE INDEX statements on tables too large to fit in main
70963 ** memory).
70964 */
70965
70966
70967
70968 typedef struct VdbeSorterIter VdbeSorterIter;
70969 typedef struct SorterRecord SorterRecord;
70970 typedef struct FileWriter FileWriter;
70971
70972 /*
70973 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
70974 **
70975 ** As keys are added to the sorter, they are written to disk in a series
70976 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
70977 ** the same as the cache-size allowed for temporary databases. In order
70978 ** to allow the caller to extract keys from the sorter in sorted order,
70979 ** all PMAs currently stored on disk must be merged together. This comment
70980 ** describes the data structure used to do so. The structure supports 
70981 ** merging any number of arrays in a single pass with no redundant comparison 
70982 ** operations.
70983 **
70984 ** The aIter[] array contains an iterator for each of the PMAs being merged.
70985 ** An aIter[] iterator either points to a valid key or else is at EOF. For 
70986 ** the purposes of the paragraphs below, we assume that the array is actually 
70987 ** N elements in size, where N is the smallest power of 2 greater to or equal 
70988 ** to the number of iterators being merged. The extra aIter[] elements are 
70989 ** treated as if they are empty (always at EOF).
70990 **
70991 ** The aTree[] array is also N elements in size. The value of N is stored in
70992 ** the VdbeSorter.nTree variable.
70993 **
70994 ** The final (N/2) elements of aTree[] contain the results of comparing
70995 ** pairs of iterator keys together. Element i contains the result of 
70996 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
70997 ** aTree element is set to the index of it. 
70998 **
70999 ** For the purposes of this comparison, EOF is considered greater than any
71000 ** other key value. If the keys are equal (only possible with two EOF
71001 ** values), it doesn't matter which index is stored.
71002 **
71003 ** The (N/4) elements of aTree[] that preceed the final (N/2) described 
71004 ** above contains the index of the smallest of each block of 4 iterators.
71005 ** And so on. So that aTree[1] contains the index of the iterator that 
71006 ** currently points to the smallest key value. aTree[0] is unused.
71007 **
71008 ** Example:
71009 **
71010 **     aIter[0] -> Banana
71011 **     aIter[1] -> Feijoa
71012 **     aIter[2] -> Elderberry
71013 **     aIter[3] -> Currant
71014 **     aIter[4] -> Grapefruit
71015 **     aIter[5] -> Apple
71016 **     aIter[6] -> Durian
71017 **     aIter[7] -> EOF
71018 **
71019 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
71020 **
71021 ** The current element is "Apple" (the value of the key indicated by 
71022 ** iterator 5). When the Next() operation is invoked, iterator 5 will
71023 ** be advanced to the next key in its segment. Say the next key is
71024 ** "Eggplant":
71025 **
71026 **     aIter[5] -> Eggplant
71027 **
71028 ** The contents of aTree[] are updated first by comparing the new iterator
71029 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
71030 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
71031 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
71032 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
71033 ** so the value written into element 1 of the array is 0. As follows:
71034 **
71035 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
71036 **
71037 ** In other words, each time we advance to the next sorter element, log2(N)
71038 ** key comparison operations are required, where N is the number of segments
71039 ** being merged (rounded up to the next power of 2).
71040 */
71041 struct VdbeSorter {
71042   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
71043   i64 iReadOff;                   /* Current read offset within file pTemp1 */
71044   int nInMemory;                  /* Current size of pRecord list as PMA */
71045   int nTree;                      /* Used size of aTree/aIter (power of 2) */
71046   int nPMA;                       /* Number of PMAs stored in pTemp1 */
71047   int mnPmaSize;                  /* Minimum PMA size, in bytes */
71048   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
71049   VdbeSorterIter *aIter;          /* Array of iterators to merge */
71050   int *aTree;                     /* Current state of incremental merge */
71051   sqlite3_file *pTemp1;           /* PMA file 1 */
71052   SorterRecord *pRecord;          /* Head of in-memory record list */
71053   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
71054 };
71055
71056 /*
71057 ** The following type is an iterator for a PMA. It caches the current key in 
71058 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
71059 */
71060 struct VdbeSorterIter {
71061   i64 iReadOff;                   /* Current read offset */
71062   i64 iEof;                       /* 1 byte past EOF for this iterator */
71063   int nAlloc;                     /* Bytes of space at aAlloc */
71064   int nKey;                       /* Number of bytes in key */
71065   sqlite3_file *pFile;            /* File iterator is reading from */
71066   u8 *aAlloc;                     /* Allocated space */
71067   u8 *aKey;                       /* Pointer to current key */
71068   u8 *aBuffer;                    /* Current read buffer */
71069   int nBuffer;                    /* Size of read buffer in bytes */
71070 };
71071
71072 /*
71073 ** An instance of this structure is used to organize the stream of records
71074 ** being written to files by the merge-sort code into aligned, page-sized
71075 ** blocks.  Doing all I/O in aligned page-sized blocks helps I/O to go
71076 ** faster on many operating systems.
71077 */
71078 struct FileWriter {
71079   int eFWErr;                     /* Non-zero if in an error state */
71080   u8 *aBuffer;                    /* Pointer to write buffer */
71081   int nBuffer;                    /* Size of write buffer in bytes */
71082   int iBufStart;                  /* First byte of buffer to write */
71083   int iBufEnd;                    /* Last byte of buffer to write */
71084   i64 iWriteOff;                  /* Offset of start of buffer in file */
71085   sqlite3_file *pFile;            /* File to write to */
71086 };
71087
71088 /*
71089 ** A structure to store a single record. All in-memory records are connected
71090 ** together into a linked list headed at VdbeSorter.pRecord using the 
71091 ** SorterRecord.pNext pointer.
71092 */
71093 struct SorterRecord {
71094   void *pVal;
71095   int nVal;
71096   SorterRecord *pNext;
71097 };
71098
71099 /* Minimum allowable value for the VdbeSorter.nWorking variable */
71100 #define SORTER_MIN_WORKING 10
71101
71102 /* Maximum number of segments to merge in a single pass. */
71103 #define SORTER_MAX_MERGE_COUNT 16
71104
71105 /*
71106 ** Free all memory belonging to the VdbeSorterIter object passed as the second
71107 ** argument. All structure fields are set to zero before returning.
71108 */
71109 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
71110   sqlite3DbFree(db, pIter->aAlloc);
71111   sqlite3DbFree(db, pIter->aBuffer);
71112   memset(pIter, 0, sizeof(VdbeSorterIter));
71113 }
71114
71115 /*
71116 ** Read nByte bytes of data from the stream of data iterated by object p.
71117 ** If successful, set *ppOut to point to a buffer containing the data
71118 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
71119 ** error code.
71120 **
71121 ** The buffer indicated by *ppOut may only be considered valid until the
71122 ** next call to this function.
71123 */
71124 static int vdbeSorterIterRead(
71125   sqlite3 *db,                    /* Database handle (for malloc) */
71126   VdbeSorterIter *p,              /* Iterator */
71127   int nByte,                      /* Bytes of data to read */
71128   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
71129 ){
71130   int iBuf;                       /* Offset within buffer to read from */
71131   int nAvail;                     /* Bytes of data available in buffer */
71132   assert( p->aBuffer );
71133
71134   /* If there is no more data to be read from the buffer, read the next 
71135   ** p->nBuffer bytes of data from the file into it. Or, if there are less
71136   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
71137   iBuf = p->iReadOff % p->nBuffer;
71138   if( iBuf==0 ){
71139     int nRead;                    /* Bytes to read from disk */
71140     int rc;                       /* sqlite3OsRead() return code */
71141
71142     /* Determine how many bytes of data to read. */
71143     if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
71144       nRead = p->nBuffer;
71145     }else{
71146       nRead = (int)(p->iEof - p->iReadOff);
71147     }
71148     assert( nRead>0 );
71149
71150     /* Read data from the file. Return early if an error occurs. */
71151     rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
71152     assert( rc!=SQLITE_IOERR_SHORT_READ );
71153     if( rc!=SQLITE_OK ) return rc;
71154   }
71155   nAvail = p->nBuffer - iBuf; 
71156
71157   if( nByte<=nAvail ){
71158     /* The requested data is available in the in-memory buffer. In this
71159     ** case there is no need to make a copy of the data, just return a 
71160     ** pointer into the buffer to the caller.  */
71161     *ppOut = &p->aBuffer[iBuf];
71162     p->iReadOff += nByte;
71163   }else{
71164     /* The requested data is not all available in the in-memory buffer.
71165     ** In this case, allocate space at p->aAlloc[] to copy the requested
71166     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
71167     int nRem;                     /* Bytes remaining to copy */
71168
71169     /* Extend the p->aAlloc[] allocation if required. */
71170     if( p->nAlloc<nByte ){
71171       int nNew = p->nAlloc*2;
71172       while( nByte>nNew ) nNew = nNew*2;
71173       p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
71174       if( !p->aAlloc ) return SQLITE_NOMEM;
71175       p->nAlloc = nNew;
71176     }
71177
71178     /* Copy as much data as is available in the buffer into the start of
71179     ** p->aAlloc[].  */
71180     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
71181     p->iReadOff += nAvail;
71182     nRem = nByte - nAvail;
71183
71184     /* The following loop copies up to p->nBuffer bytes per iteration into
71185     ** the p->aAlloc[] buffer.  */
71186     while( nRem>0 ){
71187       int rc;                     /* vdbeSorterIterRead() return code */
71188       int nCopy;                  /* Number of bytes to copy */
71189       u8 *aNext;                  /* Pointer to buffer to copy data from */
71190
71191       nCopy = nRem;
71192       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
71193       rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
71194       if( rc!=SQLITE_OK ) return rc;
71195       assert( aNext!=p->aAlloc );
71196       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
71197       nRem -= nCopy;
71198     }
71199
71200     *ppOut = p->aAlloc;
71201   }
71202
71203   return SQLITE_OK;
71204 }
71205
71206 /*
71207 ** Read a varint from the stream of data accessed by p. Set *pnOut to
71208 ** the value read.
71209 */
71210 static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
71211   int iBuf;
71212
71213   iBuf = p->iReadOff % p->nBuffer;
71214   if( iBuf && (p->nBuffer-iBuf)>=9 ){
71215     p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
71216   }else{
71217     u8 aVarint[16], *a;
71218     int i = 0, rc;
71219     do{
71220       rc = vdbeSorterIterRead(db, p, 1, &a);
71221       if( rc ) return rc;
71222       aVarint[(i++)&0xf] = a[0];
71223     }while( (a[0]&0x80)!=0 );
71224     sqlite3GetVarint(aVarint, pnOut);
71225   }
71226
71227   return SQLITE_OK;
71228 }
71229
71230
71231 /*
71232 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
71233 ** no error occurs, or an SQLite error code if one does.
71234 */
71235 static int vdbeSorterIterNext(
71236   sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
71237   VdbeSorterIter *pIter           /* Iterator to advance */
71238 ){
71239   int rc;                         /* Return Code */
71240   u64 nRec = 0;                   /* Size of record in bytes */
71241
71242   if( pIter->iReadOff>=pIter->iEof ){
71243     /* This is an EOF condition */
71244     vdbeSorterIterZero(db, pIter);
71245     return SQLITE_OK;
71246   }
71247
71248   rc = vdbeSorterIterVarint(db, pIter, &nRec);
71249   if( rc==SQLITE_OK ){
71250     pIter->nKey = (int)nRec;
71251     rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
71252   }
71253
71254   return rc;
71255 }
71256
71257 /*
71258 ** Initialize iterator pIter to scan through the PMA stored in file pFile
71259 ** starting at offset iStart and ending at offset iEof-1. This function 
71260 ** leaves the iterator pointing to the first key in the PMA (or EOF if the 
71261 ** PMA is empty).
71262 */
71263 static int vdbeSorterIterInit(
71264   sqlite3 *db,                    /* Database handle */
71265   const VdbeSorter *pSorter,      /* Sorter object */
71266   i64 iStart,                     /* Start offset in pFile */
71267   VdbeSorterIter *pIter,          /* Iterator to populate */
71268   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
71269 ){
71270   int rc = SQLITE_OK;
71271   int nBuf;
71272
71273   nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
71274
71275   assert( pSorter->iWriteOff>iStart );
71276   assert( pIter->aAlloc==0 );
71277   assert( pIter->aBuffer==0 );
71278   pIter->pFile = pSorter->pTemp1;
71279   pIter->iReadOff = iStart;
71280   pIter->nAlloc = 128;
71281   pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
71282   pIter->nBuffer = nBuf;
71283   pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
71284
71285   if( !pIter->aBuffer ){
71286     rc = SQLITE_NOMEM;
71287   }else{
71288     int iBuf;
71289
71290     iBuf = iStart % nBuf;
71291     if( iBuf ){
71292       int nRead = nBuf - iBuf;
71293       if( (iStart + nRead) > pSorter->iWriteOff ){
71294         nRead = (int)(pSorter->iWriteOff - iStart);
71295       }
71296       rc = sqlite3OsRead(
71297           pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
71298       );
71299       assert( rc!=SQLITE_IOERR_SHORT_READ );
71300     }
71301
71302     if( rc==SQLITE_OK ){
71303       u64 nByte;                       /* Size of PMA in bytes */
71304       pIter->iEof = pSorter->iWriteOff;
71305       rc = vdbeSorterIterVarint(db, pIter, &nByte);
71306       pIter->iEof = pIter->iReadOff + nByte;
71307       *pnByte += nByte;
71308     }
71309   }
71310
71311   if( rc==SQLITE_OK ){
71312     rc = vdbeSorterIterNext(db, pIter);
71313   }
71314   return rc;
71315 }
71316
71317
71318 /*
71319 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
71320 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
71321 ** used by the comparison. If an error occurs, return an SQLite error code.
71322 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
71323 ** value, depending on whether key1 is smaller, equal to or larger than key2.
71324 **
71325 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
71326 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
71327 ** is true and key1 contains even a single NULL value, it is considered to
71328 ** be less than key2. Even if key2 also contains NULL values.
71329 **
71330 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
71331 ** has been allocated and contains an unpacked record that is used as key2.
71332 */
71333 static void vdbeSorterCompare(
71334   const VdbeCursor *pCsr,         /* Cursor object (for pKeyInfo) */
71335   int bOmitRowid,                 /* Ignore rowid field at end of keys */
71336   const void *pKey1, int nKey1,   /* Left side of comparison */
71337   const void *pKey2, int nKey2,   /* Right side of comparison */
71338   int *pRes                       /* OUT: Result of comparison */
71339 ){
71340   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
71341   VdbeSorter *pSorter = pCsr->pSorter;
71342   UnpackedRecord *r2 = pSorter->pUnpacked;
71343   int i;
71344
71345   if( pKey2 ){
71346     sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
71347   }
71348
71349   if( bOmitRowid ){
71350     r2->nField = pKeyInfo->nField;
71351     assert( r2->nField>0 );
71352     for(i=0; i<r2->nField; i++){
71353       if( r2->aMem[i].flags & MEM_Null ){
71354         *pRes = -1;
71355         return;
71356       }
71357     }
71358     r2->flags |= UNPACKED_PREFIX_MATCH;
71359   }
71360
71361   *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
71362 }
71363
71364 /*
71365 ** This function is called to compare two iterator keys when merging 
71366 ** multiple b-tree segments. Parameter iOut is the index of the aTree[] 
71367 ** value to recalculate.
71368 */
71369 static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
71370   VdbeSorter *pSorter = pCsr->pSorter;
71371   int i1;
71372   int i2;
71373   int iRes;
71374   VdbeSorterIter *p1;
71375   VdbeSorterIter *p2;
71376
71377   assert( iOut<pSorter->nTree && iOut>0 );
71378
71379   if( iOut>=(pSorter->nTree/2) ){
71380     i1 = (iOut - pSorter->nTree/2) * 2;
71381     i2 = i1 + 1;
71382   }else{
71383     i1 = pSorter->aTree[iOut*2];
71384     i2 = pSorter->aTree[iOut*2+1];
71385   }
71386
71387   p1 = &pSorter->aIter[i1];
71388   p2 = &pSorter->aIter[i2];
71389
71390   if( p1->pFile==0 ){
71391     iRes = i2;
71392   }else if( p2->pFile==0 ){
71393     iRes = i1;
71394   }else{
71395     int res;
71396     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
71397     vdbeSorterCompare(
71398         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
71399     );
71400     if( res<=0 ){
71401       iRes = i1;
71402     }else{
71403       iRes = i2;
71404     }
71405   }
71406
71407   pSorter->aTree[iOut] = iRes;
71408   return SQLITE_OK;
71409 }
71410
71411 /*
71412 ** Initialize the temporary index cursor just opened as a sorter cursor.
71413 */
71414 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
71415   int pgsz;                       /* Page size of main database */
71416   int mxCache;                    /* Cache size */
71417   VdbeSorter *pSorter;            /* The new sorter */
71418   char *d;                        /* Dummy */
71419
71420   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
71421   pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
71422   if( pSorter==0 ){
71423     return SQLITE_NOMEM;
71424   }
71425   
71426   pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
71427   if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
71428   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
71429
71430   if( !sqlite3TempInMemory(db) ){
71431     pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
71432     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
71433     mxCache = db->aDb[0].pSchema->cache_size;
71434     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
71435     pSorter->mxPmaSize = mxCache * pgsz;
71436   }
71437
71438   return SQLITE_OK;
71439 }
71440
71441 /*
71442 ** Free the list of sorted records starting at pRecord.
71443 */
71444 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
71445   SorterRecord *p;
71446   SorterRecord *pNext;
71447   for(p=pRecord; p; p=pNext){
71448     pNext = p->pNext;
71449     sqlite3DbFree(db, p);
71450   }
71451 }
71452
71453 /*
71454 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
71455 */
71456 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
71457   VdbeSorter *pSorter = pCsr->pSorter;
71458   if( pSorter ){
71459     if( pSorter->aIter ){
71460       int i;
71461       for(i=0; i<pSorter->nTree; i++){
71462         vdbeSorterIterZero(db, &pSorter->aIter[i]);
71463       }
71464       sqlite3DbFree(db, pSorter->aIter);
71465     }
71466     if( pSorter->pTemp1 ){
71467       sqlite3OsCloseFree(pSorter->pTemp1);
71468     }
71469     vdbeSorterRecordFree(db, pSorter->pRecord);
71470     sqlite3DbFree(db, pSorter->pUnpacked);
71471     sqlite3DbFree(db, pSorter);
71472     pCsr->pSorter = 0;
71473   }
71474 }
71475
71476 /*
71477 ** Allocate space for a file-handle and open a temporary file. If successful,
71478 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
71479 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
71480 */
71481 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
71482   int dummy;
71483   return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
71484       SQLITE_OPEN_TEMP_JOURNAL |
71485       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
71486       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
71487   );
71488 }
71489
71490 /*
71491 ** Merge the two sorted lists p1 and p2 into a single list.
71492 ** Set *ppOut to the head of the new list.
71493 */
71494 static void vdbeSorterMerge(
71495   const VdbeCursor *pCsr,         /* For pKeyInfo */
71496   SorterRecord *p1,               /* First list to merge */
71497   SorterRecord *p2,               /* Second list to merge */
71498   SorterRecord **ppOut            /* OUT: Head of merged list */
71499 ){
71500   SorterRecord *pFinal = 0;
71501   SorterRecord **pp = &pFinal;
71502   void *pVal2 = p2 ? p2->pVal : 0;
71503
71504   while( p1 && p2 ){
71505     int res;
71506     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
71507     if( res<=0 ){
71508       *pp = p1;
71509       pp = &p1->pNext;
71510       p1 = p1->pNext;
71511       pVal2 = 0;
71512     }else{
71513       *pp = p2;
71514        pp = &p2->pNext;
71515       p2 = p2->pNext;
71516       if( p2==0 ) break;
71517       pVal2 = p2->pVal;
71518     }
71519   }
71520   *pp = p1 ? p1 : p2;
71521   *ppOut = pFinal;
71522 }
71523
71524 /*
71525 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
71526 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
71527 ** occurs.
71528 */
71529 static int vdbeSorterSort(const VdbeCursor *pCsr){
71530   int i;
71531   SorterRecord **aSlot;
71532   SorterRecord *p;
71533   VdbeSorter *pSorter = pCsr->pSorter;
71534
71535   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
71536   if( !aSlot ){
71537     return SQLITE_NOMEM;
71538   }
71539
71540   p = pSorter->pRecord;
71541   while( p ){
71542     SorterRecord *pNext = p->pNext;
71543     p->pNext = 0;
71544     for(i=0; aSlot[i]; i++){
71545       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
71546       aSlot[i] = 0;
71547     }
71548     aSlot[i] = p;
71549     p = pNext;
71550   }
71551
71552   p = 0;
71553   for(i=0; i<64; i++){
71554     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
71555   }
71556   pSorter->pRecord = p;
71557
71558   sqlite3_free(aSlot);
71559   return SQLITE_OK;
71560 }
71561
71562 /*
71563 ** Initialize a file-writer object.
71564 */
71565 static void fileWriterInit(
71566   sqlite3 *db,                    /* Database (for malloc) */
71567   sqlite3_file *pFile,            /* File to write to */
71568   FileWriter *p,                  /* Object to populate */
71569   i64 iStart                      /* Offset of pFile to begin writing at */
71570 ){
71571   int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
71572
71573   memset(p, 0, sizeof(FileWriter));
71574   p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
71575   if( !p->aBuffer ){
71576     p->eFWErr = SQLITE_NOMEM;
71577   }else{
71578     p->iBufEnd = p->iBufStart = (iStart % nBuf);
71579     p->iWriteOff = iStart - p->iBufStart;
71580     p->nBuffer = nBuf;
71581     p->pFile = pFile;
71582   }
71583 }
71584
71585 /*
71586 ** Write nData bytes of data to the file-write object. Return SQLITE_OK
71587 ** if successful, or an SQLite error code if an error occurs.
71588 */
71589 static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
71590   int nRem = nData;
71591   while( nRem>0 && p->eFWErr==0 ){
71592     int nCopy = nRem;
71593     if( nCopy>(p->nBuffer - p->iBufEnd) ){
71594       nCopy = p->nBuffer - p->iBufEnd;
71595     }
71596
71597     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
71598     p->iBufEnd += nCopy;
71599     if( p->iBufEnd==p->nBuffer ){
71600       p->eFWErr = sqlite3OsWrite(p->pFile, 
71601           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
71602           p->iWriteOff + p->iBufStart
71603       );
71604       p->iBufStart = p->iBufEnd = 0;
71605       p->iWriteOff += p->nBuffer;
71606     }
71607     assert( p->iBufEnd<p->nBuffer );
71608
71609     nRem -= nCopy;
71610   }
71611 }
71612
71613 /*
71614 ** Flush any buffered data to disk and clean up the file-writer object.
71615 ** The results of using the file-writer after this call are undefined.
71616 ** Return SQLITE_OK if flushing the buffered data succeeds or is not 
71617 ** required. Otherwise, return an SQLite error code.
71618 **
71619 ** Before returning, set *piEof to the offset immediately following the
71620 ** last byte written to the file.
71621 */
71622 static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
71623   int rc;
71624   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
71625     p->eFWErr = sqlite3OsWrite(p->pFile, 
71626         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
71627         p->iWriteOff + p->iBufStart
71628     );
71629   }
71630   *piEof = (p->iWriteOff + p->iBufEnd);
71631   sqlite3DbFree(db, p->aBuffer);
71632   rc = p->eFWErr;
71633   memset(p, 0, sizeof(FileWriter));
71634   return rc;
71635 }
71636
71637 /*
71638 ** Write value iVal encoded as a varint to the file-write object. Return 
71639 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
71640 */
71641 static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
71642   int nByte; 
71643   u8 aByte[10];
71644   nByte = sqlite3PutVarint(aByte, iVal);
71645   fileWriterWrite(p, aByte, nByte);
71646 }
71647
71648 /*
71649 ** Write the current contents of the in-memory linked-list to a PMA. Return
71650 ** SQLITE_OK if successful, or an SQLite error code otherwise.
71651 **
71652 ** The format of a PMA is:
71653 **
71654 **     * A varint. This varint contains the total number of bytes of content
71655 **       in the PMA (not including the varint itself).
71656 **
71657 **     * One or more records packed end-to-end in order of ascending keys. 
71658 **       Each record consists of a varint followed by a blob of data (the 
71659 **       key). The varint is the number of bytes in the blob of data.
71660 */
71661 static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
71662   int rc = SQLITE_OK;             /* Return code */
71663   VdbeSorter *pSorter = pCsr->pSorter;
71664   FileWriter writer;
71665
71666   memset(&writer, 0, sizeof(FileWriter));
71667
71668   if( pSorter->nInMemory==0 ){
71669     assert( pSorter->pRecord==0 );
71670     return rc;
71671   }
71672
71673   rc = vdbeSorterSort(pCsr);
71674
71675   /* If the first temporary PMA file has not been opened, open it now. */
71676   if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
71677     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
71678     assert( rc!=SQLITE_OK || pSorter->pTemp1 );
71679     assert( pSorter->iWriteOff==0 );
71680     assert( pSorter->nPMA==0 );
71681   }
71682
71683   if( rc==SQLITE_OK ){
71684     SorterRecord *p;
71685     SorterRecord *pNext = 0;
71686
71687     fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
71688     pSorter->nPMA++;
71689     fileWriterWriteVarint(&writer, pSorter->nInMemory);
71690     for(p=pSorter->pRecord; p; p=pNext){
71691       pNext = p->pNext;
71692       fileWriterWriteVarint(&writer, p->nVal);
71693       fileWriterWrite(&writer, p->pVal, p->nVal);
71694       sqlite3DbFree(db, p);
71695     }
71696     pSorter->pRecord = p;
71697     rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
71698   }
71699
71700   return rc;
71701 }
71702
71703 /*
71704 ** Add a record to the sorter.
71705 */
71706 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
71707   sqlite3 *db,                    /* Database handle */
71708   const VdbeCursor *pCsr,               /* Sorter cursor */
71709   Mem *pVal                       /* Memory cell containing record */
71710 ){
71711   VdbeSorter *pSorter = pCsr->pSorter;
71712   int rc = SQLITE_OK;             /* Return Code */
71713   SorterRecord *pNew;             /* New list element */
71714
71715   assert( pSorter );
71716   pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
71717
71718   pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
71719   if( pNew==0 ){
71720     rc = SQLITE_NOMEM;
71721   }else{
71722     pNew->pVal = (void *)&pNew[1];
71723     memcpy(pNew->pVal, pVal->z, pVal->n);
71724     pNew->nVal = pVal->n;
71725     pNew->pNext = pSorter->pRecord;
71726     pSorter->pRecord = pNew;
71727   }
71728
71729   /* See if the contents of the sorter should now be written out. They
71730   ** are written out when either of the following are true:
71731   **
71732   **   * The total memory allocated for the in-memory list is greater 
71733   **     than (page-size * cache-size), or
71734   **
71735   **   * The total memory allocated for the in-memory list is greater 
71736   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
71737   */
71738   if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
71739         (pSorter->nInMemory>pSorter->mxPmaSize)
71740      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
71741   )){
71742 #ifdef SQLITE_DEBUG
71743     i64 nExpect = pSorter->iWriteOff
71744                 + sqlite3VarintLen(pSorter->nInMemory)
71745                 + pSorter->nInMemory;
71746 #endif
71747     rc = vdbeSorterListToPMA(db, pCsr);
71748     pSorter->nInMemory = 0;
71749     assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
71750   }
71751
71752   return rc;
71753 }
71754
71755 /*
71756 ** Helper function for sqlite3VdbeSorterRewind(). 
71757 */
71758 static int vdbeSorterInitMerge(
71759   sqlite3 *db,                    /* Database handle */
71760   const VdbeCursor *pCsr,         /* Cursor handle for this sorter */
71761   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
71762 ){
71763   VdbeSorter *pSorter = pCsr->pSorter;
71764   int rc = SQLITE_OK;             /* Return code */
71765   int i;                          /* Used to iterator through aIter[] */
71766   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
71767
71768   /* Initialize the iterators. */
71769   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
71770     VdbeSorterIter *pIter = &pSorter->aIter[i];
71771     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
71772     pSorter->iReadOff = pIter->iEof;
71773     assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
71774     if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
71775   }
71776
71777   /* Initialize the aTree[] array. */
71778   for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
71779     rc = vdbeSorterDoCompare(pCsr, i);
71780   }
71781
71782   *pnByte = nByte;
71783   return rc;
71784 }
71785
71786 /*
71787 ** Once the sorter has been populated, this function is called to prepare
71788 ** for iterating through its contents in sorted order.
71789 */
71790 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
71791   VdbeSorter *pSorter = pCsr->pSorter;
71792   int rc;                         /* Return code */
71793   sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
71794   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
71795   int nIter;                      /* Number of iterators used */
71796   int nByte;                      /* Bytes of space required for aIter/aTree */
71797   int N = 2;                      /* Power of 2 >= nIter */
71798
71799   assert( pSorter );
71800
71801   /* If no data has been written to disk, then do not do so now. Instead,
71802   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
71803   ** from the in-memory list.  */
71804   if( pSorter->nPMA==0 ){
71805     *pbEof = !pSorter->pRecord;
71806     assert( pSorter->aTree==0 );
71807     return vdbeSorterSort(pCsr);
71808   }
71809
71810   /* Write the current in-memory list to a PMA. */
71811   rc = vdbeSorterListToPMA(db, pCsr);
71812   if( rc!=SQLITE_OK ) return rc;
71813
71814   /* Allocate space for aIter[] and aTree[]. */
71815   nIter = pSorter->nPMA;
71816   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
71817   assert( nIter>0 );
71818   while( N<nIter ) N += N;
71819   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
71820   pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
71821   if( !pSorter->aIter ) return SQLITE_NOMEM;
71822   pSorter->aTree = (int *)&pSorter->aIter[N];
71823   pSorter->nTree = N;
71824
71825   do {
71826     int iNew;                     /* Index of new, merged, PMA */
71827
71828     for(iNew=0; 
71829         rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA; 
71830         iNew++
71831     ){
71832       int rc2;                    /* Return code from fileWriterFinish() */
71833       FileWriter writer;          /* Object used to write to disk */
71834       i64 nWrite;                 /* Number of bytes in new PMA */
71835
71836       memset(&writer, 0, sizeof(FileWriter));
71837
71838       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
71839       ** initialize an iterator for each of them and break out of the loop.
71840       ** These iterators will be incrementally merged as the VDBE layer calls
71841       ** sqlite3VdbeSorterNext().
71842       **
71843       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
71844       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
71845       ** are merged into a single PMA that is written to file pTemp2.
71846       */
71847       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
71848       assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
71849       if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
71850         break;
71851       }
71852
71853       /* Open the second temp file, if it is not already open. */
71854       if( pTemp2==0 ){
71855         assert( iWrite2==0 );
71856         rc = vdbeSorterOpenTempFile(db, &pTemp2);
71857       }
71858
71859       if( rc==SQLITE_OK ){
71860         int bEof = 0;
71861         fileWriterInit(db, pTemp2, &writer, iWrite2);
71862         fileWriterWriteVarint(&writer, nWrite);
71863         while( rc==SQLITE_OK && bEof==0 ){
71864           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
71865           assert( pIter->pFile );
71866
71867           fileWriterWriteVarint(&writer, pIter->nKey);
71868           fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
71869           rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
71870         }
71871         rc2 = fileWriterFinish(db, &writer, &iWrite2);
71872         if( rc==SQLITE_OK ) rc = rc2;
71873       }
71874     }
71875
71876     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
71877       break;
71878     }else{
71879       sqlite3_file *pTmp = pSorter->pTemp1;
71880       pSorter->nPMA = iNew;
71881       pSorter->pTemp1 = pTemp2;
71882       pTemp2 = pTmp;
71883       pSorter->iWriteOff = iWrite2;
71884       pSorter->iReadOff = 0;
71885       iWrite2 = 0;
71886     }
71887   }while( rc==SQLITE_OK );
71888
71889   if( pTemp2 ){
71890     sqlite3OsCloseFree(pTemp2);
71891   }
71892   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
71893   return rc;
71894 }
71895
71896 /*
71897 ** Advance to the next element in the sorter.
71898 */
71899 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
71900   VdbeSorter *pSorter = pCsr->pSorter;
71901   int rc;                         /* Return code */
71902
71903   if( pSorter->aTree ){
71904     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
71905     int i;                        /* Index of aTree[] to recalculate */
71906
71907     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
71908     for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
71909       rc = vdbeSorterDoCompare(pCsr, i);
71910     }
71911
71912     *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
71913   }else{
71914     SorterRecord *pFree = pSorter->pRecord;
71915     pSorter->pRecord = pFree->pNext;
71916     pFree->pNext = 0;
71917     vdbeSorterRecordFree(db, pFree);
71918     *pbEof = !pSorter->pRecord;
71919     rc = SQLITE_OK;
71920   }
71921   return rc;
71922 }
71923
71924 /*
71925 ** Return a pointer to a buffer owned by the sorter that contains the 
71926 ** current key.
71927 */
71928 static void *vdbeSorterRowkey(
71929   const VdbeSorter *pSorter,      /* Sorter object */
71930   int *pnKey                      /* OUT: Size of current key in bytes */
71931 ){
71932   void *pKey;
71933   if( pSorter->aTree ){
71934     VdbeSorterIter *pIter;
71935     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
71936     *pnKey = pIter->nKey;
71937     pKey = pIter->aKey;
71938   }else{
71939     *pnKey = pSorter->pRecord->nVal;
71940     pKey = pSorter->pRecord->pVal;
71941   }
71942   return pKey;
71943 }
71944
71945 /*
71946 ** Copy the current sorter key into the memory cell pOut.
71947 */
71948 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
71949   VdbeSorter *pSorter = pCsr->pSorter;
71950   void *pKey; int nKey;           /* Sorter key to copy into pOut */
71951
71952   pKey = vdbeSorterRowkey(pSorter, &nKey);
71953   if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
71954     return SQLITE_NOMEM;
71955   }
71956   pOut->n = nKey;
71957   MemSetTypeFlag(pOut, MEM_Blob);
71958   memcpy(pOut->z, pKey, nKey);
71959
71960   return SQLITE_OK;
71961 }
71962
71963 /*
71964 ** Compare the key in memory cell pVal with the key that the sorter cursor
71965 ** passed as the first argument currently points to. For the purposes of
71966 ** the comparison, ignore the rowid field at the end of each record.
71967 **
71968 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
71969 ** Otherwise, set *pRes to a negative, zero or positive value if the
71970 ** key in pVal is smaller than, equal to or larger than the current sorter
71971 ** key.
71972 */
71973 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
71974   const VdbeCursor *pCsr,         /* Sorter cursor */
71975   Mem *pVal,                      /* Value to compare to current sorter key */
71976   int *pRes                       /* OUT: Result of comparison */
71977 ){
71978   VdbeSorter *pSorter = pCsr->pSorter;
71979   void *pKey; int nKey;           /* Sorter key to compare pVal with */
71980
71981   pKey = vdbeSorterRowkey(pSorter, &nKey);
71982   vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
71983   return SQLITE_OK;
71984 }
71985
71986 /************** End of vdbesort.c ********************************************/
71987 /************** Begin file journal.c *****************************************/
71988 /*
71989 ** 2007 August 22
71990 **
71991 ** The author disclaims copyright to this source code.  In place of
71992 ** a legal notice, here is a blessing:
71993 **
71994 **    May you do good and not evil.
71995 **    May you find forgiveness for yourself and forgive others.
71996 **    May you share freely, never taking more than you give.
71997 **
71998 *************************************************************************
71999 **
72000 ** This file implements a special kind of sqlite3_file object used
72001 ** by SQLite to create journal files if the atomic-write optimization
72002 ** is enabled.
72003 **
72004 ** The distinctive characteristic of this sqlite3_file is that the
72005 ** actual on disk file is created lazily. When the file is created,
72006 ** the caller specifies a buffer size for an in-memory buffer to
72007 ** be used to service read() and write() requests. The actual file
72008 ** on disk is not created or populated until either:
72009 **
72010 **   1) The in-memory representation grows too large for the allocated 
72011 **      buffer, or
72012 **   2) The sqlite3JournalCreate() function is called.
72013 */
72014 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
72015
72016
72017 /*
72018 ** A JournalFile object is a subclass of sqlite3_file used by
72019 ** as an open file handle for journal files.
72020 */
72021 struct JournalFile {
72022   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
72023   int nBuf;                       /* Size of zBuf[] in bytes */
72024   char *zBuf;                     /* Space to buffer journal writes */
72025   int iSize;                      /* Amount of zBuf[] currently used */
72026   int flags;                      /* xOpen flags */
72027   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
72028   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
72029   const char *zJournal;           /* Name of the journal file */
72030 };
72031 typedef struct JournalFile JournalFile;
72032
72033 /*
72034 ** If it does not already exists, create and populate the on-disk file 
72035 ** for JournalFile p.
72036 */
72037 static int createFile(JournalFile *p){
72038   int rc = SQLITE_OK;
72039   if( !p->pReal ){
72040     sqlite3_file *pReal = (sqlite3_file *)&p[1];
72041     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
72042     if( rc==SQLITE_OK ){
72043       p->pReal = pReal;
72044       if( p->iSize>0 ){
72045         assert(p->iSize<=p->nBuf);
72046         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
72047       }
72048       if( rc!=SQLITE_OK ){
72049         /* If an error occurred while writing to the file, close it before
72050         ** returning. This way, SQLite uses the in-memory journal data to 
72051         ** roll back changes made to the internal page-cache before this
72052         ** function was called.  */
72053         sqlite3OsClose(pReal);
72054         p->pReal = 0;
72055       }
72056     }
72057   }
72058   return rc;
72059 }
72060
72061 /*
72062 ** Close the file.
72063 */
72064 static int jrnlClose(sqlite3_file *pJfd){
72065   JournalFile *p = (JournalFile *)pJfd;
72066   if( p->pReal ){
72067     sqlite3OsClose(p->pReal);
72068   }
72069   sqlite3_free(p->zBuf);
72070   return SQLITE_OK;
72071 }
72072
72073 /*
72074 ** Read data from the file.
72075 */
72076 static int jrnlRead(
72077   sqlite3_file *pJfd,    /* The journal file from which to read */
72078   void *zBuf,            /* Put the results here */
72079   int iAmt,              /* Number of bytes to read */
72080   sqlite_int64 iOfst     /* Begin reading at this offset */
72081 ){
72082   int rc = SQLITE_OK;
72083   JournalFile *p = (JournalFile *)pJfd;
72084   if( p->pReal ){
72085     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
72086   }else if( (iAmt+iOfst)>p->iSize ){
72087     rc = SQLITE_IOERR_SHORT_READ;
72088   }else{
72089     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
72090   }
72091   return rc;
72092 }
72093
72094 /*
72095 ** Write data to the file.
72096 */
72097 static int jrnlWrite(
72098   sqlite3_file *pJfd,    /* The journal file into which to write */
72099   const void *zBuf,      /* Take data to be written from here */
72100   int iAmt,              /* Number of bytes to write */
72101   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
72102 ){
72103   int rc = SQLITE_OK;
72104   JournalFile *p = (JournalFile *)pJfd;
72105   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
72106     rc = createFile(p);
72107   }
72108   if( rc==SQLITE_OK ){
72109     if( p->pReal ){
72110       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
72111     }else{
72112       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
72113       if( p->iSize<(iOfst+iAmt) ){
72114         p->iSize = (iOfst+iAmt);
72115       }
72116     }
72117   }
72118   return rc;
72119 }
72120
72121 /*
72122 ** Truncate the file.
72123 */
72124 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
72125   int rc = SQLITE_OK;
72126   JournalFile *p = (JournalFile *)pJfd;
72127   if( p->pReal ){
72128     rc = sqlite3OsTruncate(p->pReal, size);
72129   }else if( size<p->iSize ){
72130     p->iSize = size;
72131   }
72132   return rc;
72133 }
72134
72135 /*
72136 ** Sync the file.
72137 */
72138 static int jrnlSync(sqlite3_file *pJfd, int flags){
72139   int rc;
72140   JournalFile *p = (JournalFile *)pJfd;
72141   if( p->pReal ){
72142     rc = sqlite3OsSync(p->pReal, flags);
72143   }else{
72144     rc = SQLITE_OK;
72145   }
72146   return rc;
72147 }
72148
72149 /*
72150 ** Query the size of the file in bytes.
72151 */
72152 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
72153   int rc = SQLITE_OK;
72154   JournalFile *p = (JournalFile *)pJfd;
72155   if( p->pReal ){
72156     rc = sqlite3OsFileSize(p->pReal, pSize);
72157   }else{
72158     *pSize = (sqlite_int64) p->iSize;
72159   }
72160   return rc;
72161 }
72162
72163 /*
72164 ** Table of methods for JournalFile sqlite3_file object.
72165 */
72166 static struct sqlite3_io_methods JournalFileMethods = {
72167   1,             /* iVersion */
72168   jrnlClose,     /* xClose */
72169   jrnlRead,      /* xRead */
72170   jrnlWrite,     /* xWrite */
72171   jrnlTruncate,  /* xTruncate */
72172   jrnlSync,      /* xSync */
72173   jrnlFileSize,  /* xFileSize */
72174   0,             /* xLock */
72175   0,             /* xUnlock */
72176   0,             /* xCheckReservedLock */
72177   0,             /* xFileControl */
72178   0,             /* xSectorSize */
72179   0,             /* xDeviceCharacteristics */
72180   0,             /* xShmMap */
72181   0,             /* xShmLock */
72182   0,             /* xShmBarrier */
72183   0              /* xShmUnmap */
72184 };
72185
72186 /* 
72187 ** Open a journal file.
72188 */
72189 SQLITE_PRIVATE int sqlite3JournalOpen(
72190   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
72191   const char *zName,         /* Name of the journal file */
72192   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
72193   int flags,                 /* Opening flags */
72194   int nBuf                   /* Bytes buffered before opening the file */
72195 ){
72196   JournalFile *p = (JournalFile *)pJfd;
72197   memset(p, 0, sqlite3JournalSize(pVfs));
72198   if( nBuf>0 ){
72199     p->zBuf = sqlite3MallocZero(nBuf);
72200     if( !p->zBuf ){
72201       return SQLITE_NOMEM;
72202     }
72203   }else{
72204     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
72205   }
72206   p->pMethod = &JournalFileMethods;
72207   p->nBuf = nBuf;
72208   p->flags = flags;
72209   p->zJournal = zName;
72210   p->pVfs = pVfs;
72211   return SQLITE_OK;
72212 }
72213
72214 /*
72215 ** If the argument p points to a JournalFile structure, and the underlying
72216 ** file has not yet been created, create it now.
72217 */
72218 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
72219   if( p->pMethods!=&JournalFileMethods ){
72220     return SQLITE_OK;
72221   }
72222   return createFile((JournalFile *)p);
72223 }
72224
72225 /*
72226 ** The file-handle passed as the only argument is guaranteed to be an open
72227 ** file. It may or may not be of class JournalFile. If the file is a
72228 ** JournalFile, and the underlying file on disk has not yet been opened,
72229 ** return 0. Otherwise, return 1.
72230 */
72231 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
72232   return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
72233 }
72234
72235 /* 
72236 ** Return the number of bytes required to store a JournalFile that uses vfs
72237 ** pVfs to create the underlying on-disk files.
72238 */
72239 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
72240   return (pVfs->szOsFile+sizeof(JournalFile));
72241 }
72242 #endif
72243
72244 /************** End of journal.c *********************************************/
72245 /************** Begin file memjournal.c **************************************/
72246 /*
72247 ** 2008 October 7
72248 **
72249 ** The author disclaims copyright to this source code.  In place of
72250 ** a legal notice, here is a blessing:
72251 **
72252 **    May you do good and not evil.
72253 **    May you find forgiveness for yourself and forgive others.
72254 **    May you share freely, never taking more than you give.
72255 **
72256 *************************************************************************
72257 **
72258 ** This file contains code use to implement an in-memory rollback journal.
72259 ** The in-memory rollback journal is used to journal transactions for
72260 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
72261 */
72262
72263 /* Forward references to internal structures */
72264 typedef struct MemJournal MemJournal;
72265 typedef struct FilePoint FilePoint;
72266 typedef struct FileChunk FileChunk;
72267
72268 /* Space to hold the rollback journal is allocated in increments of
72269 ** this many bytes.
72270 **
72271 ** The size chosen is a little less than a power of two.  That way,
72272 ** the FileChunk object will have a size that almost exactly fills
72273 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
72274 ** memory allocators.
72275 */
72276 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
72277
72278 /* Macro to find the minimum of two numeric values.
72279 */
72280 #ifndef MIN
72281 # define MIN(x,y) ((x)<(y)?(x):(y))
72282 #endif
72283
72284 /*
72285 ** The rollback journal is composed of a linked list of these structures.
72286 */
72287 struct FileChunk {
72288   FileChunk *pNext;               /* Next chunk in the journal */
72289   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
72290 };
72291
72292 /*
72293 ** An instance of this object serves as a cursor into the rollback journal.
72294 ** The cursor can be either for reading or writing.
72295 */
72296 struct FilePoint {
72297   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
72298   FileChunk *pChunk;              /* Specific chunk into which cursor points */
72299 };
72300
72301 /*
72302 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
72303 ** is an instance of this class.
72304 */
72305 struct MemJournal {
72306   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
72307   FileChunk *pFirst;              /* Head of in-memory chunk-list */
72308   FilePoint endpoint;             /* Pointer to the end of the file */
72309   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
72310 };
72311
72312 /*
72313 ** Read data from the in-memory journal file.  This is the implementation
72314 ** of the sqlite3_vfs.xRead method.
72315 */
72316 static int memjrnlRead(
72317   sqlite3_file *pJfd,    /* The journal file from which to read */
72318   void *zBuf,            /* Put the results here */
72319   int iAmt,              /* Number of bytes to read */
72320   sqlite_int64 iOfst     /* Begin reading at this offset */
72321 ){
72322   MemJournal *p = (MemJournal *)pJfd;
72323   u8 *zOut = zBuf;
72324   int nRead = iAmt;
72325   int iChunkOffset;
72326   FileChunk *pChunk;
72327
72328   /* SQLite never tries to read past the end of a rollback journal file */
72329   assert( iOfst+iAmt<=p->endpoint.iOffset );
72330
72331   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
72332     sqlite3_int64 iOff = 0;
72333     for(pChunk=p->pFirst; 
72334         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
72335         pChunk=pChunk->pNext
72336     ){
72337       iOff += JOURNAL_CHUNKSIZE;
72338     }
72339   }else{
72340     pChunk = p->readpoint.pChunk;
72341   }
72342
72343   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
72344   do {
72345     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
72346     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
72347     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
72348     zOut += nCopy;
72349     nRead -= iSpace;
72350     iChunkOffset = 0;
72351   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
72352   p->readpoint.iOffset = iOfst+iAmt;
72353   p->readpoint.pChunk = pChunk;
72354
72355   return SQLITE_OK;
72356 }
72357
72358 /*
72359 ** Write data to the file.
72360 */
72361 static int memjrnlWrite(
72362   sqlite3_file *pJfd,    /* The journal file into which to write */
72363   const void *zBuf,      /* Take data to be written from here */
72364   int iAmt,              /* Number of bytes to write */
72365   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
72366 ){
72367   MemJournal *p = (MemJournal *)pJfd;
72368   int nWrite = iAmt;
72369   u8 *zWrite = (u8 *)zBuf;
72370
72371   /* An in-memory journal file should only ever be appended to. Random
72372   ** access writes are not required by sqlite.
72373   */
72374   assert( iOfst==p->endpoint.iOffset );
72375   UNUSED_PARAMETER(iOfst);
72376
72377   while( nWrite>0 ){
72378     FileChunk *pChunk = p->endpoint.pChunk;
72379     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
72380     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
72381
72382     if( iChunkOffset==0 ){
72383       /* New chunk is required to extend the file. */
72384       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
72385       if( !pNew ){
72386         return SQLITE_IOERR_NOMEM;
72387       }
72388       pNew->pNext = 0;
72389       if( pChunk ){
72390         assert( p->pFirst );
72391         pChunk->pNext = pNew;
72392       }else{
72393         assert( !p->pFirst );
72394         p->pFirst = pNew;
72395       }
72396       p->endpoint.pChunk = pNew;
72397     }
72398
72399     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
72400     zWrite += iSpace;
72401     nWrite -= iSpace;
72402     p->endpoint.iOffset += iSpace;
72403   }
72404
72405   return SQLITE_OK;
72406 }
72407
72408 /*
72409 ** Truncate the file.
72410 */
72411 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
72412   MemJournal *p = (MemJournal *)pJfd;
72413   FileChunk *pChunk;
72414   assert(size==0);
72415   UNUSED_PARAMETER(size);
72416   pChunk = p->pFirst;
72417   while( pChunk ){
72418     FileChunk *pTmp = pChunk;
72419     pChunk = pChunk->pNext;
72420     sqlite3_free(pTmp);
72421   }
72422   sqlite3MemJournalOpen(pJfd);
72423   return SQLITE_OK;
72424 }
72425
72426 /*
72427 ** Close the file.
72428 */
72429 static int memjrnlClose(sqlite3_file *pJfd){
72430   memjrnlTruncate(pJfd, 0);
72431   return SQLITE_OK;
72432 }
72433
72434
72435 /*
72436 ** Sync the file.
72437 **
72438 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
72439 ** is never called in a working implementation.  This implementation
72440 ** exists purely as a contingency, in case some malfunction in some other
72441 ** part of SQLite causes Sync to be called by mistake.
72442 */
72443 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
72444   UNUSED_PARAMETER2(NotUsed, NotUsed2);
72445   return SQLITE_OK;
72446 }
72447
72448 /*
72449 ** Query the size of the file in bytes.
72450 */
72451 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
72452   MemJournal *p = (MemJournal *)pJfd;
72453   *pSize = (sqlite_int64) p->endpoint.iOffset;
72454   return SQLITE_OK;
72455 }
72456
72457 /*
72458 ** Table of methods for MemJournal sqlite3_file object.
72459 */
72460 static const struct sqlite3_io_methods MemJournalMethods = {
72461   1,                /* iVersion */
72462   memjrnlClose,     /* xClose */
72463   memjrnlRead,      /* xRead */
72464   memjrnlWrite,     /* xWrite */
72465   memjrnlTruncate,  /* xTruncate */
72466   memjrnlSync,      /* xSync */
72467   memjrnlFileSize,  /* xFileSize */
72468   0,                /* xLock */
72469   0,                /* xUnlock */
72470   0,                /* xCheckReservedLock */
72471   0,                /* xFileControl */
72472   0,                /* xSectorSize */
72473   0,                /* xDeviceCharacteristics */
72474   0,                /* xShmMap */
72475   0,                /* xShmLock */
72476   0,                /* xShmBarrier */
72477   0                 /* xShmUnlock */
72478 };
72479
72480 /* 
72481 ** Open a journal file.
72482 */
72483 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
72484   MemJournal *p = (MemJournal *)pJfd;
72485   assert( EIGHT_BYTE_ALIGNMENT(p) );
72486   memset(p, 0, sqlite3MemJournalSize());
72487   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
72488 }
72489
72490 /*
72491 ** Return true if the file-handle passed as an argument is 
72492 ** an in-memory journal 
72493 */
72494 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
72495   return pJfd->pMethods==&MemJournalMethods;
72496 }
72497
72498 /* 
72499 ** Return the number of bytes required to store a MemJournal file descriptor.
72500 */
72501 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
72502   return sizeof(MemJournal);
72503 }
72504
72505 /************** End of memjournal.c ******************************************/
72506 /************** Begin file walker.c ******************************************/
72507 /*
72508 ** 2008 August 16
72509 **
72510 ** The author disclaims copyright to this source code.  In place of
72511 ** a legal notice, here is a blessing:
72512 **
72513 **    May you do good and not evil.
72514 **    May you find forgiveness for yourself and forgive others.
72515 **    May you share freely, never taking more than you give.
72516 **
72517 *************************************************************************
72518 ** This file contains routines used for walking the parser tree for
72519 ** an SQL statement.
72520 */
72521 /* #include <stdlib.h> */
72522 /* #include <string.h> */
72523
72524
72525 /*
72526 ** Walk an expression tree.  Invoke the callback once for each node
72527 ** of the expression, while decending.  (In other words, the callback
72528 ** is invoked before visiting children.)
72529 **
72530 ** The return value from the callback should be one of the WRC_*
72531 ** constants to specify how to proceed with the walk.
72532 **
72533 **    WRC_Continue      Continue descending down the tree.
72534 **
72535 **    WRC_Prune         Do not descend into child nodes.  But allow
72536 **                      the walk to continue with sibling nodes.
72537 **
72538 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
72539 **                      return the top-level walk call.
72540 **
72541 ** The return value from this routine is WRC_Abort to abandon the tree walk
72542 ** and WRC_Continue to continue.
72543 */
72544 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
72545   int rc;
72546   if( pExpr==0 ) return WRC_Continue;
72547   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
72548   testcase( ExprHasProperty(pExpr, EP_Reduced) );
72549   rc = pWalker->xExprCallback(pWalker, pExpr);
72550   if( rc==WRC_Continue
72551               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
72552     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
72553     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
72554     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72555       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
72556     }else{
72557       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
72558     }
72559   }
72560   return rc & WRC_Abort;
72561 }
72562
72563 /*
72564 ** Call sqlite3WalkExpr() for every expression in list p or until
72565 ** an abort request is seen.
72566 */
72567 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
72568   int i;
72569   struct ExprList_item *pItem;
72570   if( p ){
72571     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
72572       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
72573     }
72574   }
72575   return WRC_Continue;
72576 }
72577
72578 /*
72579 ** Walk all expressions associated with SELECT statement p.  Do
72580 ** not invoke the SELECT callback on p, but do (of course) invoke
72581 ** any expr callbacks and SELECT callbacks that come from subqueries.
72582 ** Return WRC_Abort or WRC_Continue.
72583 */
72584 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
72585   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
72586   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
72587   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
72588   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
72589   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
72590   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
72591   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
72592   return WRC_Continue;
72593 }
72594
72595 /*
72596 ** Walk the parse trees associated with all subqueries in the
72597 ** FROM clause of SELECT statement p.  Do not invoke the select
72598 ** callback on p, but do invoke it on each FROM clause subquery
72599 ** and on any subqueries further down in the tree.  Return 
72600 ** WRC_Abort or WRC_Continue;
72601 */
72602 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
72603   SrcList *pSrc;
72604   int i;
72605   struct SrcList_item *pItem;
72606
72607   pSrc = p->pSrc;
72608   if( ALWAYS(pSrc) ){
72609     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
72610       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
72611         return WRC_Abort;
72612       }
72613     }
72614   }
72615   return WRC_Continue;
72616
72617
72618 /*
72619 ** Call sqlite3WalkExpr() for every expression in Select statement p.
72620 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
72621 ** on the compound select chain, p->pPrior.
72622 **
72623 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
72624 ** there is an abort request.
72625 **
72626 ** If the Walker does not have an xSelectCallback() then this routine
72627 ** is a no-op returning WRC_Continue.
72628 */
72629 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
72630   int rc;
72631   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
72632   rc = WRC_Continue;
72633   pWalker->walkerDepth++;
72634   while( p ){
72635     rc = pWalker->xSelectCallback(pWalker, p);
72636     if( rc ) break;
72637     if( sqlite3WalkSelectExpr(pWalker, p)
72638      || sqlite3WalkSelectFrom(pWalker, p)
72639     ){
72640       pWalker->walkerDepth--;
72641       return WRC_Abort;
72642     }
72643     p = p->pPrior;
72644   }
72645   pWalker->walkerDepth--;
72646   return rc & WRC_Abort;
72647 }
72648
72649 /************** End of walker.c **********************************************/
72650 /************** Begin file resolve.c *****************************************/
72651 /*
72652 ** 2008 August 18
72653 **
72654 ** The author disclaims copyright to this source code.  In place of
72655 ** a legal notice, here is a blessing:
72656 **
72657 **    May you do good and not evil.
72658 **    May you find forgiveness for yourself and forgive others.
72659 **    May you share freely, never taking more than you give.
72660 **
72661 *************************************************************************
72662 **
72663 ** This file contains routines used for walking the parser tree and
72664 ** resolve all identifiers by associating them with a particular
72665 ** table and column.
72666 */
72667 /* #include <stdlib.h> */
72668 /* #include <string.h> */
72669
72670 /*
72671 ** Walk the expression tree pExpr and increase the aggregate function
72672 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
72673 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
72674 ** outer query into an inner subquery.
72675 **
72676 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
72677 ** is a helper function - a callback for the tree walker.
72678 */
72679 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
72680   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
72681   return WRC_Continue;
72682 }
72683 static void incrAggFunctionDepth(Expr *pExpr, int N){
72684   if( N>0 ){
72685     Walker w;
72686     memset(&w, 0, sizeof(w));
72687     w.xExprCallback = incrAggDepth;
72688     w.u.i = N;
72689     sqlite3WalkExpr(&w, pExpr);
72690   }
72691 }
72692
72693 /*
72694 ** Turn the pExpr expression into an alias for the iCol-th column of the
72695 ** result set in pEList.
72696 **
72697 ** If the result set column is a simple column reference, then this routine
72698 ** makes an exact copy.  But for any other kind of expression, this
72699 ** routine make a copy of the result set column as the argument to the
72700 ** TK_AS operator.  The TK_AS operator causes the expression to be
72701 ** evaluated just once and then reused for each alias.
72702 **
72703 ** The reason for suppressing the TK_AS term when the expression is a simple
72704 ** column reference is so that the column reference will be recognized as
72705 ** usable by indices within the WHERE clause processing logic. 
72706 **
72707 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
72708 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
72709 **
72710 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
72711 **
72712 ** Is equivalent to:
72713 **
72714 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
72715 **
72716 ** The result of random()%5 in the GROUP BY clause is probably different
72717 ** from the result in the result-set.  We might fix this someday.  Or
72718 ** then again, we might not...
72719 **
72720 ** If the reference is followed by a COLLATE operator, then make sure
72721 ** the COLLATE operator is preserved.  For example:
72722 **
72723 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
72724 **
72725 ** Should be transformed into:
72726 **
72727 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
72728 **
72729 ** The nSubquery parameter specifies how many levels of subquery the
72730 ** alias is removed from the original expression.  The usually value is
72731 ** zero but it might be more if the alias is contained within a subquery
72732 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
72733 ** structures must be increased by the nSubquery amount.
72734 */
72735 static void resolveAlias(
72736   Parse *pParse,         /* Parsing context */
72737   ExprList *pEList,      /* A result set */
72738   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
72739   Expr *pExpr,           /* Transform this into an alias to the result set */
72740   const char *zType,     /* "GROUP" or "ORDER" or "" */
72741   int nSubquery          /* Number of subqueries that the label is moving */
72742 ){
72743   Expr *pOrig;           /* The iCol-th column of the result set */
72744   Expr *pDup;            /* Copy of pOrig */
72745   sqlite3 *db;           /* The database connection */
72746
72747   assert( iCol>=0 && iCol<pEList->nExpr );
72748   pOrig = pEList->a[iCol].pExpr;
72749   assert( pOrig!=0 );
72750   assert( pOrig->flags & EP_Resolved );
72751   db = pParse->db;
72752   pDup = sqlite3ExprDup(db, pOrig, 0);
72753   if( pDup==0 ) return;
72754   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
72755     incrAggFunctionDepth(pDup, nSubquery);
72756     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
72757     if( pDup==0 ) return;
72758     if( pEList->a[iCol].iAlias==0 ){
72759       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
72760     }
72761     pDup->iTable = pEList->a[iCol].iAlias;
72762   }
72763   if( pExpr->op==TK_COLLATE ){
72764     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
72765   }
72766
72767   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
72768   ** prevents ExprDelete() from deleting the Expr structure itself,
72769   ** allowing it to be repopulated by the memcpy() on the following line.
72770   ** The pExpr->u.zToken might point into memory that will be freed by the
72771   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
72772   ** make a copy of the token before doing the sqlite3DbFree().
72773   */
72774   ExprSetProperty(pExpr, EP_Static);
72775   sqlite3ExprDelete(db, pExpr);
72776   memcpy(pExpr, pDup, sizeof(*pExpr));
72777   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
72778     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
72779     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
72780     pExpr->flags2 |= EP2_MallocedToken;
72781   }
72782   sqlite3DbFree(db, pDup);
72783 }
72784
72785
72786 /*
72787 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
72788 **
72789 ** Return FALSE if the USING clause is NULL or if it does not contain
72790 ** zCol.
72791 */
72792 static int nameInUsingClause(IdList *pUsing, const char *zCol){
72793   if( pUsing ){
72794     int k;
72795     for(k=0; k<pUsing->nId; k++){
72796       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
72797     }
72798   }
72799   return 0;
72800 }
72801
72802 /*
72803 ** Subqueries stores the original database, table and column names for their
72804 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
72805 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
72806 ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
72807 ** match anything.
72808 */
72809 SQLITE_PRIVATE int sqlite3MatchSpanName(
72810   const char *zSpan,
72811   const char *zCol,
72812   const char *zTab,
72813   const char *zDb
72814 ){
72815   int n;
72816   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
72817   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
72818     return 0;
72819   }
72820   zSpan += n+1;
72821   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
72822   if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
72823     return 0;
72824   }
72825   zSpan += n+1;
72826   if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
72827     return 0;
72828   }
72829   return 1;
72830 }
72831
72832 /*
72833 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
72834 ** that name in the set of source tables in pSrcList and make the pExpr 
72835 ** expression node refer back to that source column.  The following changes
72836 ** are made to pExpr:
72837 **
72838 **    pExpr->iDb           Set the index in db->aDb[] of the database X
72839 **                         (even if X is implied).
72840 **    pExpr->iTable        Set to the cursor number for the table obtained
72841 **                         from pSrcList.
72842 **    pExpr->pTab          Points to the Table structure of X.Y (even if
72843 **                         X and/or Y are implied.)
72844 **    pExpr->iColumn       Set to the column number within the table.
72845 **    pExpr->op            Set to TK_COLUMN.
72846 **    pExpr->pLeft         Any expression this points to is deleted
72847 **    pExpr->pRight        Any expression this points to is deleted.
72848 **
72849 ** The zDb variable is the name of the database (the "X").  This value may be
72850 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
72851 ** can be used.  The zTable variable is the name of the table (the "Y").  This
72852 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
72853 ** means that the form of the name is Z and that columns from any table
72854 ** can be used.
72855 **
72856 ** If the name cannot be resolved unambiguously, leave an error message
72857 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
72858 */
72859 static int lookupName(
72860   Parse *pParse,       /* The parsing context */
72861   const char *zDb,     /* Name of the database containing table, or NULL */
72862   const char *zTab,    /* Name of table containing column, or NULL */
72863   const char *zCol,    /* Name of the column. */
72864   NameContext *pNC,    /* The name context used to resolve the name */
72865   Expr *pExpr          /* Make this EXPR node point to the selected column */
72866 ){
72867   int i, j;                         /* Loop counters */
72868   int cnt = 0;                      /* Number of matching column names */
72869   int cntTab = 0;                   /* Number of matching table names */
72870   int nSubquery = 0;                /* How many levels of subquery */
72871   sqlite3 *db = pParse->db;         /* The database connection */
72872   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
72873   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
72874   NameContext *pTopNC = pNC;        /* First namecontext in the list */
72875   Schema *pSchema = 0;              /* Schema of the expression */
72876   int isTrigger = 0;
72877
72878   assert( pNC );     /* the name context cannot be NULL. */
72879   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
72880   assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
72881
72882   /* Initialize the node to no-match */
72883   pExpr->iTable = -1;
72884   pExpr->pTab = 0;
72885   ExprSetIrreducible(pExpr);
72886
72887   /* Translate the schema name in zDb into a pointer to the corresponding
72888   ** schema.  If not found, pSchema will remain NULL and nothing will match
72889   ** resulting in an appropriate error message toward the end of this routine
72890   */
72891   if( zDb ){
72892     for(i=0; i<db->nDb; i++){
72893       assert( db->aDb[i].zName );
72894       if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
72895         pSchema = db->aDb[i].pSchema;
72896         break;
72897       }
72898     }
72899   }
72900
72901   /* Start at the inner-most context and move outward until a match is found */
72902   while( pNC && cnt==0 ){
72903     ExprList *pEList;
72904     SrcList *pSrcList = pNC->pSrcList;
72905
72906     if( pSrcList ){
72907       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
72908         Table *pTab;
72909         Column *pCol;
72910   
72911         pTab = pItem->pTab;
72912         assert( pTab!=0 && pTab->zName!=0 );
72913         assert( pTab->nCol>0 );
72914         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
72915           int hit = 0;
72916           pEList = pItem->pSelect->pEList;
72917           for(j=0; j<pEList->nExpr; j++){
72918             if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
72919               cnt++;
72920               cntTab = 2;
72921               pMatch = pItem;
72922               pExpr->iColumn = j;
72923               hit = 1;
72924             }
72925           }
72926           if( hit || zTab==0 ) continue;
72927         }
72928         if( zDb && pTab->pSchema!=pSchema ){
72929           continue;
72930         }
72931         if( zTab ){
72932           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
72933           assert( zTabName!=0 );
72934           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
72935             continue;
72936           }
72937         }
72938         if( 0==(cntTab++) ){
72939           pMatch = pItem;
72940         }
72941         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
72942           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
72943             /* If there has been exactly one prior match and this match
72944             ** is for the right-hand table of a NATURAL JOIN or is in a 
72945             ** USING clause, then skip this match.
72946             */
72947             if( cnt==1 ){
72948               if( pItem->jointype & JT_NATURAL ) continue;
72949               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
72950             }
72951             cnt++;
72952             pMatch = pItem;
72953             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
72954             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
72955             break;
72956           }
72957         }
72958       }
72959       if( pMatch ){
72960         pExpr->iTable = pMatch->iCursor;
72961         pExpr->pTab = pMatch->pTab;
72962         pSchema = pExpr->pTab->pSchema;
72963       }
72964     } /* if( pSrcList ) */
72965
72966 #ifndef SQLITE_OMIT_TRIGGER
72967     /* If we have not already resolved the name, then maybe 
72968     ** it is a new.* or old.* trigger argument reference
72969     */
72970     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
72971       int op = pParse->eTriggerOp;
72972       Table *pTab = 0;
72973       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
72974       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
72975         pExpr->iTable = 1;
72976         pTab = pParse->pTriggerTab;
72977       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
72978         pExpr->iTable = 0;
72979         pTab = pParse->pTriggerTab;
72980       }
72981
72982       if( pTab ){ 
72983         int iCol;
72984         pSchema = pTab->pSchema;
72985         cntTab++;
72986         for(iCol=0; iCol<pTab->nCol; iCol++){
72987           Column *pCol = &pTab->aCol[iCol];
72988           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
72989             if( iCol==pTab->iPKey ){
72990               iCol = -1;
72991             }
72992             break;
72993           }
72994         }
72995         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
72996           iCol = -1;        /* IMP: R-44911-55124 */
72997         }
72998         if( iCol<pTab->nCol ){
72999           cnt++;
73000           if( iCol<0 ){
73001             pExpr->affinity = SQLITE_AFF_INTEGER;
73002           }else if( pExpr->iTable==0 ){
73003             testcase( iCol==31 );
73004             testcase( iCol==32 );
73005             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
73006           }else{
73007             testcase( iCol==31 );
73008             testcase( iCol==32 );
73009             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
73010           }
73011           pExpr->iColumn = (i16)iCol;
73012           pExpr->pTab = pTab;
73013           isTrigger = 1;
73014         }
73015       }
73016     }
73017 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
73018
73019     /*
73020     ** Perhaps the name is a reference to the ROWID
73021     */
73022     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
73023       cnt = 1;
73024       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
73025       pExpr->affinity = SQLITE_AFF_INTEGER;
73026     }
73027
73028     /*
73029     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
73030     ** might refer to an result-set alias.  This happens, for example, when
73031     ** we are resolving names in the WHERE clause of the following command:
73032     **
73033     **     SELECT a+b AS x FROM table WHERE x<10;
73034     **
73035     ** In cases like this, replace pExpr with a copy of the expression that
73036     ** forms the result set entry ("a+b" in the example) and return immediately.
73037     ** Note that the expression in the result set should have already been
73038     ** resolved by the time the WHERE clause is resolved.
73039     */
73040     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
73041       for(j=0; j<pEList->nExpr; j++){
73042         char *zAs = pEList->a[j].zName;
73043         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
73044           Expr *pOrig;
73045           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
73046           assert( pExpr->x.pList==0 );
73047           assert( pExpr->x.pSelect==0 );
73048           pOrig = pEList->a[j].pExpr;
73049           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
73050             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
73051             return WRC_Abort;
73052           }
73053           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
73054           cnt = 1;
73055           pMatch = 0;
73056           assert( zTab==0 && zDb==0 );
73057           goto lookupname_end;
73058         }
73059       } 
73060     }
73061
73062     /* Advance to the next name context.  The loop will exit when either
73063     ** we have a match (cnt>0) or when we run out of name contexts.
73064     */
73065     if( cnt==0 ){
73066       pNC = pNC->pNext;
73067       nSubquery++;
73068     }
73069   }
73070
73071   /*
73072   ** If X and Y are NULL (in other words if only the column name Z is
73073   ** supplied) and the value of Z is enclosed in double-quotes, then
73074   ** Z is a string literal if it doesn't match any column names.  In that
73075   ** case, we need to return right away and not make any changes to
73076   ** pExpr.
73077   **
73078   ** Because no reference was made to outer contexts, the pNC->nRef
73079   ** fields are not changed in any context.
73080   */
73081   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
73082     pExpr->op = TK_STRING;
73083     pExpr->pTab = 0;
73084     return WRC_Prune;
73085   }
73086
73087   /*
73088   ** cnt==0 means there was not match.  cnt>1 means there were two or
73089   ** more matches.  Either way, we have an error.
73090   */
73091   if( cnt!=1 ){
73092     const char *zErr;
73093     zErr = cnt==0 ? "no such column" : "ambiguous column name";
73094     if( zDb ){
73095       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
73096     }else if( zTab ){
73097       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
73098     }else{
73099       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
73100     }
73101     pParse->checkSchema = 1;
73102     pTopNC->nErr++;
73103   }
73104
73105   /* If a column from a table in pSrcList is referenced, then record
73106   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
73107   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
73108   ** column number is greater than the number of bits in the bitmask
73109   ** then set the high-order bit of the bitmask.
73110   */
73111   if( pExpr->iColumn>=0 && pMatch!=0 ){
73112     int n = pExpr->iColumn;
73113     testcase( n==BMS-1 );
73114     if( n>=BMS ){
73115       n = BMS-1;
73116     }
73117     assert( pMatch->iCursor==pExpr->iTable );
73118     pMatch->colUsed |= ((Bitmask)1)<<n;
73119   }
73120
73121   /* Clean up and return
73122   */
73123   sqlite3ExprDelete(db, pExpr->pLeft);
73124   pExpr->pLeft = 0;
73125   sqlite3ExprDelete(db, pExpr->pRight);
73126   pExpr->pRight = 0;
73127   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
73128 lookupname_end:
73129   if( cnt==1 ){
73130     assert( pNC!=0 );
73131     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
73132     /* Increment the nRef value on all name contexts from TopNC up to
73133     ** the point where the name matched. */
73134     for(;;){
73135       assert( pTopNC!=0 );
73136       pTopNC->nRef++;
73137       if( pTopNC==pNC ) break;
73138       pTopNC = pTopNC->pNext;
73139     }
73140     return WRC_Prune;
73141   } else {
73142     return WRC_Abort;
73143   }
73144 }
73145
73146 /*
73147 ** Allocate and return a pointer to an expression to load the column iCol
73148 ** from datasource iSrc in SrcList pSrc.
73149 */
73150 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
73151   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
73152   if( p ){
73153     struct SrcList_item *pItem = &pSrc->a[iSrc];
73154     p->pTab = pItem->pTab;
73155     p->iTable = pItem->iCursor;
73156     if( p->pTab->iPKey==iCol ){
73157       p->iColumn = -1;
73158     }else{
73159       p->iColumn = (ynVar)iCol;
73160       testcase( iCol==BMS );
73161       testcase( iCol==BMS-1 );
73162       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
73163     }
73164     ExprSetProperty(p, EP_Resolved);
73165   }
73166   return p;
73167 }
73168
73169 /*
73170 ** This routine is callback for sqlite3WalkExpr().
73171 **
73172 ** Resolve symbolic names into TK_COLUMN operators for the current
73173 ** node in the expression tree.  Return 0 to continue the search down
73174 ** the tree or 2 to abort the tree walk.
73175 **
73176 ** This routine also does error checking and name resolution for
73177 ** function names.  The operator for aggregate functions is changed
73178 ** to TK_AGG_FUNCTION.
73179 */
73180 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
73181   NameContext *pNC;
73182   Parse *pParse;
73183
73184   pNC = pWalker->u.pNC;
73185   assert( pNC!=0 );
73186   pParse = pNC->pParse;
73187   assert( pParse==pWalker->pParse );
73188
73189   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
73190   ExprSetProperty(pExpr, EP_Resolved);
73191 #ifndef NDEBUG
73192   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
73193     SrcList *pSrcList = pNC->pSrcList;
73194     int i;
73195     for(i=0; i<pNC->pSrcList->nSrc; i++){
73196       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
73197     }
73198   }
73199 #endif
73200   switch( pExpr->op ){
73201
73202 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
73203     /* The special operator TK_ROW means use the rowid for the first
73204     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
73205     ** clause processing on UPDATE and DELETE statements.
73206     */
73207     case TK_ROW: {
73208       SrcList *pSrcList = pNC->pSrcList;
73209       struct SrcList_item *pItem;
73210       assert( pSrcList && pSrcList->nSrc==1 );
73211       pItem = pSrcList->a; 
73212       pExpr->op = TK_COLUMN;
73213       pExpr->pTab = pItem->pTab;
73214       pExpr->iTable = pItem->iCursor;
73215       pExpr->iColumn = -1;
73216       pExpr->affinity = SQLITE_AFF_INTEGER;
73217       break;
73218     }
73219 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
73220
73221     /* A lone identifier is the name of a column.
73222     */
73223     case TK_ID: {
73224       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
73225     }
73226   
73227     /* A table name and column name:     ID.ID
73228     ** Or a database, table and column:  ID.ID.ID
73229     */
73230     case TK_DOT: {
73231       const char *zColumn;
73232       const char *zTable;
73233       const char *zDb;
73234       Expr *pRight;
73235
73236       /* if( pSrcList==0 ) break; */
73237       pRight = pExpr->pRight;
73238       if( pRight->op==TK_ID ){
73239         zDb = 0;
73240         zTable = pExpr->pLeft->u.zToken;
73241         zColumn = pRight->u.zToken;
73242       }else{
73243         assert( pRight->op==TK_DOT );
73244         zDb = pExpr->pLeft->u.zToken;
73245         zTable = pRight->pLeft->u.zToken;
73246         zColumn = pRight->pRight->u.zToken;
73247       }
73248       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
73249     }
73250
73251     /* Resolve function names
73252     */
73253     case TK_CONST_FUNC:
73254     case TK_FUNCTION: {
73255       ExprList *pList = pExpr->x.pList;    /* The argument list */
73256       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
73257       int no_such_func = 0;       /* True if no such function exists */
73258       int wrong_num_args = 0;     /* True if wrong number of arguments */
73259       int is_agg = 0;             /* True if is an aggregate function */
73260       int auth;                   /* Authorization to use the function */
73261       int nId;                    /* Number of characters in function name */
73262       const char *zId;            /* The function name. */
73263       FuncDef *pDef;              /* Information about the function */
73264       u8 enc = ENC(pParse->db);   /* The database encoding */
73265
73266       testcase( pExpr->op==TK_CONST_FUNC );
73267       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73268       zId = pExpr->u.zToken;
73269       nId = sqlite3Strlen30(zId);
73270       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
73271       if( pDef==0 ){
73272         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
73273         if( pDef==0 ){
73274           no_such_func = 1;
73275         }else{
73276           wrong_num_args = 1;
73277         }
73278       }else{
73279         is_agg = pDef->xFunc==0;
73280       }
73281 #ifndef SQLITE_OMIT_AUTHORIZATION
73282       if( pDef ){
73283         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
73284         if( auth!=SQLITE_OK ){
73285           if( auth==SQLITE_DENY ){
73286             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
73287                                     pDef->zName);
73288             pNC->nErr++;
73289           }
73290           pExpr->op = TK_NULL;
73291           return WRC_Prune;
73292         }
73293       }
73294 #endif
73295       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
73296         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
73297         pNC->nErr++;
73298         is_agg = 0;
73299       }else if( no_such_func && pParse->db->init.busy==0 ){
73300         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
73301         pNC->nErr++;
73302       }else if( wrong_num_args ){
73303         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
73304              nId, zId);
73305         pNC->nErr++;
73306       }
73307       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
73308       sqlite3WalkExprList(pWalker, pList);
73309       if( is_agg ){
73310         NameContext *pNC2 = pNC;
73311         pExpr->op = TK_AGG_FUNCTION;
73312         pExpr->op2 = 0;
73313         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
73314           pExpr->op2++;
73315           pNC2 = pNC2->pNext;
73316         }
73317         if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
73318         pNC->ncFlags |= NC_AllowAgg;
73319       }
73320       /* FIX ME:  Compute pExpr->affinity based on the expected return
73321       ** type of the function 
73322       */
73323       return WRC_Prune;
73324     }
73325 #ifndef SQLITE_OMIT_SUBQUERY
73326     case TK_SELECT:
73327     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
73328 #endif
73329     case TK_IN: {
73330       testcase( pExpr->op==TK_IN );
73331       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73332         int nRef = pNC->nRef;
73333 #ifndef SQLITE_OMIT_CHECK
73334         if( (pNC->ncFlags & NC_IsCheck)!=0 ){
73335           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
73336         }
73337 #endif
73338         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
73339         assert( pNC->nRef>=nRef );
73340         if( nRef!=pNC->nRef ){
73341           ExprSetProperty(pExpr, EP_VarSelect);
73342         }
73343       }
73344       break;
73345     }
73346 #ifndef SQLITE_OMIT_CHECK
73347     case TK_VARIABLE: {
73348       if( (pNC->ncFlags & NC_IsCheck)!=0 ){
73349         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
73350       }
73351       break;
73352     }
73353 #endif
73354   }
73355   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
73356 }
73357
73358 /*
73359 ** pEList is a list of expressions which are really the result set of the
73360 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
73361 ** This routine checks to see if pE is a simple identifier which corresponds
73362 ** to the AS-name of one of the terms of the expression list.  If it is,
73363 ** this routine return an integer between 1 and N where N is the number of
73364 ** elements in pEList, corresponding to the matching entry.  If there is
73365 ** no match, or if pE is not a simple identifier, then this routine
73366 ** return 0.
73367 **
73368 ** pEList has been resolved.  pE has not.
73369 */
73370 static int resolveAsName(
73371   Parse *pParse,     /* Parsing context for error messages */
73372   ExprList *pEList,  /* List of expressions to scan */
73373   Expr *pE           /* Expression we are trying to match */
73374 ){
73375   int i;             /* Loop counter */
73376
73377   UNUSED_PARAMETER(pParse);
73378
73379   if( pE->op==TK_ID ){
73380     char *zCol = pE->u.zToken;
73381     for(i=0; i<pEList->nExpr; i++){
73382       char *zAs = pEList->a[i].zName;
73383       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
73384         return i+1;
73385       }
73386     }
73387   }
73388   return 0;
73389 }
73390
73391 /*
73392 ** pE is a pointer to an expression which is a single term in the
73393 ** ORDER BY of a compound SELECT.  The expression has not been
73394 ** name resolved.
73395 **
73396 ** At the point this routine is called, we already know that the
73397 ** ORDER BY term is not an integer index into the result set.  That
73398 ** case is handled by the calling routine.
73399 **
73400 ** Attempt to match pE against result set columns in the left-most
73401 ** SELECT statement.  Return the index i of the matching column,
73402 ** as an indication to the caller that it should sort by the i-th column.
73403 ** The left-most column is 1.  In other words, the value returned is the
73404 ** same integer value that would be used in the SQL statement to indicate
73405 ** the column.
73406 **
73407 ** If there is no match, return 0.  Return -1 if an error occurs.
73408 */
73409 static int resolveOrderByTermToExprList(
73410   Parse *pParse,     /* Parsing context for error messages */
73411   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
73412   Expr *pE           /* The specific ORDER BY term */
73413 ){
73414   int i;             /* Loop counter */
73415   ExprList *pEList;  /* The columns of the result set */
73416   NameContext nc;    /* Name context for resolving pE */
73417   sqlite3 *db;       /* Database connection */
73418   int rc;            /* Return code from subprocedures */
73419   u8 savedSuppErr;   /* Saved value of db->suppressErr */
73420
73421   assert( sqlite3ExprIsInteger(pE, &i)==0 );
73422   pEList = pSelect->pEList;
73423
73424   /* Resolve all names in the ORDER BY term expression
73425   */
73426   memset(&nc, 0, sizeof(nc));
73427   nc.pParse = pParse;
73428   nc.pSrcList = pSelect->pSrc;
73429   nc.pEList = pEList;
73430   nc.ncFlags = NC_AllowAgg;
73431   nc.nErr = 0;
73432   db = pParse->db;
73433   savedSuppErr = db->suppressErr;
73434   db->suppressErr = 1;
73435   rc = sqlite3ResolveExprNames(&nc, pE);
73436   db->suppressErr = savedSuppErr;
73437   if( rc ) return 0;
73438
73439   /* Try to match the ORDER BY expression against an expression
73440   ** in the result set.  Return an 1-based index of the matching
73441   ** result-set entry.
73442   */
73443   for(i=0; i<pEList->nExpr; i++){
73444     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
73445       return i+1;
73446     }
73447   }
73448
73449   /* If no match, return 0. */
73450   return 0;
73451 }
73452
73453 /*
73454 ** Generate an ORDER BY or GROUP BY term out-of-range error.
73455 */
73456 static void resolveOutOfRangeError(
73457   Parse *pParse,         /* The error context into which to write the error */
73458   const char *zType,     /* "ORDER" or "GROUP" */
73459   int i,                 /* The index (1-based) of the term out of range */
73460   int mx                 /* Largest permissible value of i */
73461 ){
73462   sqlite3ErrorMsg(pParse, 
73463     "%r %s BY term out of range - should be "
73464     "between 1 and %d", i, zType, mx);
73465 }
73466
73467 /*
73468 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
73469 ** each term of the ORDER BY clause is a constant integer between 1
73470 ** and N where N is the number of columns in the compound SELECT.
73471 **
73472 ** ORDER BY terms that are already an integer between 1 and N are
73473 ** unmodified.  ORDER BY terms that are integers outside the range of
73474 ** 1 through N generate an error.  ORDER BY terms that are expressions
73475 ** are matched against result set expressions of compound SELECT
73476 ** beginning with the left-most SELECT and working toward the right.
73477 ** At the first match, the ORDER BY expression is transformed into
73478 ** the integer column number.
73479 **
73480 ** Return the number of errors seen.
73481 */
73482 static int resolveCompoundOrderBy(
73483   Parse *pParse,        /* Parsing context.  Leave error messages here */
73484   Select *pSelect       /* The SELECT statement containing the ORDER BY */
73485 ){
73486   int i;
73487   ExprList *pOrderBy;
73488   ExprList *pEList;
73489   sqlite3 *db;
73490   int moreToDo = 1;
73491
73492   pOrderBy = pSelect->pOrderBy;
73493   if( pOrderBy==0 ) return 0;
73494   db = pParse->db;
73495 #if SQLITE_MAX_COLUMN
73496   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
73497     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
73498     return 1;
73499   }
73500 #endif
73501   for(i=0; i<pOrderBy->nExpr; i++){
73502     pOrderBy->a[i].done = 0;
73503   }
73504   pSelect->pNext = 0;
73505   while( pSelect->pPrior ){
73506     pSelect->pPrior->pNext = pSelect;
73507     pSelect = pSelect->pPrior;
73508   }
73509   while( pSelect && moreToDo ){
73510     struct ExprList_item *pItem;
73511     moreToDo = 0;
73512     pEList = pSelect->pEList;
73513     assert( pEList!=0 );
73514     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73515       int iCol = -1;
73516       Expr *pE, *pDup;
73517       if( pItem->done ) continue;
73518       pE = sqlite3ExprSkipCollate(pItem->pExpr);
73519       if( sqlite3ExprIsInteger(pE, &iCol) ){
73520         if( iCol<=0 || iCol>pEList->nExpr ){
73521           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
73522           return 1;
73523         }
73524       }else{
73525         iCol = resolveAsName(pParse, pEList, pE);
73526         if( iCol==0 ){
73527           pDup = sqlite3ExprDup(db, pE, 0);
73528           if( !db->mallocFailed ){
73529             assert(pDup);
73530             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
73531           }
73532           sqlite3ExprDelete(db, pDup);
73533         }
73534       }
73535       if( iCol>0 ){
73536         /* Convert the ORDER BY term into an integer column number iCol,
73537         ** taking care to preserve the COLLATE clause if it exists */
73538         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
73539         if( pNew==0 ) return 1;
73540         pNew->flags |= EP_IntValue;
73541         pNew->u.iValue = iCol;
73542         if( pItem->pExpr==pE ){
73543           pItem->pExpr = pNew;
73544         }else{
73545           assert( pItem->pExpr->op==TK_COLLATE );
73546           assert( pItem->pExpr->pLeft==pE );
73547           pItem->pExpr->pLeft = pNew;
73548         }
73549         sqlite3ExprDelete(db, pE);
73550         pItem->iOrderByCol = (u16)iCol;
73551         pItem->done = 1;
73552       }else{
73553         moreToDo = 1;
73554       }
73555     }
73556     pSelect = pSelect->pNext;
73557   }
73558   for(i=0; i<pOrderBy->nExpr; i++){
73559     if( pOrderBy->a[i].done==0 ){
73560       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
73561             "column in the result set", i+1);
73562       return 1;
73563     }
73564   }
73565   return 0;
73566 }
73567
73568 /*
73569 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
73570 ** the SELECT statement pSelect.  If any term is reference to a
73571 ** result set expression (as determined by the ExprList.a.iCol field)
73572 ** then convert that term into a copy of the corresponding result set
73573 ** column.
73574 **
73575 ** If any errors are detected, add an error message to pParse and
73576 ** return non-zero.  Return zero if no errors are seen.
73577 */
73578 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
73579   Parse *pParse,        /* Parsing context.  Leave error messages here */
73580   Select *pSelect,      /* The SELECT statement containing the clause */
73581   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
73582   const char *zType     /* "ORDER" or "GROUP" */
73583 ){
73584   int i;
73585   sqlite3 *db = pParse->db;
73586   ExprList *pEList;
73587   struct ExprList_item *pItem;
73588
73589   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
73590 #if SQLITE_MAX_COLUMN
73591   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
73592     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
73593     return 1;
73594   }
73595 #endif
73596   pEList = pSelect->pEList;
73597   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
73598   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73599     if( pItem->iOrderByCol ){
73600       if( pItem->iOrderByCol>pEList->nExpr ){
73601         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
73602         return 1;
73603       }
73604       resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
73605     }
73606   }
73607   return 0;
73608 }
73609
73610 /*
73611 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
73612 ** The Name context of the SELECT statement is pNC.  zType is either
73613 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
73614 **
73615 ** This routine resolves each term of the clause into an expression.
73616 ** If the order-by term is an integer I between 1 and N (where N is the
73617 ** number of columns in the result set of the SELECT) then the expression
73618 ** in the resolution is a copy of the I-th result-set expression.  If
73619 ** the order-by term is an identify that corresponds to the AS-name of
73620 ** a result-set expression, then the term resolves to a copy of the
73621 ** result-set expression.  Otherwise, the expression is resolved in
73622 ** the usual way - using sqlite3ResolveExprNames().
73623 **
73624 ** This routine returns the number of errors.  If errors occur, then
73625 ** an appropriate error message might be left in pParse.  (OOM errors
73626 ** excepted.)
73627 */
73628 static int resolveOrderGroupBy(
73629   NameContext *pNC,     /* The name context of the SELECT statement */
73630   Select *pSelect,      /* The SELECT statement holding pOrderBy */
73631   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
73632   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
73633 ){
73634   int i, j;                      /* Loop counters */
73635   int iCol;                      /* Column number */
73636   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
73637   Parse *pParse;                 /* Parsing context */
73638   int nResult;                   /* Number of terms in the result set */
73639
73640   if( pOrderBy==0 ) return 0;
73641   nResult = pSelect->pEList->nExpr;
73642   pParse = pNC->pParse;
73643   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73644     Expr *pE = pItem->pExpr;
73645     iCol = resolveAsName(pParse, pSelect->pEList, pE);
73646     if( iCol>0 ){
73647       /* If an AS-name match is found, mark this ORDER BY column as being
73648       ** a copy of the iCol-th result-set column.  The subsequent call to
73649       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
73650       ** copy of the iCol-th result-set expression. */
73651       pItem->iOrderByCol = (u16)iCol;
73652       continue;
73653     }
73654     if( sqlite3ExprIsInteger(sqlite3ExprSkipCollate(pE), &iCol) ){
73655       /* The ORDER BY term is an integer constant.  Again, set the column
73656       ** number so that sqlite3ResolveOrderGroupBy() will convert the
73657       ** order-by term to a copy of the result-set expression */
73658       if( iCol<1 || iCol>0xffff ){
73659         resolveOutOfRangeError(pParse, zType, i+1, nResult);
73660         return 1;
73661       }
73662       pItem->iOrderByCol = (u16)iCol;
73663       continue;
73664     }
73665
73666     /* Otherwise, treat the ORDER BY term as an ordinary expression */
73667     pItem->iOrderByCol = 0;
73668     if( sqlite3ResolveExprNames(pNC, pE) ){
73669       return 1;
73670     }
73671     for(j=0; j<pSelect->pEList->nExpr; j++){
73672       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
73673         pItem->iOrderByCol = j+1;
73674       }
73675     }
73676   }
73677   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
73678 }
73679
73680 /*
73681 ** Resolve names in the SELECT statement p and all of its descendents.
73682 */
73683 static int resolveSelectStep(Walker *pWalker, Select *p){
73684   NameContext *pOuterNC;  /* Context that contains this SELECT */
73685   NameContext sNC;        /* Name context of this SELECT */
73686   int isCompound;         /* True if p is a compound select */
73687   int nCompound;          /* Number of compound terms processed so far */
73688   Parse *pParse;          /* Parsing context */
73689   ExprList *pEList;       /* Result set expression list */
73690   int i;                  /* Loop counter */
73691   ExprList *pGroupBy;     /* The GROUP BY clause */
73692   Select *pLeftmost;      /* Left-most of SELECT of a compound */
73693   sqlite3 *db;            /* Database connection */
73694   
73695
73696   assert( p!=0 );
73697   if( p->selFlags & SF_Resolved ){
73698     return WRC_Prune;
73699   }
73700   pOuterNC = pWalker->u.pNC;
73701   pParse = pWalker->pParse;
73702   db = pParse->db;
73703
73704   /* Normally sqlite3SelectExpand() will be called first and will have
73705   ** already expanded this SELECT.  However, if this is a subquery within
73706   ** an expression, sqlite3ResolveExprNames() will be called without a
73707   ** prior call to sqlite3SelectExpand().  When that happens, let
73708   ** sqlite3SelectPrep() do all of the processing for this SELECT.
73709   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
73710   ** this routine in the correct order.
73711   */
73712   if( (p->selFlags & SF_Expanded)==0 ){
73713     sqlite3SelectPrep(pParse, p, pOuterNC);
73714     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
73715   }
73716
73717   isCompound = p->pPrior!=0;
73718   nCompound = 0;
73719   pLeftmost = p;
73720   while( p ){
73721     assert( (p->selFlags & SF_Expanded)!=0 );
73722     assert( (p->selFlags & SF_Resolved)==0 );
73723     p->selFlags |= SF_Resolved;
73724
73725     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
73726     ** are not allowed to refer to any names, so pass an empty NameContext.
73727     */
73728     memset(&sNC, 0, sizeof(sNC));
73729     sNC.pParse = pParse;
73730     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
73731         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
73732       return WRC_Abort;
73733     }
73734   
73735     /* Recursively resolve names in all subqueries
73736     */
73737     for(i=0; i<p->pSrc->nSrc; i++){
73738       struct SrcList_item *pItem = &p->pSrc->a[i];
73739       if( pItem->pSelect ){
73740         NameContext *pNC;         /* Used to iterate name contexts */
73741         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
73742         const char *zSavedContext = pParse->zAuthContext;
73743
73744         /* Count the total number of references to pOuterNC and all of its
73745         ** parent contexts. After resolving references to expressions in
73746         ** pItem->pSelect, check if this value has changed. If so, then
73747         ** SELECT statement pItem->pSelect must be correlated. Set the
73748         ** pItem->isCorrelated flag if this is the case. */
73749         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
73750
73751         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
73752         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
73753         pParse->zAuthContext = zSavedContext;
73754         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
73755
73756         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
73757         assert( pItem->isCorrelated==0 && nRef<=0 );
73758         pItem->isCorrelated = (nRef!=0);
73759       }
73760     }
73761   
73762     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
73763     ** resolve the result-set expression list.
73764     */
73765     sNC.ncFlags = NC_AllowAgg;
73766     sNC.pSrcList = p->pSrc;
73767     sNC.pNext = pOuterNC;
73768   
73769     /* Resolve names in the result set. */
73770     pEList = p->pEList;
73771     assert( pEList!=0 );
73772     for(i=0; i<pEList->nExpr; i++){
73773       Expr *pX = pEList->a[i].pExpr;
73774       if( sqlite3ResolveExprNames(&sNC, pX) ){
73775         return WRC_Abort;
73776       }
73777     }
73778   
73779     /* If there are no aggregate functions in the result-set, and no GROUP BY 
73780     ** expression, do not allow aggregates in any of the other expressions.
73781     */
73782     assert( (p->selFlags & SF_Aggregate)==0 );
73783     pGroupBy = p->pGroupBy;
73784     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
73785       p->selFlags |= SF_Aggregate;
73786     }else{
73787       sNC.ncFlags &= ~NC_AllowAgg;
73788     }
73789   
73790     /* If a HAVING clause is present, then there must be a GROUP BY clause.
73791     */
73792     if( p->pHaving && !pGroupBy ){
73793       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
73794       return WRC_Abort;
73795     }
73796   
73797     /* Add the expression list to the name-context before parsing the
73798     ** other expressions in the SELECT statement. This is so that
73799     ** expressions in the WHERE clause (etc.) can refer to expressions by
73800     ** aliases in the result set.
73801     **
73802     ** Minor point: If this is the case, then the expression will be
73803     ** re-evaluated for each reference to it.
73804     */
73805     sNC.pEList = p->pEList;
73806     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
73807        sqlite3ResolveExprNames(&sNC, p->pHaving)
73808     ){
73809       return WRC_Abort;
73810     }
73811
73812     /* The ORDER BY and GROUP BY clauses may not refer to terms in
73813     ** outer queries 
73814     */
73815     sNC.pNext = 0;
73816     sNC.ncFlags |= NC_AllowAgg;
73817
73818     /* Process the ORDER BY clause for singleton SELECT statements.
73819     ** The ORDER BY clause for compounds SELECT statements is handled
73820     ** below, after all of the result-sets for all of the elements of
73821     ** the compound have been resolved.
73822     */
73823     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
73824       return WRC_Abort;
73825     }
73826     if( db->mallocFailed ){
73827       return WRC_Abort;
73828     }
73829   
73830     /* Resolve the GROUP BY clause.  At the same time, make sure 
73831     ** the GROUP BY clause does not contain aggregate functions.
73832     */
73833     if( pGroupBy ){
73834       struct ExprList_item *pItem;
73835     
73836       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
73837         return WRC_Abort;
73838       }
73839       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
73840         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
73841           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
73842               "the GROUP BY clause");
73843           return WRC_Abort;
73844         }
73845       }
73846     }
73847
73848     /* Advance to the next term of the compound
73849     */
73850     p = p->pPrior;
73851     nCompound++;
73852   }
73853
73854   /* Resolve the ORDER BY on a compound SELECT after all terms of
73855   ** the compound have been resolved.
73856   */
73857   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
73858     return WRC_Abort;
73859   }
73860
73861   return WRC_Prune;
73862 }
73863
73864 /*
73865 ** This routine walks an expression tree and resolves references to
73866 ** table columns and result-set columns.  At the same time, do error
73867 ** checking on function usage and set a flag if any aggregate functions
73868 ** are seen.
73869 **
73870 ** To resolve table columns references we look for nodes (or subtrees) of the 
73871 ** form X.Y.Z or Y.Z or just Z where
73872 **
73873 **      X:   The name of a database.  Ex:  "main" or "temp" or
73874 **           the symbolic name assigned to an ATTACH-ed database.
73875 **
73876 **      Y:   The name of a table in a FROM clause.  Or in a trigger
73877 **           one of the special names "old" or "new".
73878 **
73879 **      Z:   The name of a column in table Y.
73880 **
73881 ** The node at the root of the subtree is modified as follows:
73882 **
73883 **    Expr.op        Changed to TK_COLUMN
73884 **    Expr.pTab      Points to the Table object for X.Y
73885 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
73886 **    Expr.iTable    The VDBE cursor number for X.Y
73887 **
73888 **
73889 ** To resolve result-set references, look for expression nodes of the
73890 ** form Z (with no X and Y prefix) where the Z matches the right-hand
73891 ** size of an AS clause in the result-set of a SELECT.  The Z expression
73892 ** is replaced by a copy of the left-hand side of the result-set expression.
73893 ** Table-name and function resolution occurs on the substituted expression
73894 ** tree.  For example, in:
73895 **
73896 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
73897 **
73898 ** The "x" term of the order by is replaced by "a+b" to render:
73899 **
73900 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
73901 **
73902 ** Function calls are checked to make sure that the function is 
73903 ** defined and that the correct number of arguments are specified.
73904 ** If the function is an aggregate function, then the NC_HasAgg flag is
73905 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
73906 ** If an expression contains aggregate functions then the EP_Agg
73907 ** property on the expression is set.
73908 **
73909 ** An error message is left in pParse if anything is amiss.  The number
73910 ** if errors is returned.
73911 */
73912 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
73913   NameContext *pNC,       /* Namespace to resolve expressions in. */
73914   Expr *pExpr             /* The expression to be analyzed. */
73915 ){
73916   u8 savedHasAgg;
73917   Walker w;
73918
73919   if( pExpr==0 ) return 0;
73920 #if SQLITE_MAX_EXPR_DEPTH>0
73921   {
73922     Parse *pParse = pNC->pParse;
73923     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
73924       return 1;
73925     }
73926     pParse->nHeight += pExpr->nHeight;
73927   }
73928 #endif
73929   savedHasAgg = pNC->ncFlags & NC_HasAgg;
73930   pNC->ncFlags &= ~NC_HasAgg;
73931   w.xExprCallback = resolveExprStep;
73932   w.xSelectCallback = resolveSelectStep;
73933   w.pParse = pNC->pParse;
73934   w.u.pNC = pNC;
73935   sqlite3WalkExpr(&w, pExpr);
73936 #if SQLITE_MAX_EXPR_DEPTH>0
73937   pNC->pParse->nHeight -= pExpr->nHeight;
73938 #endif
73939   if( pNC->nErr>0 || w.pParse->nErr>0 ){
73940     ExprSetProperty(pExpr, EP_Error);
73941   }
73942   if( pNC->ncFlags & NC_HasAgg ){
73943     ExprSetProperty(pExpr, EP_Agg);
73944   }else if( savedHasAgg ){
73945     pNC->ncFlags |= NC_HasAgg;
73946   }
73947   return ExprHasProperty(pExpr, EP_Error);
73948 }
73949
73950
73951 /*
73952 ** Resolve all names in all expressions of a SELECT and in all
73953 ** decendents of the SELECT, including compounds off of p->pPrior,
73954 ** subqueries in expressions, and subqueries used as FROM clause
73955 ** terms.
73956 **
73957 ** See sqlite3ResolveExprNames() for a description of the kinds of
73958 ** transformations that occur.
73959 **
73960 ** All SELECT statements should have been expanded using
73961 ** sqlite3SelectExpand() prior to invoking this routine.
73962 */
73963 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
73964   Parse *pParse,         /* The parser context */
73965   Select *p,             /* The SELECT statement being coded. */
73966   NameContext *pOuterNC  /* Name context for parent SELECT statement */
73967 ){
73968   Walker w;
73969
73970   assert( p!=0 );
73971   w.xExprCallback = resolveExprStep;
73972   w.xSelectCallback = resolveSelectStep;
73973   w.pParse = pParse;
73974   w.u.pNC = pOuterNC;
73975   sqlite3WalkSelect(&w, p);
73976 }
73977
73978 /************** End of resolve.c *********************************************/
73979 /************** Begin file expr.c ********************************************/
73980 /*
73981 ** 2001 September 15
73982 **
73983 ** The author disclaims copyright to this source code.  In place of
73984 ** a legal notice, here is a blessing:
73985 **
73986 **    May you do good and not evil.
73987 **    May you find forgiveness for yourself and forgive others.
73988 **    May you share freely, never taking more than you give.
73989 **
73990 *************************************************************************
73991 ** This file contains routines used for analyzing expressions and
73992 ** for generating VDBE code that evaluates expressions in SQLite.
73993 */
73994
73995 /*
73996 ** Return the 'affinity' of the expression pExpr if any.
73997 **
73998 ** If pExpr is a column, a reference to a column via an 'AS' alias,
73999 ** or a sub-select with a column as the return value, then the 
74000 ** affinity of that column is returned. Otherwise, 0x00 is returned,
74001 ** indicating no affinity for the expression.
74002 **
74003 ** i.e. the WHERE clause expresssions in the following statements all
74004 ** have an affinity:
74005 **
74006 ** CREATE TABLE t1(a);
74007 ** SELECT * FROM t1 WHERE a;
74008 ** SELECT a AS b FROM t1 WHERE b;
74009 ** SELECT * FROM t1 WHERE (select a from t1);
74010 */
74011 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
74012   int op;
74013   pExpr = sqlite3ExprSkipCollate(pExpr);
74014   op = pExpr->op;
74015   if( op==TK_SELECT ){
74016     assert( pExpr->flags&EP_xIsSelect );
74017     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
74018   }
74019 #ifndef SQLITE_OMIT_CAST
74020   if( op==TK_CAST ){
74021     assert( !ExprHasProperty(pExpr, EP_IntValue) );
74022     return sqlite3AffinityType(pExpr->u.zToken);
74023   }
74024 #endif
74025   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
74026    && pExpr->pTab!=0
74027   ){
74028     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
74029     ** a TK_COLUMN but was previously evaluated and cached in a register */
74030     int j = pExpr->iColumn;
74031     if( j<0 ) return SQLITE_AFF_INTEGER;
74032     assert( pExpr->pTab && j<pExpr->pTab->nCol );
74033     return pExpr->pTab->aCol[j].affinity;
74034   }
74035   return pExpr->affinity;
74036 }
74037
74038 /*
74039 ** Set the collating sequence for expression pExpr to be the collating
74040 ** sequence named by pToken.   Return a pointer to a new Expr node that
74041 ** implements the COLLATE operator.
74042 **
74043 ** If a memory allocation error occurs, that fact is recorded in pParse->db
74044 ** and the pExpr parameter is returned unchanged.
74045 */
74046 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
74047   if( pCollName->n>0 ){
74048     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
74049     if( pNew ){
74050       pNew->pLeft = pExpr;
74051       pNew->flags |= EP_Collate;
74052       pExpr = pNew;
74053     }
74054   }
74055   return pExpr;
74056 }
74057 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
74058   Token s;
74059   assert( zC!=0 );
74060   s.z = zC;
74061   s.n = sqlite3Strlen30(s.z);
74062   return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
74063 }
74064
74065 /*
74066 ** Skip over any TK_COLLATE and/or TK_AS operators at the root of
74067 ** an expression.
74068 */
74069 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
74070   while( pExpr && (pExpr->op==TK_COLLATE || pExpr->op==TK_AS) ){
74071     pExpr = pExpr->pLeft;
74072   }
74073   return pExpr;
74074 }
74075
74076 /*
74077 ** Return the collation sequence for the expression pExpr. If
74078 ** there is no defined collating sequence, return NULL.
74079 **
74080 ** The collating sequence might be determined by a COLLATE operator
74081 ** or by the presence of a column with a defined collating sequence.
74082 ** COLLATE operators take first precedence.  Left operands take
74083 ** precedence over right operands.
74084 */
74085 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
74086   sqlite3 *db = pParse->db;
74087   CollSeq *pColl = 0;
74088   Expr *p = pExpr;
74089   while( p ){
74090     int op = p->op;
74091     if( op==TK_CAST || op==TK_UPLUS ){
74092       p = p->pLeft;
74093       continue;
74094     }
74095     assert( op!=TK_REGISTER || p->op2!=TK_COLLATE );
74096     if( op==TK_COLLATE ){
74097       if( db->init.busy ){
74098         /* Do not report errors when parsing while the schema */
74099         pColl = sqlite3FindCollSeq(db, ENC(db), p->u.zToken, 0);
74100       }else{
74101         pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
74102       }
74103       break;
74104     }
74105     if( p->pTab!=0
74106      && (op==TK_AGG_COLUMN || op==TK_COLUMN
74107           || op==TK_REGISTER || op==TK_TRIGGER)
74108     ){
74109       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
74110       ** a TK_COLUMN but was previously evaluated and cached in a register */
74111       int j = p->iColumn;
74112       if( j>=0 ){
74113         const char *zColl = p->pTab->aCol[j].zColl;
74114         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
74115       }
74116       break;
74117     }
74118     if( p->flags & EP_Collate ){
74119       if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
74120         p = p->pLeft;
74121       }else{
74122         p = p->pRight;
74123       }
74124     }else{
74125       break;
74126     }
74127   }
74128   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
74129     pColl = 0;
74130   }
74131   return pColl;
74132 }
74133
74134 /*
74135 ** pExpr is an operand of a comparison operator.  aff2 is the
74136 ** type affinity of the other operand.  This routine returns the
74137 ** type affinity that should be used for the comparison operator.
74138 */
74139 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
74140   char aff1 = sqlite3ExprAffinity(pExpr);
74141   if( aff1 && aff2 ){
74142     /* Both sides of the comparison are columns. If one has numeric
74143     ** affinity, use that. Otherwise use no affinity.
74144     */
74145     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
74146       return SQLITE_AFF_NUMERIC;
74147     }else{
74148       return SQLITE_AFF_NONE;
74149     }
74150   }else if( !aff1 && !aff2 ){
74151     /* Neither side of the comparison is a column.  Compare the
74152     ** results directly.
74153     */
74154     return SQLITE_AFF_NONE;
74155   }else{
74156     /* One side is a column, the other is not. Use the columns affinity. */
74157     assert( aff1==0 || aff2==0 );
74158     return (aff1 + aff2);
74159   }
74160 }
74161
74162 /*
74163 ** pExpr is a comparison operator.  Return the type affinity that should
74164 ** be applied to both operands prior to doing the comparison.
74165 */
74166 static char comparisonAffinity(Expr *pExpr){
74167   char aff;
74168   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
74169           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
74170           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
74171   assert( pExpr->pLeft );
74172   aff = sqlite3ExprAffinity(pExpr->pLeft);
74173   if( pExpr->pRight ){
74174     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
74175   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74176     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
74177   }else if( !aff ){
74178     aff = SQLITE_AFF_NONE;
74179   }
74180   return aff;
74181 }
74182
74183 /*
74184 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
74185 ** idx_affinity is the affinity of an indexed column. Return true
74186 ** if the index with affinity idx_affinity may be used to implement
74187 ** the comparison in pExpr.
74188 */
74189 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
74190   char aff = comparisonAffinity(pExpr);
74191   switch( aff ){
74192     case SQLITE_AFF_NONE:
74193       return 1;
74194     case SQLITE_AFF_TEXT:
74195       return idx_affinity==SQLITE_AFF_TEXT;
74196     default:
74197       return sqlite3IsNumericAffinity(idx_affinity);
74198   }
74199 }
74200
74201 /*
74202 ** Return the P5 value that should be used for a binary comparison
74203 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
74204 */
74205 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
74206   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
74207   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
74208   return aff;
74209 }
74210
74211 /*
74212 ** Return a pointer to the collation sequence that should be used by
74213 ** a binary comparison operator comparing pLeft and pRight.
74214 **
74215 ** If the left hand expression has a collating sequence type, then it is
74216 ** used. Otherwise the collation sequence for the right hand expression
74217 ** is used, or the default (BINARY) if neither expression has a collating
74218 ** type.
74219 **
74220 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
74221 ** it is not considered.
74222 */
74223 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
74224   Parse *pParse, 
74225   Expr *pLeft, 
74226   Expr *pRight
74227 ){
74228   CollSeq *pColl;
74229   assert( pLeft );
74230   if( pLeft->flags & EP_Collate ){
74231     pColl = sqlite3ExprCollSeq(pParse, pLeft);
74232   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
74233     pColl = sqlite3ExprCollSeq(pParse, pRight);
74234   }else{
74235     pColl = sqlite3ExprCollSeq(pParse, pLeft);
74236     if( !pColl ){
74237       pColl = sqlite3ExprCollSeq(pParse, pRight);
74238     }
74239   }
74240   return pColl;
74241 }
74242
74243 /*
74244 ** Generate code for a comparison operator.
74245 */
74246 static int codeCompare(
74247   Parse *pParse,    /* The parsing (and code generating) context */
74248   Expr *pLeft,      /* The left operand */
74249   Expr *pRight,     /* The right operand */
74250   int opcode,       /* The comparison opcode */
74251   int in1, int in2, /* Register holding operands */
74252   int dest,         /* Jump here if true.  */
74253   int jumpIfNull    /* If true, jump if either operand is NULL */
74254 ){
74255   int p5;
74256   int addr;
74257   CollSeq *p4;
74258
74259   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
74260   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
74261   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
74262                            (void*)p4, P4_COLLSEQ);
74263   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
74264   return addr;
74265 }
74266
74267 #if SQLITE_MAX_EXPR_DEPTH>0
74268 /*
74269 ** Check that argument nHeight is less than or equal to the maximum
74270 ** expression depth allowed. If it is not, leave an error message in
74271 ** pParse.
74272 */
74273 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
74274   int rc = SQLITE_OK;
74275   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
74276   if( nHeight>mxHeight ){
74277     sqlite3ErrorMsg(pParse, 
74278        "Expression tree is too large (maximum depth %d)", mxHeight
74279     );
74280     rc = SQLITE_ERROR;
74281   }
74282   return rc;
74283 }
74284
74285 /* The following three functions, heightOfExpr(), heightOfExprList()
74286 ** and heightOfSelect(), are used to determine the maximum height
74287 ** of any expression tree referenced by the structure passed as the
74288 ** first argument.
74289 **
74290 ** If this maximum height is greater than the current value pointed
74291 ** to by pnHeight, the second parameter, then set *pnHeight to that
74292 ** value.
74293 */
74294 static void heightOfExpr(Expr *p, int *pnHeight){
74295   if( p ){
74296     if( p->nHeight>*pnHeight ){
74297       *pnHeight = p->nHeight;
74298     }
74299   }
74300 }
74301 static void heightOfExprList(ExprList *p, int *pnHeight){
74302   if( p ){
74303     int i;
74304     for(i=0; i<p->nExpr; i++){
74305       heightOfExpr(p->a[i].pExpr, pnHeight);
74306     }
74307   }
74308 }
74309 static void heightOfSelect(Select *p, int *pnHeight){
74310   if( p ){
74311     heightOfExpr(p->pWhere, pnHeight);
74312     heightOfExpr(p->pHaving, pnHeight);
74313     heightOfExpr(p->pLimit, pnHeight);
74314     heightOfExpr(p->pOffset, pnHeight);
74315     heightOfExprList(p->pEList, pnHeight);
74316     heightOfExprList(p->pGroupBy, pnHeight);
74317     heightOfExprList(p->pOrderBy, pnHeight);
74318     heightOfSelect(p->pPrior, pnHeight);
74319   }
74320 }
74321
74322 /*
74323 ** Set the Expr.nHeight variable in the structure passed as an 
74324 ** argument. An expression with no children, Expr.pList or 
74325 ** Expr.pSelect member has a height of 1. Any other expression
74326 ** has a height equal to the maximum height of any other 
74327 ** referenced Expr plus one.
74328 */
74329 static void exprSetHeight(Expr *p){
74330   int nHeight = 0;
74331   heightOfExpr(p->pLeft, &nHeight);
74332   heightOfExpr(p->pRight, &nHeight);
74333   if( ExprHasProperty(p, EP_xIsSelect) ){
74334     heightOfSelect(p->x.pSelect, &nHeight);
74335   }else{
74336     heightOfExprList(p->x.pList, &nHeight);
74337   }
74338   p->nHeight = nHeight + 1;
74339 }
74340
74341 /*
74342 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
74343 ** the height is greater than the maximum allowed expression depth,
74344 ** leave an error in pParse.
74345 */
74346 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
74347   exprSetHeight(p);
74348   sqlite3ExprCheckHeight(pParse, p->nHeight);
74349 }
74350
74351 /*
74352 ** Return the maximum height of any expression tree referenced
74353 ** by the select statement passed as an argument.
74354 */
74355 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
74356   int nHeight = 0;
74357   heightOfSelect(p, &nHeight);
74358   return nHeight;
74359 }
74360 #else
74361   #define exprSetHeight(y)
74362 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
74363
74364 /*
74365 ** This routine is the core allocator for Expr nodes.
74366 **
74367 ** Construct a new expression node and return a pointer to it.  Memory
74368 ** for this node and for the pToken argument is a single allocation
74369 ** obtained from sqlite3DbMalloc().  The calling function
74370 ** is responsible for making sure the node eventually gets freed.
74371 **
74372 ** If dequote is true, then the token (if it exists) is dequoted.
74373 ** If dequote is false, no dequoting is performance.  The deQuote
74374 ** parameter is ignored if pToken is NULL or if the token does not
74375 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
74376 ** then the EP_DblQuoted flag is set on the expression node.
74377 **
74378 ** Special case:  If op==TK_INTEGER and pToken points to a string that
74379 ** can be translated into a 32-bit integer, then the token is not
74380 ** stored in u.zToken.  Instead, the integer values is written
74381 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
74382 ** is allocated to hold the integer text and the dequote flag is ignored.
74383 */
74384 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
74385   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
74386   int op,                 /* Expression opcode */
74387   const Token *pToken,    /* Token argument.  Might be NULL */
74388   int dequote             /* True to dequote */
74389 ){
74390   Expr *pNew;
74391   int nExtra = 0;
74392   int iValue = 0;
74393
74394   if( pToken ){
74395     if( op!=TK_INTEGER || pToken->z==0
74396           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
74397       nExtra = pToken->n+1;
74398       assert( iValue>=0 );
74399     }
74400   }
74401   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
74402   if( pNew ){
74403     pNew->op = (u8)op;
74404     pNew->iAgg = -1;
74405     if( pToken ){
74406       if( nExtra==0 ){
74407         pNew->flags |= EP_IntValue;
74408         pNew->u.iValue = iValue;
74409       }else{
74410         int c;
74411         pNew->u.zToken = (char*)&pNew[1];
74412         assert( pToken->z!=0 || pToken->n==0 );
74413         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
74414         pNew->u.zToken[pToken->n] = 0;
74415         if( dequote && nExtra>=3 
74416              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
74417           sqlite3Dequote(pNew->u.zToken);
74418           if( c=='"' ) pNew->flags |= EP_DblQuoted;
74419         }
74420       }
74421     }
74422 #if SQLITE_MAX_EXPR_DEPTH>0
74423     pNew->nHeight = 1;
74424 #endif  
74425   }
74426   return pNew;
74427 }
74428
74429 /*
74430 ** Allocate a new expression node from a zero-terminated token that has
74431 ** already been dequoted.
74432 */
74433 SQLITE_PRIVATE Expr *sqlite3Expr(
74434   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
74435   int op,                 /* Expression opcode */
74436   const char *zToken      /* Token argument.  Might be NULL */
74437 ){
74438   Token x;
74439   x.z = zToken;
74440   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
74441   return sqlite3ExprAlloc(db, op, &x, 0);
74442 }
74443
74444 /*
74445 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
74446 **
74447 ** If pRoot==NULL that means that a memory allocation error has occurred.
74448 ** In that case, delete the subtrees pLeft and pRight.
74449 */
74450 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
74451   sqlite3 *db,
74452   Expr *pRoot,
74453   Expr *pLeft,
74454   Expr *pRight
74455 ){
74456   if( pRoot==0 ){
74457     assert( db->mallocFailed );
74458     sqlite3ExprDelete(db, pLeft);
74459     sqlite3ExprDelete(db, pRight);
74460   }else{
74461     if( pRight ){
74462       pRoot->pRight = pRight;
74463       pRoot->flags |= EP_Collate & pRight->flags;
74464     }
74465     if( pLeft ){
74466       pRoot->pLeft = pLeft;
74467       pRoot->flags |= EP_Collate & pLeft->flags;
74468     }
74469     exprSetHeight(pRoot);
74470   }
74471 }
74472
74473 /*
74474 ** Allocate a Expr node which joins as many as two subtrees.
74475 **
74476 ** One or both of the subtrees can be NULL.  Return a pointer to the new
74477 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
74478 ** free the subtrees and return NULL.
74479 */
74480 SQLITE_PRIVATE Expr *sqlite3PExpr(
74481   Parse *pParse,          /* Parsing context */
74482   int op,                 /* Expression opcode */
74483   Expr *pLeft,            /* Left operand */
74484   Expr *pRight,           /* Right operand */
74485   const Token *pToken     /* Argument token */
74486 ){
74487   Expr *p;
74488   if( op==TK_AND && pLeft && pRight ){
74489     /* Take advantage of short-circuit false optimization for AND */
74490     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
74491   }else{
74492     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
74493     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
74494   }
74495   if( p ) {
74496     sqlite3ExprCheckHeight(pParse, p->nHeight);
74497   }
74498   return p;
74499 }
74500
74501 /*
74502 ** Return 1 if an expression must be FALSE in all cases and 0 if the
74503 ** expression might be true.  This is an optimization.  If is OK to
74504 ** return 0 here even if the expression really is always false (a 
74505 ** false negative).  But it is a bug to return 1 if the expression
74506 ** might be true in some rare circumstances (a false positive.)
74507 **
74508 ** Note that if the expression is part of conditional for a
74509 ** LEFT JOIN, then we cannot determine at compile-time whether or not
74510 ** is it true or false, so always return 0.
74511 */
74512 static int exprAlwaysFalse(Expr *p){
74513   int v = 0;
74514   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
74515   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
74516   return v==0;
74517 }
74518
74519 /*
74520 ** Join two expressions using an AND operator.  If either expression is
74521 ** NULL, then just return the other expression.
74522 **
74523 ** If one side or the other of the AND is known to be false, then instead
74524 ** of returning an AND expression, just return a constant expression with
74525 ** a value of false.
74526 */
74527 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
74528   if( pLeft==0 ){
74529     return pRight;
74530   }else if( pRight==0 ){
74531     return pLeft;
74532   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
74533     sqlite3ExprDelete(db, pLeft);
74534     sqlite3ExprDelete(db, pRight);
74535     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
74536   }else{
74537     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
74538     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
74539     return pNew;
74540   }
74541 }
74542
74543 /*
74544 ** Construct a new expression node for a function with multiple
74545 ** arguments.
74546 */
74547 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
74548   Expr *pNew;
74549   sqlite3 *db = pParse->db;
74550   assert( pToken );
74551   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
74552   if( pNew==0 ){
74553     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
74554     return 0;
74555   }
74556   pNew->x.pList = pList;
74557   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
74558   sqlite3ExprSetHeight(pParse, pNew);
74559   return pNew;
74560 }
74561
74562 /*
74563 ** Assign a variable number to an expression that encodes a wildcard
74564 ** in the original SQL statement.  
74565 **
74566 ** Wildcards consisting of a single "?" are assigned the next sequential
74567 ** variable number.
74568 **
74569 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
74570 ** sure "nnn" is not too be to avoid a denial of service attack when
74571 ** the SQL statement comes from an external source.
74572 **
74573 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
74574 ** as the previous instance of the same wildcard.  Or if this is the first
74575 ** instance of the wildcard, the next sequenial variable number is
74576 ** assigned.
74577 */
74578 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
74579   sqlite3 *db = pParse->db;
74580   const char *z;
74581
74582   if( pExpr==0 ) return;
74583   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
74584   z = pExpr->u.zToken;
74585   assert( z!=0 );
74586   assert( z[0]!=0 );
74587   if( z[1]==0 ){
74588     /* Wildcard of the form "?".  Assign the next variable number */
74589     assert( z[0]=='?' );
74590     pExpr->iColumn = (ynVar)(++pParse->nVar);
74591   }else{
74592     ynVar x = 0;
74593     u32 n = sqlite3Strlen30(z);
74594     if( z[0]=='?' ){
74595       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
74596       ** use it as the variable number */
74597       i64 i;
74598       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
74599       pExpr->iColumn = x = (ynVar)i;
74600       testcase( i==0 );
74601       testcase( i==1 );
74602       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
74603       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
74604       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
74605         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
74606             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
74607         x = 0;
74608       }
74609       if( i>pParse->nVar ){
74610         pParse->nVar = (int)i;
74611       }
74612     }else{
74613       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
74614       ** number as the prior appearance of the same name, or if the name
74615       ** has never appeared before, reuse the same variable number
74616       */
74617       ynVar i;
74618       for(i=0; i<pParse->nzVar; i++){
74619         if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
74620           pExpr->iColumn = x = (ynVar)i+1;
74621           break;
74622         }
74623       }
74624       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
74625     }
74626     if( x>0 ){
74627       if( x>pParse->nzVar ){
74628         char **a;
74629         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
74630         if( a==0 ) return;  /* Error reported through db->mallocFailed */
74631         pParse->azVar = a;
74632         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
74633         pParse->nzVar = x;
74634       }
74635       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
74636         sqlite3DbFree(db, pParse->azVar[x-1]);
74637         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
74638       }
74639     }
74640   } 
74641   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
74642     sqlite3ErrorMsg(pParse, "too many SQL variables");
74643   }
74644 }
74645
74646 /*
74647 ** Recursively delete an expression tree.
74648 */
74649 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
74650   if( p==0 ) return;
74651   /* Sanity check: Assert that the IntValue is non-negative if it exists */
74652   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
74653   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
74654     sqlite3ExprDelete(db, p->pLeft);
74655     sqlite3ExprDelete(db, p->pRight);
74656     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
74657       sqlite3DbFree(db, p->u.zToken);
74658     }
74659     if( ExprHasProperty(p, EP_xIsSelect) ){
74660       sqlite3SelectDelete(db, p->x.pSelect);
74661     }else{
74662       sqlite3ExprListDelete(db, p->x.pList);
74663     }
74664   }
74665   if( !ExprHasProperty(p, EP_Static) ){
74666     sqlite3DbFree(db, p);
74667   }
74668 }
74669
74670 /*
74671 ** Return the number of bytes allocated for the expression structure 
74672 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
74673 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
74674 */
74675 static int exprStructSize(Expr *p){
74676   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
74677   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
74678   return EXPR_FULLSIZE;
74679 }
74680
74681 /*
74682 ** The dupedExpr*Size() routines each return the number of bytes required
74683 ** to store a copy of an expression or expression tree.  They differ in
74684 ** how much of the tree is measured.
74685 **
74686 **     dupedExprStructSize()     Size of only the Expr structure 
74687 **     dupedExprNodeSize()       Size of Expr + space for token
74688 **     dupedExprSize()           Expr + token + subtree components
74689 **
74690 ***************************************************************************
74691 **
74692 ** The dupedExprStructSize() function returns two values OR-ed together:  
74693 ** (1) the space required for a copy of the Expr structure only and 
74694 ** (2) the EP_xxx flags that indicate what the structure size should be.
74695 ** The return values is always one of:
74696 **
74697 **      EXPR_FULLSIZE
74698 **      EXPR_REDUCEDSIZE   | EP_Reduced
74699 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
74700 **
74701 ** The size of the structure can be found by masking the return value
74702 ** of this routine with 0xfff.  The flags can be found by masking the
74703 ** return value with EP_Reduced|EP_TokenOnly.
74704 **
74705 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
74706 ** (unreduced) Expr objects as they or originally constructed by the parser.
74707 ** During expression analysis, extra information is computed and moved into
74708 ** later parts of teh Expr object and that extra information might get chopped
74709 ** off if the expression is reduced.  Note also that it does not work to
74710 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
74711 ** to reduce a pristine expression tree from the parser.  The implementation
74712 ** of dupedExprStructSize() contain multiple assert() statements that attempt
74713 ** to enforce this constraint.
74714 */
74715 static int dupedExprStructSize(Expr *p, int flags){
74716   int nSize;
74717   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
74718   if( 0==(flags&EXPRDUP_REDUCE) ){
74719     nSize = EXPR_FULLSIZE;
74720   }else{
74721     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
74722     assert( !ExprHasProperty(p, EP_FromJoin) ); 
74723     assert( (p->flags2 & EP2_MallocedToken)==0 );
74724     assert( (p->flags2 & EP2_Irreducible)==0 );
74725     if( p->pLeft || p->pRight || p->x.pList ){
74726       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
74727     }else{
74728       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
74729     }
74730   }
74731   return nSize;
74732 }
74733
74734 /*
74735 ** This function returns the space in bytes required to store the copy 
74736 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
74737 ** string is defined.)
74738 */
74739 static int dupedExprNodeSize(Expr *p, int flags){
74740   int nByte = dupedExprStructSize(p, flags) & 0xfff;
74741   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
74742     nByte += sqlite3Strlen30(p->u.zToken)+1;
74743   }
74744   return ROUND8(nByte);
74745 }
74746
74747 /*
74748 ** Return the number of bytes required to create a duplicate of the 
74749 ** expression passed as the first argument. The second argument is a
74750 ** mask containing EXPRDUP_XXX flags.
74751 **
74752 ** The value returned includes space to create a copy of the Expr struct
74753 ** itself and the buffer referred to by Expr.u.zToken, if any.
74754 **
74755 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
74756 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
74757 ** and Expr.pRight variables (but not for any structures pointed to or 
74758 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
74759 */
74760 static int dupedExprSize(Expr *p, int flags){
74761   int nByte = 0;
74762   if( p ){
74763     nByte = dupedExprNodeSize(p, flags);
74764     if( flags&EXPRDUP_REDUCE ){
74765       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
74766     }
74767   }
74768   return nByte;
74769 }
74770
74771 /*
74772 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
74773 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
74774 ** to store the copy of expression p, the copies of p->u.zToken
74775 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
74776 ** if any. Before returning, *pzBuffer is set to the first byte passed the
74777 ** portion of the buffer copied into by this function.
74778 */
74779 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
74780   Expr *pNew = 0;                      /* Value to return */
74781   if( p ){
74782     const int isReduced = (flags&EXPRDUP_REDUCE);
74783     u8 *zAlloc;
74784     u32 staticFlag = 0;
74785
74786     assert( pzBuffer==0 || isReduced );
74787
74788     /* Figure out where to write the new Expr structure. */
74789     if( pzBuffer ){
74790       zAlloc = *pzBuffer;
74791       staticFlag = EP_Static;
74792     }else{
74793       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
74794     }
74795     pNew = (Expr *)zAlloc;
74796
74797     if( pNew ){
74798       /* Set nNewSize to the size allocated for the structure pointed to
74799       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
74800       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
74801       ** by the copy of the p->u.zToken string (if any).
74802       */
74803       const unsigned nStructSize = dupedExprStructSize(p, flags);
74804       const int nNewSize = nStructSize & 0xfff;
74805       int nToken;
74806       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
74807         nToken = sqlite3Strlen30(p->u.zToken) + 1;
74808       }else{
74809         nToken = 0;
74810       }
74811       if( isReduced ){
74812         assert( ExprHasProperty(p, EP_Reduced)==0 );
74813         memcpy(zAlloc, p, nNewSize);
74814       }else{
74815         int nSize = exprStructSize(p);
74816         memcpy(zAlloc, p, nSize);
74817         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
74818       }
74819
74820       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
74821       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
74822       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
74823       pNew->flags |= staticFlag;
74824
74825       /* Copy the p->u.zToken string, if any. */
74826       if( nToken ){
74827         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
74828         memcpy(zToken, p->u.zToken, nToken);
74829       }
74830
74831       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
74832         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
74833         if( ExprHasProperty(p, EP_xIsSelect) ){
74834           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
74835         }else{
74836           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
74837         }
74838       }
74839
74840       /* Fill in pNew->pLeft and pNew->pRight. */
74841       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
74842         zAlloc += dupedExprNodeSize(p, flags);
74843         if( ExprHasProperty(pNew, EP_Reduced) ){
74844           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
74845           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
74846         }
74847         if( pzBuffer ){
74848           *pzBuffer = zAlloc;
74849         }
74850       }else{
74851         pNew->flags2 = 0;
74852         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
74853           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
74854           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
74855         }
74856       }
74857
74858     }
74859   }
74860   return pNew;
74861 }
74862
74863 /*
74864 ** The following group of routines make deep copies of expressions,
74865 ** expression lists, ID lists, and select statements.  The copies can
74866 ** be deleted (by being passed to their respective ...Delete() routines)
74867 ** without effecting the originals.
74868 **
74869 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
74870 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
74871 ** by subsequent calls to sqlite*ListAppend() routines.
74872 **
74873 ** Any tables that the SrcList might point to are not duplicated.
74874 **
74875 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
74876 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
74877 ** truncated version of the usual Expr structure that will be stored as
74878 ** part of the in-memory representation of the database schema.
74879 */
74880 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
74881   return exprDup(db, p, flags, 0);
74882 }
74883 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
74884   ExprList *pNew;
74885   struct ExprList_item *pItem, *pOldItem;
74886   int i;
74887   if( p==0 ) return 0;
74888   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
74889   if( pNew==0 ) return 0;
74890   pNew->iECursor = 0;
74891   pNew->nExpr = i = p->nExpr;
74892   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
74893   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
74894   if( pItem==0 ){
74895     sqlite3DbFree(db, pNew);
74896     return 0;
74897   } 
74898   pOldItem = p->a;
74899   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
74900     Expr *pOldExpr = pOldItem->pExpr;
74901     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
74902     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
74903     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
74904     pItem->sortOrder = pOldItem->sortOrder;
74905     pItem->done = 0;
74906     pItem->iOrderByCol = pOldItem->iOrderByCol;
74907     pItem->iAlias = pOldItem->iAlias;
74908   }
74909   return pNew;
74910 }
74911
74912 /*
74913 ** If cursors, triggers, views and subqueries are all omitted from
74914 ** the build, then none of the following routines, except for 
74915 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
74916 ** called with a NULL argument.
74917 */
74918 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
74919  || !defined(SQLITE_OMIT_SUBQUERY)
74920 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
74921   SrcList *pNew;
74922   int i;
74923   int nByte;
74924   if( p==0 ) return 0;
74925   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
74926   pNew = sqlite3DbMallocRaw(db, nByte );
74927   if( pNew==0 ) return 0;
74928   pNew->nSrc = pNew->nAlloc = p->nSrc;
74929   for(i=0; i<p->nSrc; i++){
74930     struct SrcList_item *pNewItem = &pNew->a[i];
74931     struct SrcList_item *pOldItem = &p->a[i];
74932     Table *pTab;
74933     pNewItem->pSchema = pOldItem->pSchema;
74934     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
74935     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
74936     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
74937     pNewItem->jointype = pOldItem->jointype;
74938     pNewItem->iCursor = pOldItem->iCursor;
74939     pNewItem->addrFillSub = pOldItem->addrFillSub;
74940     pNewItem->regReturn = pOldItem->regReturn;
74941     pNewItem->isCorrelated = pOldItem->isCorrelated;
74942     pNewItem->viaCoroutine = pOldItem->viaCoroutine;
74943     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
74944     pNewItem->notIndexed = pOldItem->notIndexed;
74945     pNewItem->pIndex = pOldItem->pIndex;
74946     pTab = pNewItem->pTab = pOldItem->pTab;
74947     if( pTab ){
74948       pTab->nRef++;
74949     }
74950     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
74951     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
74952     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
74953     pNewItem->colUsed = pOldItem->colUsed;
74954   }
74955   return pNew;
74956 }
74957 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
74958   IdList *pNew;
74959   int i;
74960   if( p==0 ) return 0;
74961   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
74962   if( pNew==0 ) return 0;
74963   pNew->nId = p->nId;
74964   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
74965   if( pNew->a==0 ){
74966     sqlite3DbFree(db, pNew);
74967     return 0;
74968   }
74969   /* Note that because the size of the allocation for p->a[] is not
74970   ** necessarily a power of two, sqlite3IdListAppend() may not be called
74971   ** on the duplicate created by this function. */
74972   for(i=0; i<p->nId; i++){
74973     struct IdList_item *pNewItem = &pNew->a[i];
74974     struct IdList_item *pOldItem = &p->a[i];
74975     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
74976     pNewItem->idx = pOldItem->idx;
74977   }
74978   return pNew;
74979 }
74980 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
74981   Select *pNew, *pPrior;
74982   if( p==0 ) return 0;
74983   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
74984   if( pNew==0 ) return 0;
74985   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
74986   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
74987   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
74988   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
74989   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
74990   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
74991   pNew->op = p->op;
74992   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
74993   if( pPrior ) pPrior->pNext = pNew;
74994   pNew->pNext = 0;
74995   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
74996   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
74997   pNew->iLimit = 0;
74998   pNew->iOffset = 0;
74999   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
75000   pNew->pRightmost = 0;
75001   pNew->addrOpenEphm[0] = -1;
75002   pNew->addrOpenEphm[1] = -1;
75003   pNew->addrOpenEphm[2] = -1;
75004   return pNew;
75005 }
75006 #else
75007 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
75008   assert( p==0 );
75009   return 0;
75010 }
75011 #endif
75012
75013
75014 /*
75015 ** Add a new element to the end of an expression list.  If pList is
75016 ** initially NULL, then create a new expression list.
75017 **
75018 ** If a memory allocation error occurs, the entire list is freed and
75019 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
75020 ** that the new entry was successfully appended.
75021 */
75022 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
75023   Parse *pParse,          /* Parsing context */
75024   ExprList *pList,        /* List to which to append. Might be NULL */
75025   Expr *pExpr             /* Expression to be appended. Might be NULL */
75026 ){
75027   sqlite3 *db = pParse->db;
75028   if( pList==0 ){
75029     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
75030     if( pList==0 ){
75031       goto no_mem;
75032     }
75033     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
75034     if( pList->a==0 ) goto no_mem;
75035   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
75036     struct ExprList_item *a;
75037     assert( pList->nExpr>0 );
75038     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
75039     if( a==0 ){
75040       goto no_mem;
75041     }
75042     pList->a = a;
75043   }
75044   assert( pList->a!=0 );
75045   if( 1 ){
75046     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
75047     memset(pItem, 0, sizeof(*pItem));
75048     pItem->pExpr = pExpr;
75049   }
75050   return pList;
75051
75052 no_mem:     
75053   /* Avoid leaking memory if malloc has failed. */
75054   sqlite3ExprDelete(db, pExpr);
75055   sqlite3ExprListDelete(db, pList);
75056   return 0;
75057 }
75058
75059 /*
75060 ** Set the ExprList.a[].zName element of the most recently added item
75061 ** on the expression list.
75062 **
75063 ** pList might be NULL following an OOM error.  But pName should never be
75064 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
75065 ** is set.
75066 */
75067 SQLITE_PRIVATE void sqlite3ExprListSetName(
75068   Parse *pParse,          /* Parsing context */
75069   ExprList *pList,        /* List to which to add the span. */
75070   Token *pName,           /* Name to be added */
75071   int dequote             /* True to cause the name to be dequoted */
75072 ){
75073   assert( pList!=0 || pParse->db->mallocFailed!=0 );
75074   if( pList ){
75075     struct ExprList_item *pItem;
75076     assert( pList->nExpr>0 );
75077     pItem = &pList->a[pList->nExpr-1];
75078     assert( pItem->zName==0 );
75079     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
75080     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
75081   }
75082 }
75083
75084 /*
75085 ** Set the ExprList.a[].zSpan element of the most recently added item
75086 ** on the expression list.
75087 **
75088 ** pList might be NULL following an OOM error.  But pSpan should never be
75089 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
75090 ** is set.
75091 */
75092 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
75093   Parse *pParse,          /* Parsing context */
75094   ExprList *pList,        /* List to which to add the span. */
75095   ExprSpan *pSpan         /* The span to be added */
75096 ){
75097   sqlite3 *db = pParse->db;
75098   assert( pList!=0 || db->mallocFailed!=0 );
75099   if( pList ){
75100     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
75101     assert( pList->nExpr>0 );
75102     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
75103     sqlite3DbFree(db, pItem->zSpan);
75104     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
75105                                     (int)(pSpan->zEnd - pSpan->zStart));
75106   }
75107 }
75108
75109 /*
75110 ** If the expression list pEList contains more than iLimit elements,
75111 ** leave an error message in pParse.
75112 */
75113 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
75114   Parse *pParse,
75115   ExprList *pEList,
75116   const char *zObject
75117 ){
75118   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
75119   testcase( pEList && pEList->nExpr==mx );
75120   testcase( pEList && pEList->nExpr==mx+1 );
75121   if( pEList && pEList->nExpr>mx ){
75122     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
75123   }
75124 }
75125
75126 /*
75127 ** Delete an entire expression list.
75128 */
75129 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
75130   int i;
75131   struct ExprList_item *pItem;
75132   if( pList==0 ) return;
75133   assert( pList->a!=0 || pList->nExpr==0 );
75134   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
75135     sqlite3ExprDelete(db, pItem->pExpr);
75136     sqlite3DbFree(db, pItem->zName);
75137     sqlite3DbFree(db, pItem->zSpan);
75138   }
75139   sqlite3DbFree(db, pList->a);
75140   sqlite3DbFree(db, pList);
75141 }
75142
75143 /*
75144 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
75145 ** to an integer.  These routines are checking an expression to see
75146 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
75147 ** not constant.
75148 **
75149 ** These callback routines are used to implement the following:
75150 **
75151 **     sqlite3ExprIsConstant()
75152 **     sqlite3ExprIsConstantNotJoin()
75153 **     sqlite3ExprIsConstantOrFunction()
75154 **
75155 */
75156 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
75157
75158   /* If pWalker->u.i is 3 then any term of the expression that comes from
75159   ** the ON or USING clauses of a join disqualifies the expression
75160   ** from being considered constant. */
75161   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
75162     pWalker->u.i = 0;
75163     return WRC_Abort;
75164   }
75165
75166   switch( pExpr->op ){
75167     /* Consider functions to be constant if all their arguments are constant
75168     ** and pWalker->u.i==2 */
75169     case TK_FUNCTION:
75170       if( pWalker->u.i==2 ) return 0;
75171       /* Fall through */
75172     case TK_ID:
75173     case TK_COLUMN:
75174     case TK_AGG_FUNCTION:
75175     case TK_AGG_COLUMN:
75176       testcase( pExpr->op==TK_ID );
75177       testcase( pExpr->op==TK_COLUMN );
75178       testcase( pExpr->op==TK_AGG_FUNCTION );
75179       testcase( pExpr->op==TK_AGG_COLUMN );
75180       pWalker->u.i = 0;
75181       return WRC_Abort;
75182     default:
75183       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
75184       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
75185       return WRC_Continue;
75186   }
75187 }
75188 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
75189   UNUSED_PARAMETER(NotUsed);
75190   pWalker->u.i = 0;
75191   return WRC_Abort;
75192 }
75193 static int exprIsConst(Expr *p, int initFlag){
75194   Walker w;
75195   w.u.i = initFlag;
75196   w.xExprCallback = exprNodeIsConstant;
75197   w.xSelectCallback = selectNodeIsConstant;
75198   sqlite3WalkExpr(&w, p);
75199   return w.u.i;
75200 }
75201
75202 /*
75203 ** Walk an expression tree.  Return 1 if the expression is constant
75204 ** and 0 if it involves variables or function calls.
75205 **
75206 ** For the purposes of this function, a double-quoted string (ex: "abc")
75207 ** is considered a variable but a single-quoted string (ex: 'abc') is
75208 ** a constant.
75209 */
75210 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
75211   return exprIsConst(p, 1);
75212 }
75213
75214 /*
75215 ** Walk an expression tree.  Return 1 if the expression is constant
75216 ** that does no originate from the ON or USING clauses of a join.
75217 ** Return 0 if it involves variables or function calls or terms from
75218 ** an ON or USING clause.
75219 */
75220 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
75221   return exprIsConst(p, 3);
75222 }
75223
75224 /*
75225 ** Walk an expression tree.  Return 1 if the expression is constant
75226 ** or a function call with constant arguments.  Return and 0 if there
75227 ** are any variables.
75228 **
75229 ** For the purposes of this function, a double-quoted string (ex: "abc")
75230 ** is considered a variable but a single-quoted string (ex: 'abc') is
75231 ** a constant.
75232 */
75233 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
75234   return exprIsConst(p, 2);
75235 }
75236
75237 /*
75238 ** If the expression p codes a constant integer that is small enough
75239 ** to fit in a 32-bit integer, return 1 and put the value of the integer
75240 ** in *pValue.  If the expression is not an integer or if it is too big
75241 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
75242 */
75243 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
75244   int rc = 0;
75245
75246   /* If an expression is an integer literal that fits in a signed 32-bit
75247   ** integer, then the EP_IntValue flag will have already been set */
75248   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
75249            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
75250
75251   if( p->flags & EP_IntValue ){
75252     *pValue = p->u.iValue;
75253     return 1;
75254   }
75255   switch( p->op ){
75256     case TK_UPLUS: {
75257       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
75258       break;
75259     }
75260     case TK_UMINUS: {
75261       int v;
75262       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
75263         *pValue = -v;
75264         rc = 1;
75265       }
75266       break;
75267     }
75268     default: break;
75269   }
75270   return rc;
75271 }
75272
75273 /*
75274 ** Return FALSE if there is no chance that the expression can be NULL.
75275 **
75276 ** If the expression might be NULL or if the expression is too complex
75277 ** to tell return TRUE.  
75278 **
75279 ** This routine is used as an optimization, to skip OP_IsNull opcodes
75280 ** when we know that a value cannot be NULL.  Hence, a false positive
75281 ** (returning TRUE when in fact the expression can never be NULL) might
75282 ** be a small performance hit but is otherwise harmless.  On the other
75283 ** hand, a false negative (returning FALSE when the result could be NULL)
75284 ** will likely result in an incorrect answer.  So when in doubt, return
75285 ** TRUE.
75286 */
75287 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
75288   u8 op;
75289   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75290   op = p->op;
75291   if( op==TK_REGISTER ) op = p->op2;
75292   switch( op ){
75293     case TK_INTEGER:
75294     case TK_STRING:
75295     case TK_FLOAT:
75296     case TK_BLOB:
75297       return 0;
75298     default:
75299       return 1;
75300   }
75301 }
75302
75303 /*
75304 ** Generate an OP_IsNull instruction that tests register iReg and jumps
75305 ** to location iDest if the value in iReg is NULL.  The value in iReg 
75306 ** was computed by pExpr.  If we can look at pExpr at compile-time and
75307 ** determine that it can never generate a NULL, then the OP_IsNull operation
75308 ** can be omitted.
75309 */
75310 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
75311   Vdbe *v,            /* The VDBE under construction */
75312   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
75313   int iReg,           /* Test the value in this register for NULL */
75314   int iDest           /* Jump here if the value is null */
75315 ){
75316   if( sqlite3ExprCanBeNull(pExpr) ){
75317     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
75318   }
75319 }
75320
75321 /*
75322 ** Return TRUE if the given expression is a constant which would be
75323 ** unchanged by OP_Affinity with the affinity given in the second
75324 ** argument.
75325 **
75326 ** This routine is used to determine if the OP_Affinity operation
75327 ** can be omitted.  When in doubt return FALSE.  A false negative
75328 ** is harmless.  A false positive, however, can result in the wrong
75329 ** answer.
75330 */
75331 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
75332   u8 op;
75333   if( aff==SQLITE_AFF_NONE ) return 1;
75334   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75335   op = p->op;
75336   if( op==TK_REGISTER ) op = p->op2;
75337   switch( op ){
75338     case TK_INTEGER: {
75339       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
75340     }
75341     case TK_FLOAT: {
75342       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
75343     }
75344     case TK_STRING: {
75345       return aff==SQLITE_AFF_TEXT;
75346     }
75347     case TK_BLOB: {
75348       return 1;
75349     }
75350     case TK_COLUMN: {
75351       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
75352       return p->iColumn<0
75353           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
75354     }
75355     default: {
75356       return 0;
75357     }
75358   }
75359 }
75360
75361 /*
75362 ** Return TRUE if the given string is a row-id column name.
75363 */
75364 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
75365   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
75366   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
75367   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
75368   return 0;
75369 }
75370
75371 /*
75372 ** Return true if we are able to the IN operator optimization on a
75373 ** query of the form
75374 **
75375 **       x IN (SELECT ...)
75376 **
75377 ** Where the SELECT... clause is as specified by the parameter to this
75378 ** routine.
75379 **
75380 ** The Select object passed in has already been preprocessed and no
75381 ** errors have been found.
75382 */
75383 #ifndef SQLITE_OMIT_SUBQUERY
75384 static int isCandidateForInOpt(Select *p){
75385   SrcList *pSrc;
75386   ExprList *pEList;
75387   Table *pTab;
75388   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
75389   if( p->pPrior ) return 0;              /* Not a compound SELECT */
75390   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
75391     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
75392     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
75393     return 0; /* No DISTINCT keyword and no aggregate functions */
75394   }
75395   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
75396   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
75397   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
75398   if( p->pWhere ) return 0;              /* Has no WHERE clause */
75399   pSrc = p->pSrc;
75400   assert( pSrc!=0 );
75401   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
75402   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
75403   pTab = pSrc->a[0].pTab;
75404   if( NEVER(pTab==0) ) return 0;
75405   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
75406   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
75407   pEList = p->pEList;
75408   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
75409   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
75410   return 1;
75411 }
75412 #endif /* SQLITE_OMIT_SUBQUERY */
75413
75414 /*
75415 ** Code an OP_Once instruction and allocate space for its flag. Return the 
75416 ** address of the new instruction.
75417 */
75418 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
75419   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
75420   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
75421 }
75422
75423 /*
75424 ** This function is used by the implementation of the IN (...) operator.
75425 ** The pX parameter is the expression on the RHS of the IN operator, which
75426 ** might be either a list of expressions or a subquery.
75427 **
75428 ** The job of this routine is to find or create a b-tree object that can
75429 ** be used either to test for membership in the RHS set or to iterate through
75430 ** all members of the RHS set, skipping duplicates.
75431 **
75432 ** A cursor is opened on the b-tree object that the RHS of the IN operator
75433 ** and pX->iTable is set to the index of that cursor.
75434 **
75435 ** The returned value of this function indicates the b-tree type, as follows:
75436 **
75437 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
75438 **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
75439 **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
75440 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
75441 **                         populated epheremal table.
75442 **
75443 ** An existing b-tree might be used if the RHS expression pX is a simple
75444 ** subquery such as:
75445 **
75446 **     SELECT <column> FROM <table>
75447 **
75448 ** If the RHS of the IN operator is a list or a more complex subquery, then
75449 ** an ephemeral table might need to be generated from the RHS and then
75450 ** pX->iTable made to point to the ephermeral table instead of an
75451 ** existing table.  
75452 **
75453 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
75454 ** through the set members, skipping any duplicates. In this case an
75455 ** epheremal table must be used unless the selected <column> is guaranteed
75456 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
75457 ** has a UNIQUE constraint or UNIQUE index.
75458 **
75459 ** If the prNotFound parameter is not 0, then the b-tree will be used 
75460 ** for fast set membership tests. In this case an epheremal table must 
75461 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
75462 ** be found with <column> as its left-most column.
75463 **
75464 ** When the b-tree is being used for membership tests, the calling function
75465 ** needs to know whether or not the structure contains an SQL NULL 
75466 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
75467 ** If there is any chance that the (...) might contain a NULL value at
75468 ** runtime, then a register is allocated and the register number written
75469 ** to *prNotFound. If there is no chance that the (...) contains a
75470 ** NULL value, then *prNotFound is left unchanged.
75471 **
75472 ** If a register is allocated and its location stored in *prNotFound, then
75473 ** its initial value is NULL.  If the (...) does not remain constant
75474 ** for the duration of the query (i.e. the SELECT within the (...)
75475 ** is a correlated subquery) then the value of the allocated register is
75476 ** reset to NULL each time the subquery is rerun. This allows the
75477 ** caller to use vdbe code equivalent to the following:
75478 **
75479 **   if( register==NULL ){
75480 **     has_null = <test if data structure contains null>
75481 **     register = 1
75482 **   }
75483 **
75484 ** in order to avoid running the <test if data structure contains null>
75485 ** test more often than is necessary.
75486 */
75487 #ifndef SQLITE_OMIT_SUBQUERY
75488 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
75489   Select *p;                            /* SELECT to the right of IN operator */
75490   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
75491   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
75492   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
75493   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
75494
75495   assert( pX->op==TK_IN );
75496
75497   /* Check to see if an existing table or index can be used to
75498   ** satisfy the query.  This is preferable to generating a new 
75499   ** ephemeral table.
75500   */
75501   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
75502   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
75503     sqlite3 *db = pParse->db;              /* Database connection */
75504     Table *pTab;                           /* Table <table>. */
75505     Expr *pExpr;                           /* Expression <column> */
75506     int iCol;                              /* Index of column <column> */
75507     int iDb;                               /* Database idx for pTab */
75508
75509     assert( p );                        /* Because of isCandidateForInOpt(p) */
75510     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
75511     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
75512     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
75513     pTab = p->pSrc->a[0].pTab;
75514     pExpr = p->pEList->a[0].pExpr;
75515     iCol = pExpr->iColumn;
75516    
75517     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
75518     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75519     sqlite3CodeVerifySchema(pParse, iDb);
75520     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75521
75522     /* This function is only called from two places. In both cases the vdbe
75523     ** has already been allocated. So assume sqlite3GetVdbe() is always
75524     ** successful here.
75525     */
75526     assert(v);
75527     if( iCol<0 ){
75528       int iAddr;
75529
75530       iAddr = sqlite3CodeOnce(pParse);
75531
75532       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
75533       eType = IN_INDEX_ROWID;
75534
75535       sqlite3VdbeJumpHere(v, iAddr);
75536     }else{
75537       Index *pIdx;                         /* Iterator variable */
75538
75539       /* The collation sequence used by the comparison. If an index is to
75540       ** be used in place of a temp-table, it must be ordered according
75541       ** to this collation sequence.  */
75542       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
75543
75544       /* Check that the affinity that will be used to perform the 
75545       ** comparison is the same as the affinity of the column. If
75546       ** it is not, it is not possible to use any index.
75547       */
75548       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
75549
75550       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
75551         if( (pIdx->aiColumn[0]==iCol)
75552          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
75553          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
75554         ){
75555           int iAddr;
75556           char *pKey;
75557   
75558           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
75559           iAddr = sqlite3CodeOnce(pParse);
75560   
75561           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
75562                                pKey,P4_KEYINFO_HANDOFF);
75563           VdbeComment((v, "%s", pIdx->zName));
75564           assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
75565           eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
75566
75567           sqlite3VdbeJumpHere(v, iAddr);
75568           if( prNotFound && !pTab->aCol[iCol].notNull ){
75569             *prNotFound = ++pParse->nMem;
75570             sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
75571           }
75572         }
75573       }
75574     }
75575   }
75576
75577   if( eType==0 ){
75578     /* Could not found an existing table or index to use as the RHS b-tree.
75579     ** We will have to generate an ephemeral table to do the job.
75580     */
75581     double savedNQueryLoop = pParse->nQueryLoop;
75582     int rMayHaveNull = 0;
75583     eType = IN_INDEX_EPH;
75584     if( prNotFound ){
75585       *prNotFound = rMayHaveNull = ++pParse->nMem;
75586       sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
75587     }else{
75588       testcase( pParse->nQueryLoop>(double)1 );
75589       pParse->nQueryLoop = (double)1;
75590       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
75591         eType = IN_INDEX_ROWID;
75592       }
75593     }
75594     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
75595     pParse->nQueryLoop = savedNQueryLoop;
75596   }else{
75597     pX->iTable = iTab;
75598   }
75599   return eType;
75600 }
75601 #endif
75602
75603 /*
75604 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
75605 ** or IN operators.  Examples:
75606 **
75607 **     (SELECT a FROM b)          -- subquery
75608 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
75609 **     x IN (4,5,11)              -- IN operator with list on right-hand side
75610 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
75611 **
75612 ** The pExpr parameter describes the expression that contains the IN
75613 ** operator or subquery.
75614 **
75615 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
75616 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
75617 ** to some integer key column of a table B-Tree. In this case, use an
75618 ** intkey B-Tree to store the set of IN(...) values instead of the usual
75619 ** (slower) variable length keys B-Tree.
75620 **
75621 ** If rMayHaveNull is non-zero, that means that the operation is an IN
75622 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
75623 ** Furthermore, the IN is in a WHERE clause and that we really want
75624 ** to iterate over the RHS of the IN operator in order to quickly locate
75625 ** all corresponding LHS elements.  All this routine does is initialize
75626 ** the register given by rMayHaveNull to NULL.  Calling routines will take
75627 ** care of changing this register value to non-NULL if the RHS is NULL-free.
75628 **
75629 ** If rMayHaveNull is zero, that means that the subquery is being used
75630 ** for membership testing only.  There is no need to initialize any
75631 ** registers to indicate the presense or absence of NULLs on the RHS.
75632 **
75633 ** For a SELECT or EXISTS operator, return the register that holds the
75634 ** result.  For IN operators or if an error occurs, the return value is 0.
75635 */
75636 #ifndef SQLITE_OMIT_SUBQUERY
75637 SQLITE_PRIVATE int sqlite3CodeSubselect(
75638   Parse *pParse,          /* Parsing context */
75639   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
75640   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
75641   int isRowid             /* If true, LHS of IN operator is a rowid */
75642 ){
75643   int testAddr = -1;                      /* One-time test address */
75644   int rReg = 0;                           /* Register storing resulting */
75645   Vdbe *v = sqlite3GetVdbe(pParse);
75646   if( NEVER(v==0) ) return 0;
75647   sqlite3ExprCachePush(pParse);
75648
75649   /* This code must be run in its entirety every time it is encountered
75650   ** if any of the following is true:
75651   **
75652   **    *  The right-hand side is a correlated subquery
75653   **    *  The right-hand side is an expression list containing variables
75654   **    *  We are inside a trigger
75655   **
75656   ** If all of the above are false, then we can run this code just once
75657   ** save the results, and reuse the same result on subsequent invocations.
75658   */
75659   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
75660     testAddr = sqlite3CodeOnce(pParse);
75661   }
75662
75663 #ifndef SQLITE_OMIT_EXPLAIN
75664   if( pParse->explain==2 ){
75665     char *zMsg = sqlite3MPrintf(
75666         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
75667         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
75668     );
75669     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
75670   }
75671 #endif
75672
75673   switch( pExpr->op ){
75674     case TK_IN: {
75675       char affinity;              /* Affinity of the LHS of the IN */
75676       KeyInfo keyInfo;            /* Keyinfo for the generated table */
75677       static u8 sortOrder = 0;    /* Fake aSortOrder for keyInfo */
75678       int addr;                   /* Address of OP_OpenEphemeral instruction */
75679       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
75680
75681       if( rMayHaveNull ){
75682         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
75683       }
75684
75685       affinity = sqlite3ExprAffinity(pLeft);
75686
75687       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
75688       ** expression it is handled the same way.  An ephemeral table is 
75689       ** filled with single-field index keys representing the results
75690       ** from the SELECT or the <exprlist>.
75691       **
75692       ** If the 'x' expression is a column value, or the SELECT...
75693       ** statement returns a column value, then the affinity of that
75694       ** column is used to build the index keys. If both 'x' and the
75695       ** SELECT... statement are columns, then numeric affinity is used
75696       ** if either column has NUMERIC or INTEGER affinity. If neither
75697       ** 'x' nor the SELECT... statement are columns, then numeric affinity
75698       ** is used.
75699       */
75700       pExpr->iTable = pParse->nTab++;
75701       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
75702       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
75703       memset(&keyInfo, 0, sizeof(keyInfo));
75704       keyInfo.nField = 1;
75705       keyInfo.aSortOrder = &sortOrder;
75706
75707       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
75708         /* Case 1:     expr IN (SELECT ...)
75709         **
75710         ** Generate code to write the results of the select into the temporary
75711         ** table allocated and opened above.
75712         */
75713         SelectDest dest;
75714         ExprList *pEList;
75715
75716         assert( !isRowid );
75717         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
75718         dest.affSdst = (u8)affinity;
75719         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
75720         pExpr->x.pSelect->iLimit = 0;
75721         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
75722           return 0;
75723         }
75724         pEList = pExpr->x.pSelect->pEList;
75725         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
75726           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
75727               pEList->a[0].pExpr);
75728         }
75729       }else if( ALWAYS(pExpr->x.pList!=0) ){
75730         /* Case 2:     expr IN (exprlist)
75731         **
75732         ** For each expression, build an index key from the evaluation and
75733         ** store it in the temporary table. If <expr> is a column, then use
75734         ** that columns affinity when building index keys. If <expr> is not
75735         ** a column, use numeric affinity.
75736         */
75737         int i;
75738         ExprList *pList = pExpr->x.pList;
75739         struct ExprList_item *pItem;
75740         int r1, r2, r3;
75741
75742         if( !affinity ){
75743           affinity = SQLITE_AFF_NONE;
75744         }
75745         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
75746         keyInfo.aSortOrder = &sortOrder;
75747
75748         /* Loop through each expression in <exprlist>. */
75749         r1 = sqlite3GetTempReg(pParse);
75750         r2 = sqlite3GetTempReg(pParse);
75751         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
75752         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
75753           Expr *pE2 = pItem->pExpr;
75754           int iValToIns;
75755
75756           /* If the expression is not constant then we will need to
75757           ** disable the test that was generated above that makes sure
75758           ** this code only executes once.  Because for a non-constant
75759           ** expression we need to rerun this code each time.
75760           */
75761           if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
75762             sqlite3VdbeChangeToNoop(v, testAddr);
75763             testAddr = -1;
75764           }
75765
75766           /* Evaluate the expression and insert it into the temp table */
75767           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
75768             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
75769           }else{
75770             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
75771             if( isRowid ){
75772               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
75773                                 sqlite3VdbeCurrentAddr(v)+2);
75774               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
75775             }else{
75776               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
75777               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
75778               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
75779             }
75780           }
75781         }
75782         sqlite3ReleaseTempReg(pParse, r1);
75783         sqlite3ReleaseTempReg(pParse, r2);
75784       }
75785       if( !isRowid ){
75786         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
75787       }
75788       break;
75789     }
75790
75791     case TK_EXISTS:
75792     case TK_SELECT:
75793     default: {
75794       /* If this has to be a scalar SELECT.  Generate code to put the
75795       ** value of this select in a memory cell and record the number
75796       ** of the memory cell in iColumn.  If this is an EXISTS, write
75797       ** an integer 0 (not exists) or 1 (exists) into a memory cell
75798       ** and record that memory cell in iColumn.
75799       */
75800       Select *pSel;                         /* SELECT statement to encode */
75801       SelectDest dest;                      /* How to deal with SELECt result */
75802
75803       testcase( pExpr->op==TK_EXISTS );
75804       testcase( pExpr->op==TK_SELECT );
75805       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
75806
75807       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
75808       pSel = pExpr->x.pSelect;
75809       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
75810       if( pExpr->op==TK_SELECT ){
75811         dest.eDest = SRT_Mem;
75812         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
75813         VdbeComment((v, "Init subquery result"));
75814       }else{
75815         dest.eDest = SRT_Exists;
75816         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
75817         VdbeComment((v, "Init EXISTS result"));
75818       }
75819       sqlite3ExprDelete(pParse->db, pSel->pLimit);
75820       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
75821                                   &sqlite3IntTokens[1]);
75822       pSel->iLimit = 0;
75823       if( sqlite3Select(pParse, pSel, &dest) ){
75824         return 0;
75825       }
75826       rReg = dest.iSDParm;
75827       ExprSetIrreducible(pExpr);
75828       break;
75829     }
75830   }
75831
75832   if( testAddr>=0 ){
75833     sqlite3VdbeJumpHere(v, testAddr);
75834   }
75835   sqlite3ExprCachePop(pParse, 1);
75836
75837   return rReg;
75838 }
75839 #endif /* SQLITE_OMIT_SUBQUERY */
75840
75841 #ifndef SQLITE_OMIT_SUBQUERY
75842 /*
75843 ** Generate code for an IN expression.
75844 **
75845 **      x IN (SELECT ...)
75846 **      x IN (value, value, ...)
75847 **
75848 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
75849 ** is an array of zero or more values.  The expression is true if the LHS is
75850 ** contained within the RHS.  The value of the expression is unknown (NULL)
75851 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
75852 ** RHS contains one or more NULL values.
75853 **
75854 ** This routine generates code will jump to destIfFalse if the LHS is not 
75855 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
75856 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
75857 ** within the RHS then fall through.
75858 */
75859 static void sqlite3ExprCodeIN(
75860   Parse *pParse,        /* Parsing and code generating context */
75861   Expr *pExpr,          /* The IN expression */
75862   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
75863   int destIfNull        /* Jump here if the results are unknown due to NULLs */
75864 ){
75865   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
75866   char affinity;        /* Comparison affinity to use */
75867   int eType;            /* Type of the RHS */
75868   int r1;               /* Temporary use register */
75869   Vdbe *v;              /* Statement under construction */
75870
75871   /* Compute the RHS.   After this step, the table with cursor
75872   ** pExpr->iTable will contains the values that make up the RHS.
75873   */
75874   v = pParse->pVdbe;
75875   assert( v!=0 );       /* OOM detected prior to this routine */
75876   VdbeNoopComment((v, "begin IN expr"));
75877   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
75878
75879   /* Figure out the affinity to use to create a key from the results
75880   ** of the expression. affinityStr stores a static string suitable for
75881   ** P4 of OP_MakeRecord.
75882   */
75883   affinity = comparisonAffinity(pExpr);
75884
75885   /* Code the LHS, the <expr> from "<expr> IN (...)".
75886   */
75887   sqlite3ExprCachePush(pParse);
75888   r1 = sqlite3GetTempReg(pParse);
75889   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
75890
75891   /* If the LHS is NULL, then the result is either false or NULL depending
75892   ** on whether the RHS is empty or not, respectively.
75893   */
75894   if( destIfNull==destIfFalse ){
75895     /* Shortcut for the common case where the false and NULL outcomes are
75896     ** the same. */
75897     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
75898   }else{
75899     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
75900     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
75901     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
75902     sqlite3VdbeJumpHere(v, addr1);
75903   }
75904
75905   if( eType==IN_INDEX_ROWID ){
75906     /* In this case, the RHS is the ROWID of table b-tree
75907     */
75908     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
75909     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
75910   }else{
75911     /* In this case, the RHS is an index b-tree.
75912     */
75913     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
75914
75915     /* If the set membership test fails, then the result of the 
75916     ** "x IN (...)" expression must be either 0 or NULL. If the set
75917     ** contains no NULL values, then the result is 0. If the set 
75918     ** contains one or more NULL values, then the result of the
75919     ** expression is also NULL.
75920     */
75921     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
75922       /* This branch runs if it is known at compile time that the RHS
75923       ** cannot contain NULL values. This happens as the result
75924       ** of a "NOT NULL" constraint in the database schema.
75925       **
75926       ** Also run this branch if NULL is equivalent to FALSE
75927       ** for this particular IN operator.
75928       */
75929       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
75930
75931     }else{
75932       /* In this branch, the RHS of the IN might contain a NULL and
75933       ** the presence of a NULL on the RHS makes a difference in the
75934       ** outcome.
75935       */
75936       int j1, j2, j3;
75937
75938       /* First check to see if the LHS is contained in the RHS.  If so,
75939       ** then the presence of NULLs in the RHS does not matter, so jump
75940       ** over all of the code that follows.
75941       */
75942       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
75943
75944       /* Here we begin generating code that runs if the LHS is not
75945       ** contained within the RHS.  Generate additional code that
75946       ** tests the RHS for NULLs.  If the RHS contains a NULL then
75947       ** jump to destIfNull.  If there are no NULLs in the RHS then
75948       ** jump to destIfFalse.
75949       */
75950       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
75951       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
75952       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
75953       sqlite3VdbeJumpHere(v, j3);
75954       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
75955       sqlite3VdbeJumpHere(v, j2);
75956
75957       /* Jump to the appropriate target depending on whether or not
75958       ** the RHS contains a NULL
75959       */
75960       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
75961       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
75962
75963       /* The OP_Found at the top of this branch jumps here when true, 
75964       ** causing the overall IN expression evaluation to fall through.
75965       */
75966       sqlite3VdbeJumpHere(v, j1);
75967     }
75968   }
75969   sqlite3ReleaseTempReg(pParse, r1);
75970   sqlite3ExprCachePop(pParse, 1);
75971   VdbeComment((v, "end IN expr"));
75972 }
75973 #endif /* SQLITE_OMIT_SUBQUERY */
75974
75975 /*
75976 ** Duplicate an 8-byte value
75977 */
75978 static char *dup8bytes(Vdbe *v, const char *in){
75979   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
75980   if( out ){
75981     memcpy(out, in, 8);
75982   }
75983   return out;
75984 }
75985
75986 #ifndef SQLITE_OMIT_FLOATING_POINT
75987 /*
75988 ** Generate an instruction that will put the floating point
75989 ** value described by z[0..n-1] into register iMem.
75990 **
75991 ** The z[] string will probably not be zero-terminated.  But the 
75992 ** z[n] character is guaranteed to be something that does not look
75993 ** like the continuation of the number.
75994 */
75995 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
75996   if( ALWAYS(z!=0) ){
75997     double value;
75998     char *zV;
75999     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
76000     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
76001     if( negateFlag ) value = -value;
76002     zV = dup8bytes(v, (char*)&value);
76003     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
76004   }
76005 }
76006 #endif
76007
76008
76009 /*
76010 ** Generate an instruction that will put the integer describe by
76011 ** text z[0..n-1] into register iMem.
76012 **
76013 ** Expr.u.zToken is always UTF8 and zero-terminated.
76014 */
76015 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
76016   Vdbe *v = pParse->pVdbe;
76017   if( pExpr->flags & EP_IntValue ){
76018     int i = pExpr->u.iValue;
76019     assert( i>=0 );
76020     if( negFlag ) i = -i;
76021     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
76022   }else{
76023     int c;
76024     i64 value;
76025     const char *z = pExpr->u.zToken;
76026     assert( z!=0 );
76027     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
76028     if( c==0 || (c==2 && negFlag) ){
76029       char *zV;
76030       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
76031       zV = dup8bytes(v, (char*)&value);
76032       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
76033     }else{
76034 #ifdef SQLITE_OMIT_FLOATING_POINT
76035       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
76036 #else
76037       codeReal(v, z, negFlag, iMem);
76038 #endif
76039     }
76040   }
76041 }
76042
76043 /*
76044 ** Clear a cache entry.
76045 */
76046 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
76047   if( p->tempReg ){
76048     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
76049       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
76050     }
76051     p->tempReg = 0;
76052   }
76053 }
76054
76055
76056 /*
76057 ** Record in the column cache that a particular column from a
76058 ** particular table is stored in a particular register.
76059 */
76060 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
76061   int i;
76062   int minLru;
76063   int idxLru;
76064   struct yColCache *p;
76065
76066   assert( iReg>0 );  /* Register numbers are always positive */
76067   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
76068
76069   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
76070   ** for testing only - to verify that SQLite always gets the same answer
76071   ** with and without the column cache.
76072   */
76073   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
76074
76075   /* First replace any existing entry.
76076   **
76077   ** Actually, the way the column cache is currently used, we are guaranteed
76078   ** that the object will never already be in cache.  Verify this guarantee.
76079   */
76080 #ifndef NDEBUG
76081   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76082     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
76083   }
76084 #endif
76085
76086   /* Find an empty slot and replace it */
76087   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76088     if( p->iReg==0 ){
76089       p->iLevel = pParse->iCacheLevel;
76090       p->iTable = iTab;
76091       p->iColumn = iCol;
76092       p->iReg = iReg;
76093       p->tempReg = 0;
76094       p->lru = pParse->iCacheCnt++;
76095       return;
76096     }
76097   }
76098
76099   /* Replace the last recently used */
76100   minLru = 0x7fffffff;
76101   idxLru = -1;
76102   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76103     if( p->lru<minLru ){
76104       idxLru = i;
76105       minLru = p->lru;
76106     }
76107   }
76108   if( ALWAYS(idxLru>=0) ){
76109     p = &pParse->aColCache[idxLru];
76110     p->iLevel = pParse->iCacheLevel;
76111     p->iTable = iTab;
76112     p->iColumn = iCol;
76113     p->iReg = iReg;
76114     p->tempReg = 0;
76115     p->lru = pParse->iCacheCnt++;
76116     return;
76117   }
76118 }
76119
76120 /*
76121 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
76122 ** Purge the range of registers from the column cache.
76123 */
76124 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
76125   int i;
76126   int iLast = iReg + nReg - 1;
76127   struct yColCache *p;
76128   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76129     int r = p->iReg;
76130     if( r>=iReg && r<=iLast ){
76131       cacheEntryClear(pParse, p);
76132       p->iReg = 0;
76133     }
76134   }
76135 }
76136
76137 /*
76138 ** Remember the current column cache context.  Any new entries added
76139 ** added to the column cache after this call are removed when the
76140 ** corresponding pop occurs.
76141 */
76142 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
76143   pParse->iCacheLevel++;
76144 }
76145
76146 /*
76147 ** Remove from the column cache any entries that were added since the
76148 ** the previous N Push operations.  In other words, restore the cache
76149 ** to the state it was in N Pushes ago.
76150 */
76151 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
76152   int i;
76153   struct yColCache *p;
76154   assert( N>0 );
76155   assert( pParse->iCacheLevel>=N );
76156   pParse->iCacheLevel -= N;
76157   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76158     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
76159       cacheEntryClear(pParse, p);
76160       p->iReg = 0;
76161     }
76162   }
76163 }
76164
76165 /*
76166 ** When a cached column is reused, make sure that its register is
76167 ** no longer available as a temp register.  ticket #3879:  that same
76168 ** register might be in the cache in multiple places, so be sure to
76169 ** get them all.
76170 */
76171 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
76172   int i;
76173   struct yColCache *p;
76174   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76175     if( p->iReg==iReg ){
76176       p->tempReg = 0;
76177     }
76178   }
76179 }
76180
76181 /*
76182 ** Generate code to extract the value of the iCol-th column of a table.
76183 */
76184 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
76185   Vdbe *v,        /* The VDBE under construction */
76186   Table *pTab,    /* The table containing the value */
76187   int iTabCur,    /* The cursor for this table */
76188   int iCol,       /* Index of the column to extract */
76189   int regOut      /* Extract the valud into this register */
76190 ){
76191   if( iCol<0 || iCol==pTab->iPKey ){
76192     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
76193   }else{
76194     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
76195     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
76196   }
76197   if( iCol>=0 ){
76198     sqlite3ColumnDefault(v, pTab, iCol, regOut);
76199   }
76200 }
76201
76202 /*
76203 ** Generate code that will extract the iColumn-th column from
76204 ** table pTab and store the column value in a register.  An effort
76205 ** is made to store the column value in register iReg, but this is
76206 ** not guaranteed.  The location of the column value is returned.
76207 **
76208 ** There must be an open cursor to pTab in iTable when this routine
76209 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
76210 */
76211 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
76212   Parse *pParse,   /* Parsing and code generating context */
76213   Table *pTab,     /* Description of the table we are reading from */
76214   int iColumn,     /* Index of the table column */
76215   int iTable,      /* The cursor pointing to the table */
76216   int iReg,        /* Store results here */
76217   u8 p5            /* P5 value for OP_Column */
76218 ){
76219   Vdbe *v = pParse->pVdbe;
76220   int i;
76221   struct yColCache *p;
76222
76223   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76224     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
76225       p->lru = pParse->iCacheCnt++;
76226       sqlite3ExprCachePinRegister(pParse, p->iReg);
76227       return p->iReg;
76228     }
76229   }  
76230   assert( v!=0 );
76231   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
76232   if( p5 ){
76233     sqlite3VdbeChangeP5(v, p5);
76234   }else{   
76235     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
76236   }
76237   return iReg;
76238 }
76239
76240 /*
76241 ** Clear all column cache entries.
76242 */
76243 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
76244   int i;
76245   struct yColCache *p;
76246
76247   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76248     if( p->iReg ){
76249       cacheEntryClear(pParse, p);
76250       p->iReg = 0;
76251     }
76252   }
76253 }
76254
76255 /*
76256 ** Record the fact that an affinity change has occurred on iCount
76257 ** registers starting with iStart.
76258 */
76259 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
76260   sqlite3ExprCacheRemove(pParse, iStart, iCount);
76261 }
76262
76263 /*
76264 ** Generate code to move content from registers iFrom...iFrom+nReg-1
76265 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
76266 */
76267 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
76268   int i;
76269   struct yColCache *p;
76270   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
76271   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
76272   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76273     int x = p->iReg;
76274     if( x>=iFrom && x<iFrom+nReg ){
76275       p->iReg += iTo-iFrom;
76276     }
76277   }
76278 }
76279
76280 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
76281 /*
76282 ** Return true if any register in the range iFrom..iTo (inclusive)
76283 ** is used as part of the column cache.
76284 **
76285 ** This routine is used within assert() and testcase() macros only
76286 ** and does not appear in a normal build.
76287 */
76288 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
76289   int i;
76290   struct yColCache *p;
76291   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76292     int r = p->iReg;
76293     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
76294   }
76295   return 0;
76296 }
76297 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
76298
76299 /*
76300 ** Generate code into the current Vdbe to evaluate the given
76301 ** expression.  Attempt to store the results in register "target".
76302 ** Return the register where results are stored.
76303 **
76304 ** With this routine, there is no guarantee that results will
76305 ** be stored in target.  The result might be stored in some other
76306 ** register if it is convenient to do so.  The calling function
76307 ** must check the return code and move the results to the desired
76308 ** register.
76309 */
76310 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
76311   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
76312   int op;                   /* The opcode being coded */
76313   int inReg = target;       /* Results stored in register inReg */
76314   int regFree1 = 0;         /* If non-zero free this temporary register */
76315   int regFree2 = 0;         /* If non-zero free this temporary register */
76316   int r1, r2, r3, r4;       /* Various register numbers */
76317   sqlite3 *db = pParse->db; /* The database connection */
76318
76319   assert( target>0 && target<=pParse->nMem );
76320   if( v==0 ){
76321     assert( pParse->db->mallocFailed );
76322     return 0;
76323   }
76324
76325   if( pExpr==0 ){
76326     op = TK_NULL;
76327   }else{
76328     op = pExpr->op;
76329   }
76330   switch( op ){
76331     case TK_AGG_COLUMN: {
76332       AggInfo *pAggInfo = pExpr->pAggInfo;
76333       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
76334       if( !pAggInfo->directMode ){
76335         assert( pCol->iMem>0 );
76336         inReg = pCol->iMem;
76337         break;
76338       }else if( pAggInfo->useSortingIdx ){
76339         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
76340                               pCol->iSorterColumn, target);
76341         break;
76342       }
76343       /* Otherwise, fall thru into the TK_COLUMN case */
76344     }
76345     case TK_COLUMN: {
76346       if( pExpr->iTable<0 ){
76347         /* This only happens when coding check constraints */
76348         assert( pParse->ckBase>0 );
76349         inReg = pExpr->iColumn + pParse->ckBase;
76350       }else{
76351         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
76352                                  pExpr->iColumn, pExpr->iTable, target,
76353                                  pExpr->op2);
76354       }
76355       break;
76356     }
76357     case TK_INTEGER: {
76358       codeInteger(pParse, pExpr, 0, target);
76359       break;
76360     }
76361 #ifndef SQLITE_OMIT_FLOATING_POINT
76362     case TK_FLOAT: {
76363       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76364       codeReal(v, pExpr->u.zToken, 0, target);
76365       break;
76366     }
76367 #endif
76368     case TK_STRING: {
76369       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76370       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
76371       break;
76372     }
76373     case TK_NULL: {
76374       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
76375       break;
76376     }
76377 #ifndef SQLITE_OMIT_BLOB_LITERAL
76378     case TK_BLOB: {
76379       int n;
76380       const char *z;
76381       char *zBlob;
76382       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76383       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
76384       assert( pExpr->u.zToken[1]=='\'' );
76385       z = &pExpr->u.zToken[2];
76386       n = sqlite3Strlen30(z) - 1;
76387       assert( z[n]=='\'' );
76388       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
76389       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
76390       break;
76391     }
76392 #endif
76393     case TK_VARIABLE: {
76394       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76395       assert( pExpr->u.zToken!=0 );
76396       assert( pExpr->u.zToken[0]!=0 );
76397       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
76398       if( pExpr->u.zToken[1]!=0 ){
76399         assert( pExpr->u.zToken[0]=='?' 
76400              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
76401         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
76402       }
76403       break;
76404     }
76405     case TK_REGISTER: {
76406       inReg = pExpr->iTable;
76407       break;
76408     }
76409     case TK_AS: {
76410       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76411       break;
76412     }
76413 #ifndef SQLITE_OMIT_CAST
76414     case TK_CAST: {
76415       /* Expressions of the form:   CAST(pLeft AS token) */
76416       int aff, to_op;
76417       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76418       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76419       aff = sqlite3AffinityType(pExpr->u.zToken);
76420       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
76421       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
76422       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
76423       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
76424       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
76425       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
76426       testcase( to_op==OP_ToText );
76427       testcase( to_op==OP_ToBlob );
76428       testcase( to_op==OP_ToNumeric );
76429       testcase( to_op==OP_ToInt );
76430       testcase( to_op==OP_ToReal );
76431       if( inReg!=target ){
76432         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
76433         inReg = target;
76434       }
76435       sqlite3VdbeAddOp1(v, to_op, inReg);
76436       testcase( usedAsColumnCache(pParse, inReg, inReg) );
76437       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
76438       break;
76439     }
76440 #endif /* SQLITE_OMIT_CAST */
76441     case TK_LT:
76442     case TK_LE:
76443     case TK_GT:
76444     case TK_GE:
76445     case TK_NE:
76446     case TK_EQ: {
76447       assert( TK_LT==OP_Lt );
76448       assert( TK_LE==OP_Le );
76449       assert( TK_GT==OP_Gt );
76450       assert( TK_GE==OP_Ge );
76451       assert( TK_EQ==OP_Eq );
76452       assert( TK_NE==OP_Ne );
76453       testcase( op==TK_LT );
76454       testcase( op==TK_LE );
76455       testcase( op==TK_GT );
76456       testcase( op==TK_GE );
76457       testcase( op==TK_EQ );
76458       testcase( op==TK_NE );
76459       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76460       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76461       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76462                   r1, r2, inReg, SQLITE_STOREP2);
76463       testcase( regFree1==0 );
76464       testcase( regFree2==0 );
76465       break;
76466     }
76467     case TK_IS:
76468     case TK_ISNOT: {
76469       testcase( op==TK_IS );
76470       testcase( op==TK_ISNOT );
76471       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76472       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76473       op = (op==TK_IS) ? TK_EQ : TK_NE;
76474       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76475                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
76476       testcase( regFree1==0 );
76477       testcase( regFree2==0 );
76478       break;
76479     }
76480     case TK_AND:
76481     case TK_OR:
76482     case TK_PLUS:
76483     case TK_STAR:
76484     case TK_MINUS:
76485     case TK_REM:
76486     case TK_BITAND:
76487     case TK_BITOR:
76488     case TK_SLASH:
76489     case TK_LSHIFT:
76490     case TK_RSHIFT: 
76491     case TK_CONCAT: {
76492       assert( TK_AND==OP_And );
76493       assert( TK_OR==OP_Or );
76494       assert( TK_PLUS==OP_Add );
76495       assert( TK_MINUS==OP_Subtract );
76496       assert( TK_REM==OP_Remainder );
76497       assert( TK_BITAND==OP_BitAnd );
76498       assert( TK_BITOR==OP_BitOr );
76499       assert( TK_SLASH==OP_Divide );
76500       assert( TK_LSHIFT==OP_ShiftLeft );
76501       assert( TK_RSHIFT==OP_ShiftRight );
76502       assert( TK_CONCAT==OP_Concat );
76503       testcase( op==TK_AND );
76504       testcase( op==TK_OR );
76505       testcase( op==TK_PLUS );
76506       testcase( op==TK_MINUS );
76507       testcase( op==TK_REM );
76508       testcase( op==TK_BITAND );
76509       testcase( op==TK_BITOR );
76510       testcase( op==TK_SLASH );
76511       testcase( op==TK_LSHIFT );
76512       testcase( op==TK_RSHIFT );
76513       testcase( op==TK_CONCAT );
76514       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76515       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76516       sqlite3VdbeAddOp3(v, op, r2, r1, target);
76517       testcase( regFree1==0 );
76518       testcase( regFree2==0 );
76519       break;
76520     }
76521     case TK_UMINUS: {
76522       Expr *pLeft = pExpr->pLeft;
76523       assert( pLeft );
76524       if( pLeft->op==TK_INTEGER ){
76525         codeInteger(pParse, pLeft, 1, target);
76526 #ifndef SQLITE_OMIT_FLOATING_POINT
76527       }else if( pLeft->op==TK_FLOAT ){
76528         assert( !ExprHasProperty(pExpr, EP_IntValue) );
76529         codeReal(v, pLeft->u.zToken, 1, target);
76530 #endif
76531       }else{
76532         regFree1 = r1 = sqlite3GetTempReg(pParse);
76533         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
76534         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
76535         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
76536         testcase( regFree2==0 );
76537       }
76538       inReg = target;
76539       break;
76540     }
76541     case TK_BITNOT:
76542     case TK_NOT: {
76543       assert( TK_BITNOT==OP_BitNot );
76544       assert( TK_NOT==OP_Not );
76545       testcase( op==TK_BITNOT );
76546       testcase( op==TK_NOT );
76547       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76548       testcase( regFree1==0 );
76549       inReg = target;
76550       sqlite3VdbeAddOp2(v, op, r1, inReg);
76551       break;
76552     }
76553     case TK_ISNULL:
76554     case TK_NOTNULL: {
76555       int addr;
76556       assert( TK_ISNULL==OP_IsNull );
76557       assert( TK_NOTNULL==OP_NotNull );
76558       testcase( op==TK_ISNULL );
76559       testcase( op==TK_NOTNULL );
76560       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
76561       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76562       testcase( regFree1==0 );
76563       addr = sqlite3VdbeAddOp1(v, op, r1);
76564       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
76565       sqlite3VdbeJumpHere(v, addr);
76566       break;
76567     }
76568     case TK_AGG_FUNCTION: {
76569       AggInfo *pInfo = pExpr->pAggInfo;
76570       if( pInfo==0 ){
76571         assert( !ExprHasProperty(pExpr, EP_IntValue) );
76572         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
76573       }else{
76574         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
76575       }
76576       break;
76577     }
76578     case TK_CONST_FUNC:
76579     case TK_FUNCTION: {
76580       ExprList *pFarg;       /* List of function arguments */
76581       int nFarg;             /* Number of function arguments */
76582       FuncDef *pDef;         /* The function definition object */
76583       int nId;               /* Length of the function name in bytes */
76584       const char *zId;       /* The function name */
76585       int constMask = 0;     /* Mask of function arguments that are constant */
76586       int i;                 /* Loop counter */
76587       u8 enc = ENC(db);      /* The text encoding used by this database */
76588       CollSeq *pColl = 0;    /* A collating sequence */
76589
76590       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76591       testcase( op==TK_CONST_FUNC );
76592       testcase( op==TK_FUNCTION );
76593       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
76594         pFarg = 0;
76595       }else{
76596         pFarg = pExpr->x.pList;
76597       }
76598       nFarg = pFarg ? pFarg->nExpr : 0;
76599       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76600       zId = pExpr->u.zToken;
76601       nId = sqlite3Strlen30(zId);
76602       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
76603       if( pDef==0 ){
76604         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
76605         break;
76606       }
76607
76608       /* Attempt a direct implementation of the built-in COALESCE() and
76609       ** IFNULL() functions.  This avoids unnecessary evalation of
76610       ** arguments past the first non-NULL argument.
76611       */
76612       if( pDef->flags & SQLITE_FUNC_COALESCE ){
76613         int endCoalesce = sqlite3VdbeMakeLabel(v);
76614         assert( nFarg>=2 );
76615         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
76616         for(i=1; i<nFarg; i++){
76617           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
76618           sqlite3ExprCacheRemove(pParse, target, 1);
76619           sqlite3ExprCachePush(pParse);
76620           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
76621           sqlite3ExprCachePop(pParse, 1);
76622         }
76623         sqlite3VdbeResolveLabel(v, endCoalesce);
76624         break;
76625       }
76626
76627
76628       if( pFarg ){
76629         r1 = sqlite3GetTempRange(pParse, nFarg);
76630
76631         /* For length() and typeof() functions with a column argument,
76632         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
76633         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
76634         ** loading.
76635         */
76636         if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
76637           u8 exprOp;
76638           assert( nFarg==1 );
76639           assert( pFarg->a[0].pExpr!=0 );
76640           exprOp = pFarg->a[0].pExpr->op;
76641           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
76642             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
76643             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
76644             testcase( pDef->flags==SQLITE_FUNC_LENGTH );
76645             pFarg->a[0].pExpr->op2 = pDef->flags;
76646           }
76647         }
76648
76649         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
76650         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
76651         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
76652       }else{
76653         r1 = 0;
76654       }
76655 #ifndef SQLITE_OMIT_VIRTUALTABLE
76656       /* Possibly overload the function if the first argument is
76657       ** a virtual table column.
76658       **
76659       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
76660       ** second argument, not the first, as the argument to test to
76661       ** see if it is a column in a virtual table.  This is done because
76662       ** the left operand of infix functions (the operand we want to
76663       ** control overloading) ends up as the second argument to the
76664       ** function.  The expression "A glob B" is equivalent to 
76665       ** "glob(B,A).  We want to use the A in "A glob B" to test
76666       ** for function overloading.  But we use the B term in "glob(B,A)".
76667       */
76668       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
76669         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
76670       }else if( nFarg>0 ){
76671         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
76672       }
76673 #endif
76674       for(i=0; i<nFarg; i++){
76675         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
76676           constMask |= (1<<i);
76677         }
76678         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
76679           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
76680         }
76681       }
76682       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
76683         if( !pColl ) pColl = db->pDfltColl; 
76684         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
76685       }
76686       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
76687                         (char*)pDef, P4_FUNCDEF);
76688       sqlite3VdbeChangeP5(v, (u8)nFarg);
76689       if( nFarg ){
76690         sqlite3ReleaseTempRange(pParse, r1, nFarg);
76691       }
76692       break;
76693     }
76694 #ifndef SQLITE_OMIT_SUBQUERY
76695     case TK_EXISTS:
76696     case TK_SELECT: {
76697       testcase( op==TK_EXISTS );
76698       testcase( op==TK_SELECT );
76699       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
76700       break;
76701     }
76702     case TK_IN: {
76703       int destIfFalse = sqlite3VdbeMakeLabel(v);
76704       int destIfNull = sqlite3VdbeMakeLabel(v);
76705       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
76706       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
76707       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
76708       sqlite3VdbeResolveLabel(v, destIfFalse);
76709       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
76710       sqlite3VdbeResolveLabel(v, destIfNull);
76711       break;
76712     }
76713 #endif /* SQLITE_OMIT_SUBQUERY */
76714
76715
76716     /*
76717     **    x BETWEEN y AND z
76718     **
76719     ** This is equivalent to
76720     **
76721     **    x>=y AND x<=z
76722     **
76723     ** X is stored in pExpr->pLeft.
76724     ** Y is stored in pExpr->pList->a[0].pExpr.
76725     ** Z is stored in pExpr->pList->a[1].pExpr.
76726     */
76727     case TK_BETWEEN: {
76728       Expr *pLeft = pExpr->pLeft;
76729       struct ExprList_item *pLItem = pExpr->x.pList->a;
76730       Expr *pRight = pLItem->pExpr;
76731
76732       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
76733       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
76734       testcase( regFree1==0 );
76735       testcase( regFree2==0 );
76736       r3 = sqlite3GetTempReg(pParse);
76737       r4 = sqlite3GetTempReg(pParse);
76738       codeCompare(pParse, pLeft, pRight, OP_Ge,
76739                   r1, r2, r3, SQLITE_STOREP2);
76740       pLItem++;
76741       pRight = pLItem->pExpr;
76742       sqlite3ReleaseTempReg(pParse, regFree2);
76743       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
76744       testcase( regFree2==0 );
76745       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
76746       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
76747       sqlite3ReleaseTempReg(pParse, r3);
76748       sqlite3ReleaseTempReg(pParse, r4);
76749       break;
76750     }
76751     case TK_COLLATE: 
76752     case TK_UPLUS: {
76753       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76754       break;
76755     }
76756
76757     case TK_TRIGGER: {
76758       /* If the opcode is TK_TRIGGER, then the expression is a reference
76759       ** to a column in the new.* or old.* pseudo-tables available to
76760       ** trigger programs. In this case Expr.iTable is set to 1 for the
76761       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
76762       ** is set to the column of the pseudo-table to read, or to -1 to
76763       ** read the rowid field.
76764       **
76765       ** The expression is implemented using an OP_Param opcode. The p1
76766       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
76767       ** to reference another column of the old.* pseudo-table, where 
76768       ** i is the index of the column. For a new.rowid reference, p1 is
76769       ** set to (n+1), where n is the number of columns in each pseudo-table.
76770       ** For a reference to any other column in the new.* pseudo-table, p1
76771       ** is set to (n+2+i), where n and i are as defined previously. For
76772       ** example, if the table on which triggers are being fired is
76773       ** declared as:
76774       **
76775       **   CREATE TABLE t1(a, b);
76776       **
76777       ** Then p1 is interpreted as follows:
76778       **
76779       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
76780       **   p1==1   ->    old.a         p1==4   ->    new.a
76781       **   p1==2   ->    old.b         p1==5   ->    new.b       
76782       */
76783       Table *pTab = pExpr->pTab;
76784       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
76785
76786       assert( pExpr->iTable==0 || pExpr->iTable==1 );
76787       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
76788       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
76789       assert( p1>=0 && p1<(pTab->nCol*2+2) );
76790
76791       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
76792       VdbeComment((v, "%s.%s -> $%d",
76793         (pExpr->iTable ? "new" : "old"),
76794         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
76795         target
76796       ));
76797
76798 #ifndef SQLITE_OMIT_FLOATING_POINT
76799       /* If the column has REAL affinity, it may currently be stored as an
76800       ** integer. Use OP_RealAffinity to make sure it is really real.  */
76801       if( pExpr->iColumn>=0 
76802        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
76803       ){
76804         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
76805       }
76806 #endif
76807       break;
76808     }
76809
76810
76811     /*
76812     ** Form A:
76813     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
76814     **
76815     ** Form B:
76816     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
76817     **
76818     ** Form A is can be transformed into the equivalent form B as follows:
76819     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
76820     **        WHEN x=eN THEN rN ELSE y END
76821     **
76822     ** X (if it exists) is in pExpr->pLeft.
76823     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
76824     ** ELSE clause and no other term matches, then the result of the
76825     ** exprssion is NULL.
76826     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
76827     **
76828     ** The result of the expression is the Ri for the first matching Ei,
76829     ** or if there is no matching Ei, the ELSE term Y, or if there is
76830     ** no ELSE term, NULL.
76831     */
76832     default: assert( op==TK_CASE ); {
76833       int endLabel;                     /* GOTO label for end of CASE stmt */
76834       int nextCase;                     /* GOTO label for next WHEN clause */
76835       int nExpr;                        /* 2x number of WHEN terms */
76836       int i;                            /* Loop counter */
76837       ExprList *pEList;                 /* List of WHEN terms */
76838       struct ExprList_item *aListelem;  /* Array of WHEN terms */
76839       Expr opCompare;                   /* The X==Ei expression */
76840       Expr cacheX;                      /* Cached expression X */
76841       Expr *pX;                         /* The X expression */
76842       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
76843       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
76844
76845       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
76846       assert((pExpr->x.pList->nExpr % 2) == 0);
76847       assert(pExpr->x.pList->nExpr > 0);
76848       pEList = pExpr->x.pList;
76849       aListelem = pEList->a;
76850       nExpr = pEList->nExpr;
76851       endLabel = sqlite3VdbeMakeLabel(v);
76852       if( (pX = pExpr->pLeft)!=0 ){
76853         cacheX = *pX;
76854         testcase( pX->op==TK_COLUMN );
76855         testcase( pX->op==TK_REGISTER );
76856         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
76857         testcase( regFree1==0 );
76858         cacheX.op = TK_REGISTER;
76859         opCompare.op = TK_EQ;
76860         opCompare.pLeft = &cacheX;
76861         pTest = &opCompare;
76862         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
76863         ** The value in regFree1 might get SCopy-ed into the file result.
76864         ** So make sure that the regFree1 register is not reused for other
76865         ** purposes and possibly overwritten.  */
76866         regFree1 = 0;
76867       }
76868       for(i=0; i<nExpr; i=i+2){
76869         sqlite3ExprCachePush(pParse);
76870         if( pX ){
76871           assert( pTest!=0 );
76872           opCompare.pRight = aListelem[i].pExpr;
76873         }else{
76874           pTest = aListelem[i].pExpr;
76875         }
76876         nextCase = sqlite3VdbeMakeLabel(v);
76877         testcase( pTest->op==TK_COLUMN );
76878         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
76879         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
76880         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
76881         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
76882         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
76883         sqlite3ExprCachePop(pParse, 1);
76884         sqlite3VdbeResolveLabel(v, nextCase);
76885       }
76886       if( pExpr->pRight ){
76887         sqlite3ExprCachePush(pParse);
76888         sqlite3ExprCode(pParse, pExpr->pRight, target);
76889         sqlite3ExprCachePop(pParse, 1);
76890       }else{
76891         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
76892       }
76893       assert( db->mallocFailed || pParse->nErr>0 
76894            || pParse->iCacheLevel==iCacheLevel );
76895       sqlite3VdbeResolveLabel(v, endLabel);
76896       break;
76897     }
76898 #ifndef SQLITE_OMIT_TRIGGER
76899     case TK_RAISE: {
76900       assert( pExpr->affinity==OE_Rollback 
76901            || pExpr->affinity==OE_Abort
76902            || pExpr->affinity==OE_Fail
76903            || pExpr->affinity==OE_Ignore
76904       );
76905       if( !pParse->pTriggerTab ){
76906         sqlite3ErrorMsg(pParse,
76907                        "RAISE() may only be used within a trigger-program");
76908         return 0;
76909       }
76910       if( pExpr->affinity==OE_Abort ){
76911         sqlite3MayAbort(pParse);
76912       }
76913       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76914       if( pExpr->affinity==OE_Ignore ){
76915         sqlite3VdbeAddOp4(
76916             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
76917       }else{
76918         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
76919                               pExpr->affinity, pExpr->u.zToken, 0);
76920       }
76921
76922       break;
76923     }
76924 #endif
76925   }
76926   sqlite3ReleaseTempReg(pParse, regFree1);
76927   sqlite3ReleaseTempReg(pParse, regFree2);
76928   return inReg;
76929 }
76930
76931 /*
76932 ** Generate code to evaluate an expression and store the results
76933 ** into a register.  Return the register number where the results
76934 ** are stored.
76935 **
76936 ** If the register is a temporary register that can be deallocated,
76937 ** then write its number into *pReg.  If the result register is not
76938 ** a temporary, then set *pReg to zero.
76939 */
76940 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
76941   int r1 = sqlite3GetTempReg(pParse);
76942   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
76943   if( r2==r1 ){
76944     *pReg = r1;
76945   }else{
76946     sqlite3ReleaseTempReg(pParse, r1);
76947     *pReg = 0;
76948   }
76949   return r2;
76950 }
76951
76952 /*
76953 ** Generate code that will evaluate expression pExpr and store the
76954 ** results in register target.  The results are guaranteed to appear
76955 ** in register target.
76956 */
76957 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
76958   int inReg;
76959
76960   assert( target>0 && target<=pParse->nMem );
76961   if( pExpr && pExpr->op==TK_REGISTER ){
76962     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
76963   }else{
76964     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
76965     assert( pParse->pVdbe || pParse->db->mallocFailed );
76966     if( inReg!=target && pParse->pVdbe ){
76967       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
76968     }
76969   }
76970   return target;
76971 }
76972
76973 /*
76974 ** Generate code that evalutes the given expression and puts the result
76975 ** in register target.
76976 **
76977 ** Also make a copy of the expression results into another "cache" register
76978 ** and modify the expression so that the next time it is evaluated,
76979 ** the result is a copy of the cache register.
76980 **
76981 ** This routine is used for expressions that are used multiple 
76982 ** times.  They are evaluated once and the results of the expression
76983 ** are reused.
76984 */
76985 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
76986   Vdbe *v = pParse->pVdbe;
76987   int inReg;
76988   inReg = sqlite3ExprCode(pParse, pExpr, target);
76989   assert( target>0 );
76990   /* This routine is called for terms to INSERT or UPDATE.  And the only
76991   ** other place where expressions can be converted into TK_REGISTER is
76992   ** in WHERE clause processing.  So as currently implemented, there is
76993   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
76994   ** keep the ALWAYS() in case the conditions above change with future
76995   ** modifications or enhancements. */
76996   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
76997     int iMem;
76998     iMem = ++pParse->nMem;
76999     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
77000     pExpr->iTable = iMem;
77001     pExpr->op2 = pExpr->op;
77002     pExpr->op = TK_REGISTER;
77003   }
77004   return inReg;
77005 }
77006
77007 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
77008 /*
77009 ** Generate a human-readable explanation of an expression tree.
77010 */
77011 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
77012   int op;                   /* The opcode being coded */
77013   const char *zBinOp = 0;   /* Binary operator */
77014   const char *zUniOp = 0;   /* Unary operator */
77015   if( pExpr==0 ){
77016     op = TK_NULL;
77017   }else{
77018     op = pExpr->op;
77019   }
77020   switch( op ){
77021     case TK_AGG_COLUMN: {
77022       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
77023             pExpr->iTable, pExpr->iColumn);
77024       break;
77025     }
77026     case TK_COLUMN: {
77027       if( pExpr->iTable<0 ){
77028         /* This only happens when coding check constraints */
77029         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
77030       }else{
77031         sqlite3ExplainPrintf(pOut, "{%d:%d}",
77032                              pExpr->iTable, pExpr->iColumn);
77033       }
77034       break;
77035     }
77036     case TK_INTEGER: {
77037       if( pExpr->flags & EP_IntValue ){
77038         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
77039       }else{
77040         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
77041       }
77042       break;
77043     }
77044 #ifndef SQLITE_OMIT_FLOATING_POINT
77045     case TK_FLOAT: {
77046       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
77047       break;
77048     }
77049 #endif
77050     case TK_STRING: {
77051       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
77052       break;
77053     }
77054     case TK_NULL: {
77055       sqlite3ExplainPrintf(pOut,"NULL");
77056       break;
77057     }
77058 #ifndef SQLITE_OMIT_BLOB_LITERAL
77059     case TK_BLOB: {
77060       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
77061       break;
77062     }
77063 #endif
77064     case TK_VARIABLE: {
77065       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
77066                            pExpr->u.zToken, pExpr->iColumn);
77067       break;
77068     }
77069     case TK_REGISTER: {
77070       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
77071       break;
77072     }
77073     case TK_AS: {
77074       sqlite3ExplainExpr(pOut, pExpr->pLeft);
77075       break;
77076     }
77077 #ifndef SQLITE_OMIT_CAST
77078     case TK_CAST: {
77079       /* Expressions of the form:   CAST(pLeft AS token) */
77080       const char *zAff = "unk";
77081       switch( sqlite3AffinityType(pExpr->u.zToken) ){
77082         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
77083         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
77084         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
77085         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
77086         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
77087       }
77088       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
77089       sqlite3ExplainExpr(pOut, pExpr->pLeft);
77090       sqlite3ExplainPrintf(pOut, ")");
77091       break;
77092     }
77093 #endif /* SQLITE_OMIT_CAST */
77094     case TK_LT:      zBinOp = "LT";     break;
77095     case TK_LE:      zBinOp = "LE";     break;
77096     case TK_GT:      zBinOp = "GT";     break;
77097     case TK_GE:      zBinOp = "GE";     break;
77098     case TK_NE:      zBinOp = "NE";     break;
77099     case TK_EQ:      zBinOp = "EQ";     break;
77100     case TK_IS:      zBinOp = "IS";     break;
77101     case TK_ISNOT:   zBinOp = "ISNOT";  break;
77102     case TK_AND:     zBinOp = "AND";    break;
77103     case TK_OR:      zBinOp = "OR";     break;
77104     case TK_PLUS:    zBinOp = "ADD";    break;
77105     case TK_STAR:    zBinOp = "MUL";    break;
77106     case TK_MINUS:   zBinOp = "SUB";    break;
77107     case TK_REM:     zBinOp = "REM";    break;
77108     case TK_BITAND:  zBinOp = "BITAND"; break;
77109     case TK_BITOR:   zBinOp = "BITOR";  break;
77110     case TK_SLASH:   zBinOp = "DIV";    break;
77111     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
77112     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
77113     case TK_CONCAT:  zBinOp = "CONCAT"; break;
77114
77115     case TK_UMINUS:  zUniOp = "UMINUS"; break;
77116     case TK_UPLUS:   zUniOp = "UPLUS";  break;
77117     case TK_BITNOT:  zUniOp = "BITNOT"; break;
77118     case TK_NOT:     zUniOp = "NOT";    break;
77119     case TK_ISNULL:  zUniOp = "ISNULL"; break;
77120     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
77121
77122     case TK_COLLATE: {
77123       sqlite3ExplainExpr(pOut, pExpr->pLeft);
77124       sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
77125       break;
77126     }
77127
77128     case TK_AGG_FUNCTION:
77129     case TK_CONST_FUNC:
77130     case TK_FUNCTION: {
77131       ExprList *pFarg;       /* List of function arguments */
77132       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
77133         pFarg = 0;
77134       }else{
77135         pFarg = pExpr->x.pList;
77136       }
77137       if( op==TK_AGG_FUNCTION ){
77138         sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
77139                              pExpr->op2, pExpr->u.zToken);
77140       }else{
77141         sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
77142       }
77143       if( pFarg ){
77144         sqlite3ExplainExprList(pOut, pFarg);
77145       }
77146       sqlite3ExplainPrintf(pOut, ")");
77147       break;
77148     }
77149 #ifndef SQLITE_OMIT_SUBQUERY
77150     case TK_EXISTS: {
77151       sqlite3ExplainPrintf(pOut, "EXISTS(");
77152       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
77153       sqlite3ExplainPrintf(pOut,")");
77154       break;
77155     }
77156     case TK_SELECT: {
77157       sqlite3ExplainPrintf(pOut, "(");
77158       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
77159       sqlite3ExplainPrintf(pOut, ")");
77160       break;
77161     }
77162     case TK_IN: {
77163       sqlite3ExplainPrintf(pOut, "IN(");
77164       sqlite3ExplainExpr(pOut, pExpr->pLeft);
77165       sqlite3ExplainPrintf(pOut, ",");
77166       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
77167         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
77168       }else{
77169         sqlite3ExplainExprList(pOut, pExpr->x.pList);
77170       }
77171       sqlite3ExplainPrintf(pOut, ")");
77172       break;
77173     }
77174 #endif /* SQLITE_OMIT_SUBQUERY */
77175
77176     /*
77177     **    x BETWEEN y AND z
77178     **
77179     ** This is equivalent to
77180     **
77181     **    x>=y AND x<=z
77182     **
77183     ** X is stored in pExpr->pLeft.
77184     ** Y is stored in pExpr->pList->a[0].pExpr.
77185     ** Z is stored in pExpr->pList->a[1].pExpr.
77186     */
77187     case TK_BETWEEN: {
77188       Expr *pX = pExpr->pLeft;
77189       Expr *pY = pExpr->x.pList->a[0].pExpr;
77190       Expr *pZ = pExpr->x.pList->a[1].pExpr;
77191       sqlite3ExplainPrintf(pOut, "BETWEEN(");
77192       sqlite3ExplainExpr(pOut, pX);
77193       sqlite3ExplainPrintf(pOut, ",");
77194       sqlite3ExplainExpr(pOut, pY);
77195       sqlite3ExplainPrintf(pOut, ",");
77196       sqlite3ExplainExpr(pOut, pZ);
77197       sqlite3ExplainPrintf(pOut, ")");
77198       break;
77199     }
77200     case TK_TRIGGER: {
77201       /* If the opcode is TK_TRIGGER, then the expression is a reference
77202       ** to a column in the new.* or old.* pseudo-tables available to
77203       ** trigger programs. In this case Expr.iTable is set to 1 for the
77204       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
77205       ** is set to the column of the pseudo-table to read, or to -1 to
77206       ** read the rowid field.
77207       */
77208       sqlite3ExplainPrintf(pOut, "%s(%d)", 
77209           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
77210       break;
77211     }
77212     case TK_CASE: {
77213       sqlite3ExplainPrintf(pOut, "CASE(");
77214       sqlite3ExplainExpr(pOut, pExpr->pLeft);
77215       sqlite3ExplainPrintf(pOut, ",");
77216       sqlite3ExplainExprList(pOut, pExpr->x.pList);
77217       break;
77218     }
77219 #ifndef SQLITE_OMIT_TRIGGER
77220     case TK_RAISE: {
77221       const char *zType = "unk";
77222       switch( pExpr->affinity ){
77223         case OE_Rollback:   zType = "rollback";  break;
77224         case OE_Abort:      zType = "abort";     break;
77225         case OE_Fail:       zType = "fail";      break;
77226         case OE_Ignore:     zType = "ignore";    break;
77227       }
77228       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
77229       break;
77230     }
77231 #endif
77232   }
77233   if( zBinOp ){
77234     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
77235     sqlite3ExplainExpr(pOut, pExpr->pLeft);
77236     sqlite3ExplainPrintf(pOut,",");
77237     sqlite3ExplainExpr(pOut, pExpr->pRight);
77238     sqlite3ExplainPrintf(pOut,")");
77239   }else if( zUniOp ){
77240     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
77241     sqlite3ExplainExpr(pOut, pExpr->pLeft);
77242     sqlite3ExplainPrintf(pOut,")");
77243   }
77244 }
77245 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
77246
77247 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
77248 /*
77249 ** Generate a human-readable explanation of an expression list.
77250 */
77251 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
77252   int i;
77253   if( pList==0 || pList->nExpr==0 ){
77254     sqlite3ExplainPrintf(pOut, "(empty-list)");
77255     return;
77256   }else if( pList->nExpr==1 ){
77257     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
77258   }else{
77259     sqlite3ExplainPush(pOut);
77260     for(i=0; i<pList->nExpr; i++){
77261       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
77262       sqlite3ExplainPush(pOut);
77263       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
77264       sqlite3ExplainPop(pOut);
77265       if( pList->a[i].zName ){
77266         sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
77267       }
77268       if( pList->a[i].bSpanIsTab ){
77269         sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
77270       }
77271       if( i<pList->nExpr-1 ){
77272         sqlite3ExplainNL(pOut);
77273       }
77274     }
77275     sqlite3ExplainPop(pOut);
77276   }
77277 }
77278 #endif /* SQLITE_DEBUG */
77279
77280 /*
77281 ** Return TRUE if pExpr is an constant expression that is appropriate
77282 ** for factoring out of a loop.  Appropriate expressions are:
77283 **
77284 **    *  Any expression that evaluates to two or more opcodes.
77285 **
77286 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
77287 **       or OP_Variable that does not need to be placed in a 
77288 **       specific register.
77289 **
77290 ** There is no point in factoring out single-instruction constant
77291 ** expressions that need to be placed in a particular register.  
77292 ** We could factor them out, but then we would end up adding an
77293 ** OP_SCopy instruction to move the value into the correct register
77294 ** later.  We might as well just use the original instruction and
77295 ** avoid the OP_SCopy.
77296 */
77297 static int isAppropriateForFactoring(Expr *p){
77298   if( !sqlite3ExprIsConstantNotJoin(p) ){
77299     return 0;  /* Only constant expressions are appropriate for factoring */
77300   }
77301   if( (p->flags & EP_FixedDest)==0 ){
77302     return 1;  /* Any constant without a fixed destination is appropriate */
77303   }
77304   while( p->op==TK_UPLUS ) p = p->pLeft;
77305   switch( p->op ){
77306 #ifndef SQLITE_OMIT_BLOB_LITERAL
77307     case TK_BLOB:
77308 #endif
77309     case TK_VARIABLE:
77310     case TK_INTEGER:
77311     case TK_FLOAT:
77312     case TK_NULL:
77313     case TK_STRING: {
77314       testcase( p->op==TK_BLOB );
77315       testcase( p->op==TK_VARIABLE );
77316       testcase( p->op==TK_INTEGER );
77317       testcase( p->op==TK_FLOAT );
77318       testcase( p->op==TK_NULL );
77319       testcase( p->op==TK_STRING );
77320       /* Single-instruction constants with a fixed destination are
77321       ** better done in-line.  If we factor them, they will just end
77322       ** up generating an OP_SCopy to move the value to the destination
77323       ** register. */
77324       return 0;
77325     }
77326     case TK_UMINUS: {
77327       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
77328         return 0;
77329       }
77330       break;
77331     }
77332     default: {
77333       break;
77334     }
77335   }
77336   return 1;
77337 }
77338
77339 /*
77340 ** If pExpr is a constant expression that is appropriate for
77341 ** factoring out of a loop, then evaluate the expression
77342 ** into a register and convert the expression into a TK_REGISTER
77343 ** expression.
77344 */
77345 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
77346   Parse *pParse = pWalker->pParse;
77347   switch( pExpr->op ){
77348     case TK_IN:
77349     case TK_REGISTER: {
77350       return WRC_Prune;
77351     }
77352     case TK_COLLATE: {
77353       return WRC_Continue;
77354     }
77355     case TK_FUNCTION:
77356     case TK_AGG_FUNCTION:
77357     case TK_CONST_FUNC: {
77358       /* The arguments to a function have a fixed destination.
77359       ** Mark them this way to avoid generated unneeded OP_SCopy
77360       ** instructions. 
77361       */
77362       ExprList *pList = pExpr->x.pList;
77363       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77364       if( pList ){
77365         int i = pList->nExpr;
77366         struct ExprList_item *pItem = pList->a;
77367         for(; i>0; i--, pItem++){
77368           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
77369         }
77370       }
77371       break;
77372     }
77373   }
77374   if( isAppropriateForFactoring(pExpr) ){
77375     int r1 = ++pParse->nMem;
77376     int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
77377     /* If r2!=r1, it means that register r1 is never used.  That is harmless
77378     ** but suboptimal, so we want to know about the situation to fix it.
77379     ** Hence the following assert: */
77380     assert( r2==r1 );
77381     pExpr->op2 = pExpr->op;
77382     pExpr->op = TK_REGISTER;
77383     pExpr->iTable = r2;
77384     return WRC_Prune;
77385   }
77386   return WRC_Continue;
77387 }
77388
77389 /*
77390 ** Preevaluate constant subexpressions within pExpr and store the
77391 ** results in registers.  Modify pExpr so that the constant subexpresions
77392 ** are TK_REGISTER opcodes that refer to the precomputed values.
77393 **
77394 ** This routine is a no-op if the jump to the cookie-check code has
77395 ** already occur.  Since the cookie-check jump is generated prior to
77396 ** any other serious processing, this check ensures that there is no
77397 ** way to accidently bypass the constant initializations.
77398 **
77399 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
77400 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
77401 ** interface.  This allows test logic to verify that the same answer is
77402 ** obtained for queries regardless of whether or not constants are
77403 ** precomputed into registers or if they are inserted in-line.
77404 */
77405 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
77406   Walker w;
77407   if( pParse->cookieGoto ) return;
77408   if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
77409   w.xExprCallback = evalConstExpr;
77410   w.xSelectCallback = 0;
77411   w.pParse = pParse;
77412   sqlite3WalkExpr(&w, pExpr);
77413 }
77414
77415
77416 /*
77417 ** Generate code that pushes the value of every element of the given
77418 ** expression list into a sequence of registers beginning at target.
77419 **
77420 ** Return the number of elements evaluated.
77421 */
77422 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
77423   Parse *pParse,     /* Parsing context */
77424   ExprList *pList,   /* The expression list to be coded */
77425   int target,        /* Where to write results */
77426   int doHardCopy     /* Make a hard copy of every element */
77427 ){
77428   struct ExprList_item *pItem;
77429   int i, n;
77430   assert( pList!=0 );
77431   assert( target>0 );
77432   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
77433   n = pList->nExpr;
77434   for(pItem=pList->a, i=0; i<n; i++, pItem++){
77435     Expr *pExpr = pItem->pExpr;
77436     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
77437     if( inReg!=target+i ){
77438       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
77439                         inReg, target+i);
77440     }
77441   }
77442   return n;
77443 }
77444
77445 /*
77446 ** Generate code for a BETWEEN operator.
77447 **
77448 **    x BETWEEN y AND z
77449 **
77450 ** The above is equivalent to 
77451 **
77452 **    x>=y AND x<=z
77453 **
77454 ** Code it as such, taking care to do the common subexpression
77455 ** elementation of x.
77456 */
77457 static void exprCodeBetween(
77458   Parse *pParse,    /* Parsing and code generating context */
77459   Expr *pExpr,      /* The BETWEEN expression */
77460   int dest,         /* Jump here if the jump is taken */
77461   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
77462   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
77463 ){
77464   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
77465   Expr compLeft;    /* The  x>=y  term */
77466   Expr compRight;   /* The  x<=z  term */
77467   Expr exprX;       /* The  x  subexpression */
77468   int regFree1 = 0; /* Temporary use register */
77469
77470   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77471   exprX = *pExpr->pLeft;
77472   exprAnd.op = TK_AND;
77473   exprAnd.pLeft = &compLeft;
77474   exprAnd.pRight = &compRight;
77475   compLeft.op = TK_GE;
77476   compLeft.pLeft = &exprX;
77477   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
77478   compRight.op = TK_LE;
77479   compRight.pLeft = &exprX;
77480   compRight.pRight = pExpr->x.pList->a[1].pExpr;
77481   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
77482   exprX.op = TK_REGISTER;
77483   if( jumpIfTrue ){
77484     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
77485   }else{
77486     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
77487   }
77488   sqlite3ReleaseTempReg(pParse, regFree1);
77489
77490   /* Ensure adequate test coverage */
77491   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
77492   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
77493   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
77494   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
77495   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
77496   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
77497   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
77498   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
77499 }
77500
77501 /*
77502 ** Generate code for a boolean expression such that a jump is made
77503 ** to the label "dest" if the expression is true but execution
77504 ** continues straight thru if the expression is false.
77505 **
77506 ** If the expression evaluates to NULL (neither true nor false), then
77507 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
77508 **
77509 ** This code depends on the fact that certain token values (ex: TK_EQ)
77510 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
77511 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
77512 ** the make process cause these values to align.  Assert()s in the code
77513 ** below verify that the numbers are aligned correctly.
77514 */
77515 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77516   Vdbe *v = pParse->pVdbe;
77517   int op = 0;
77518   int regFree1 = 0;
77519   int regFree2 = 0;
77520   int r1, r2;
77521
77522   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
77523   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
77524   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
77525   op = pExpr->op;
77526   switch( op ){
77527     case TK_AND: {
77528       int d2 = sqlite3VdbeMakeLabel(v);
77529       testcase( jumpIfNull==0 );
77530       sqlite3ExprCachePush(pParse);
77531       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
77532       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77533       sqlite3VdbeResolveLabel(v, d2);
77534       sqlite3ExprCachePop(pParse, 1);
77535       break;
77536     }
77537     case TK_OR: {
77538       testcase( jumpIfNull==0 );
77539       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
77540       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77541       break;
77542     }
77543     case TK_NOT: {
77544       testcase( jumpIfNull==0 );
77545       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77546       break;
77547     }
77548     case TK_LT:
77549     case TK_LE:
77550     case TK_GT:
77551     case TK_GE:
77552     case TK_NE:
77553     case TK_EQ: {
77554       assert( TK_LT==OP_Lt );
77555       assert( TK_LE==OP_Le );
77556       assert( TK_GT==OP_Gt );
77557       assert( TK_GE==OP_Ge );
77558       assert( TK_EQ==OP_Eq );
77559       assert( TK_NE==OP_Ne );
77560       testcase( op==TK_LT );
77561       testcase( op==TK_LE );
77562       testcase( op==TK_GT );
77563       testcase( op==TK_GE );
77564       testcase( op==TK_EQ );
77565       testcase( op==TK_NE );
77566       testcase( jumpIfNull==0 );
77567       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77568       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77569       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77570                   r1, r2, dest, jumpIfNull);
77571       testcase( regFree1==0 );
77572       testcase( regFree2==0 );
77573       break;
77574     }
77575     case TK_IS:
77576     case TK_ISNOT: {
77577       testcase( op==TK_IS );
77578       testcase( op==TK_ISNOT );
77579       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77580       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77581       op = (op==TK_IS) ? TK_EQ : TK_NE;
77582       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77583                   r1, r2, dest, SQLITE_NULLEQ);
77584       testcase( regFree1==0 );
77585       testcase( regFree2==0 );
77586       break;
77587     }
77588     case TK_ISNULL:
77589     case TK_NOTNULL: {
77590       assert( TK_ISNULL==OP_IsNull );
77591       assert( TK_NOTNULL==OP_NotNull );
77592       testcase( op==TK_ISNULL );
77593       testcase( op==TK_NOTNULL );
77594       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77595       sqlite3VdbeAddOp2(v, op, r1, dest);
77596       testcase( regFree1==0 );
77597       break;
77598     }
77599     case TK_BETWEEN: {
77600       testcase( jumpIfNull==0 );
77601       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
77602       break;
77603     }
77604 #ifndef SQLITE_OMIT_SUBQUERY
77605     case TK_IN: {
77606       int destIfFalse = sqlite3VdbeMakeLabel(v);
77607       int destIfNull = jumpIfNull ? dest : destIfFalse;
77608       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
77609       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
77610       sqlite3VdbeResolveLabel(v, destIfFalse);
77611       break;
77612     }
77613 #endif
77614     default: {
77615       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
77616       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
77617       testcase( regFree1==0 );
77618       testcase( jumpIfNull==0 );
77619       break;
77620     }
77621   }
77622   sqlite3ReleaseTempReg(pParse, regFree1);
77623   sqlite3ReleaseTempReg(pParse, regFree2);  
77624 }
77625
77626 /*
77627 ** Generate code for a boolean expression such that a jump is made
77628 ** to the label "dest" if the expression is false but execution
77629 ** continues straight thru if the expression is true.
77630 **
77631 ** If the expression evaluates to NULL (neither true nor false) then
77632 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
77633 ** is 0.
77634 */
77635 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77636   Vdbe *v = pParse->pVdbe;
77637   int op = 0;
77638   int regFree1 = 0;
77639   int regFree2 = 0;
77640   int r1, r2;
77641
77642   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
77643   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
77644   if( pExpr==0 )    return;
77645
77646   /* The value of pExpr->op and op are related as follows:
77647   **
77648   **       pExpr->op            op
77649   **       ---------          ----------
77650   **       TK_ISNULL          OP_NotNull
77651   **       TK_NOTNULL         OP_IsNull
77652   **       TK_NE              OP_Eq
77653   **       TK_EQ              OP_Ne
77654   **       TK_GT              OP_Le
77655   **       TK_LE              OP_Gt
77656   **       TK_GE              OP_Lt
77657   **       TK_LT              OP_Ge
77658   **
77659   ** For other values of pExpr->op, op is undefined and unused.
77660   ** The value of TK_ and OP_ constants are arranged such that we
77661   ** can compute the mapping above using the following expression.
77662   ** Assert()s verify that the computation is correct.
77663   */
77664   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
77665
77666   /* Verify correct alignment of TK_ and OP_ constants
77667   */
77668   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
77669   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
77670   assert( pExpr->op!=TK_NE || op==OP_Eq );
77671   assert( pExpr->op!=TK_EQ || op==OP_Ne );
77672   assert( pExpr->op!=TK_LT || op==OP_Ge );
77673   assert( pExpr->op!=TK_LE || op==OP_Gt );
77674   assert( pExpr->op!=TK_GT || op==OP_Le );
77675   assert( pExpr->op!=TK_GE || op==OP_Lt );
77676
77677   switch( pExpr->op ){
77678     case TK_AND: {
77679       testcase( jumpIfNull==0 );
77680       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77681       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
77682       break;
77683     }
77684     case TK_OR: {
77685       int d2 = sqlite3VdbeMakeLabel(v);
77686       testcase( jumpIfNull==0 );
77687       sqlite3ExprCachePush(pParse);
77688       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
77689       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
77690       sqlite3VdbeResolveLabel(v, d2);
77691       sqlite3ExprCachePop(pParse, 1);
77692       break;
77693     }
77694     case TK_NOT: {
77695       testcase( jumpIfNull==0 );
77696       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
77697       break;
77698     }
77699     case TK_LT:
77700     case TK_LE:
77701     case TK_GT:
77702     case TK_GE:
77703     case TK_NE:
77704     case TK_EQ: {
77705       testcase( op==TK_LT );
77706       testcase( op==TK_LE );
77707       testcase( op==TK_GT );
77708       testcase( op==TK_GE );
77709       testcase( op==TK_EQ );
77710       testcase( op==TK_NE );
77711       testcase( jumpIfNull==0 );
77712       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77713       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77714       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77715                   r1, r2, dest, jumpIfNull);
77716       testcase( regFree1==0 );
77717       testcase( regFree2==0 );
77718       break;
77719     }
77720     case TK_IS:
77721     case TK_ISNOT: {
77722       testcase( pExpr->op==TK_IS );
77723       testcase( pExpr->op==TK_ISNOT );
77724       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77725       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77726       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
77727       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77728                   r1, r2, dest, SQLITE_NULLEQ);
77729       testcase( regFree1==0 );
77730       testcase( regFree2==0 );
77731       break;
77732     }
77733     case TK_ISNULL:
77734     case TK_NOTNULL: {
77735       testcase( op==TK_ISNULL );
77736       testcase( op==TK_NOTNULL );
77737       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77738       sqlite3VdbeAddOp2(v, op, r1, dest);
77739       testcase( regFree1==0 );
77740       break;
77741     }
77742     case TK_BETWEEN: {
77743       testcase( jumpIfNull==0 );
77744       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
77745       break;
77746     }
77747 #ifndef SQLITE_OMIT_SUBQUERY
77748     case TK_IN: {
77749       if( jumpIfNull ){
77750         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
77751       }else{
77752         int destIfNull = sqlite3VdbeMakeLabel(v);
77753         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
77754         sqlite3VdbeResolveLabel(v, destIfNull);
77755       }
77756       break;
77757     }
77758 #endif
77759     default: {
77760       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
77761       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
77762       testcase( regFree1==0 );
77763       testcase( jumpIfNull==0 );
77764       break;
77765     }
77766   }
77767   sqlite3ReleaseTempReg(pParse, regFree1);
77768   sqlite3ReleaseTempReg(pParse, regFree2);
77769 }
77770
77771 /*
77772 ** Do a deep comparison of two expression trees.  Return 0 if the two
77773 ** expressions are completely identical.  Return 1 if they differ only
77774 ** by a COLLATE operator at the top level.  Return 2 if there are differences
77775 ** other than the top-level COLLATE operator.
77776 **
77777 ** Sometimes this routine will return 2 even if the two expressions
77778 ** really are equivalent.  If we cannot prove that the expressions are
77779 ** identical, we return 2 just to be safe.  So if this routine
77780 ** returns 2, then you do not really know for certain if the two
77781 ** expressions are the same.  But if you get a 0 or 1 return, then you
77782 ** can be sure the expressions are the same.  In the places where
77783 ** this routine is used, it does not hurt to get an extra 2 - that
77784 ** just might result in some slightly slower code.  But returning
77785 ** an incorrect 0 or 1 could lead to a malfunction.
77786 */
77787 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
77788   if( pA==0||pB==0 ){
77789     return pB==pA ? 0 : 2;
77790   }
77791   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
77792   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
77793   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
77794     return 2;
77795   }
77796   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
77797   if( pA->op!=pB->op ){
77798     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB)<2 ){
77799       return 1;
77800     }
77801     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft)<2 ){
77802       return 1;
77803     }
77804     return 2;
77805   }
77806   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
77807   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
77808   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
77809   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
77810   if( ExprHasProperty(pA, EP_IntValue) ){
77811     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
77812       return 2;
77813     }
77814   }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
77815     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
77816     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
77817       return pA->op==TK_COLLATE ? 1 : 2;
77818     }
77819   }
77820   return 0;
77821 }
77822
77823 /*
77824 ** Compare two ExprList objects.  Return 0 if they are identical and 
77825 ** non-zero if they differ in any way.
77826 **
77827 ** This routine might return non-zero for equivalent ExprLists.  The
77828 ** only consequence will be disabled optimizations.  But this routine
77829 ** must never return 0 if the two ExprList objects are different, or
77830 ** a malfunction will result.
77831 **
77832 ** Two NULL pointers are considered to be the same.  But a NULL pointer
77833 ** always differs from a non-NULL pointer.
77834 */
77835 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
77836   int i;
77837   if( pA==0 && pB==0 ) return 0;
77838   if( pA==0 || pB==0 ) return 1;
77839   if( pA->nExpr!=pB->nExpr ) return 1;
77840   for(i=0; i<pA->nExpr; i++){
77841     Expr *pExprA = pA->a[i].pExpr;
77842     Expr *pExprB = pB->a[i].pExpr;
77843     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
77844     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
77845   }
77846   return 0;
77847 }
77848
77849 /*
77850 ** An instance of the following structure is used by the tree walker
77851 ** to count references to table columns in the arguments of an 
77852 ** aggregate function, in order to implement the
77853 ** sqlite3FunctionThisSrc() routine.
77854 */
77855 struct SrcCount {
77856   SrcList *pSrc;   /* One particular FROM clause in a nested query */
77857   int nThis;       /* Number of references to columns in pSrcList */
77858   int nOther;      /* Number of references to columns in other FROM clauses */
77859 };
77860
77861 /*
77862 ** Count the number of references to columns.
77863 */
77864 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
77865   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
77866   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
77867   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
77868   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
77869   ** NEVER() will need to be removed. */
77870   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
77871     int i;
77872     struct SrcCount *p = pWalker->u.pSrcCount;
77873     SrcList *pSrc = p->pSrc;
77874     for(i=0; i<pSrc->nSrc; i++){
77875       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
77876     }
77877     if( i<pSrc->nSrc ){
77878       p->nThis++;
77879     }else{
77880       p->nOther++;
77881     }
77882   }
77883   return WRC_Continue;
77884 }
77885
77886 /*
77887 ** Determine if any of the arguments to the pExpr Function reference
77888 ** pSrcList.  Return true if they do.  Also return true if the function
77889 ** has no arguments or has only constant arguments.  Return false if pExpr
77890 ** references columns but not columns of tables found in pSrcList.
77891 */
77892 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
77893   Walker w;
77894   struct SrcCount cnt;
77895   assert( pExpr->op==TK_AGG_FUNCTION );
77896   memset(&w, 0, sizeof(w));
77897   w.xExprCallback = exprSrcCount;
77898   w.u.pSrcCount = &cnt;
77899   cnt.pSrc = pSrcList;
77900   cnt.nThis = 0;
77901   cnt.nOther = 0;
77902   sqlite3WalkExprList(&w, pExpr->x.pList);
77903   return cnt.nThis>0 || cnt.nOther==0;
77904 }
77905
77906 /*
77907 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
77908 ** the new element.  Return a negative number if malloc fails.
77909 */
77910 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
77911   int i;
77912   pInfo->aCol = sqlite3ArrayAllocate(
77913        db,
77914        pInfo->aCol,
77915        sizeof(pInfo->aCol[0]),
77916        &pInfo->nColumn,
77917        &i
77918   );
77919   return i;
77920 }    
77921
77922 /*
77923 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
77924 ** the new element.  Return a negative number if malloc fails.
77925 */
77926 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
77927   int i;
77928   pInfo->aFunc = sqlite3ArrayAllocate(
77929        db, 
77930        pInfo->aFunc,
77931        sizeof(pInfo->aFunc[0]),
77932        &pInfo->nFunc,
77933        &i
77934   );
77935   return i;
77936 }    
77937
77938 /*
77939 ** This is the xExprCallback for a tree walker.  It is used to
77940 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
77941 ** for additional information.
77942 */
77943 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
77944   int i;
77945   NameContext *pNC = pWalker->u.pNC;
77946   Parse *pParse = pNC->pParse;
77947   SrcList *pSrcList = pNC->pSrcList;
77948   AggInfo *pAggInfo = pNC->pAggInfo;
77949
77950   switch( pExpr->op ){
77951     case TK_AGG_COLUMN:
77952     case TK_COLUMN: {
77953       testcase( pExpr->op==TK_AGG_COLUMN );
77954       testcase( pExpr->op==TK_COLUMN );
77955       /* Check to see if the column is in one of the tables in the FROM
77956       ** clause of the aggregate query */
77957       if( ALWAYS(pSrcList!=0) ){
77958         struct SrcList_item *pItem = pSrcList->a;
77959         for(i=0; i<pSrcList->nSrc; i++, pItem++){
77960           struct AggInfo_col *pCol;
77961           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
77962           if( pExpr->iTable==pItem->iCursor ){
77963             /* If we reach this point, it means that pExpr refers to a table
77964             ** that is in the FROM clause of the aggregate query.  
77965             **
77966             ** Make an entry for the column in pAggInfo->aCol[] if there
77967             ** is not an entry there already.
77968             */
77969             int k;
77970             pCol = pAggInfo->aCol;
77971             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
77972               if( pCol->iTable==pExpr->iTable &&
77973                   pCol->iColumn==pExpr->iColumn ){
77974                 break;
77975               }
77976             }
77977             if( (k>=pAggInfo->nColumn)
77978              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
77979             ){
77980               pCol = &pAggInfo->aCol[k];
77981               pCol->pTab = pExpr->pTab;
77982               pCol->iTable = pExpr->iTable;
77983               pCol->iColumn = pExpr->iColumn;
77984               pCol->iMem = ++pParse->nMem;
77985               pCol->iSorterColumn = -1;
77986               pCol->pExpr = pExpr;
77987               if( pAggInfo->pGroupBy ){
77988                 int j, n;
77989                 ExprList *pGB = pAggInfo->pGroupBy;
77990                 struct ExprList_item *pTerm = pGB->a;
77991                 n = pGB->nExpr;
77992                 for(j=0; j<n; j++, pTerm++){
77993                   Expr *pE = pTerm->pExpr;
77994                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
77995                       pE->iColumn==pExpr->iColumn ){
77996                     pCol->iSorterColumn = j;
77997                     break;
77998                   }
77999                 }
78000               }
78001               if( pCol->iSorterColumn<0 ){
78002                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
78003               }
78004             }
78005             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
78006             ** because it was there before or because we just created it).
78007             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
78008             ** pAggInfo->aCol[] entry.
78009             */
78010             ExprSetIrreducible(pExpr);
78011             pExpr->pAggInfo = pAggInfo;
78012             pExpr->op = TK_AGG_COLUMN;
78013             pExpr->iAgg = (i16)k;
78014             break;
78015           } /* endif pExpr->iTable==pItem->iCursor */
78016         } /* end loop over pSrcList */
78017       }
78018       return WRC_Prune;
78019     }
78020     case TK_AGG_FUNCTION: {
78021       if( (pNC->ncFlags & NC_InAggFunc)==0
78022        && pWalker->walkerDepth==pExpr->op2
78023       ){
78024         /* Check to see if pExpr is a duplicate of another aggregate 
78025         ** function that is already in the pAggInfo structure
78026         */
78027         struct AggInfo_func *pItem = pAggInfo->aFunc;
78028         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
78029           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
78030             break;
78031           }
78032         }
78033         if( i>=pAggInfo->nFunc ){
78034           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
78035           */
78036           u8 enc = ENC(pParse->db);
78037           i = addAggInfoFunc(pParse->db, pAggInfo);
78038           if( i>=0 ){
78039             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78040             pItem = &pAggInfo->aFunc[i];
78041             pItem->pExpr = pExpr;
78042             pItem->iMem = ++pParse->nMem;
78043             assert( !ExprHasProperty(pExpr, EP_IntValue) );
78044             pItem->pFunc = sqlite3FindFunction(pParse->db,
78045                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
78046                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
78047             if( pExpr->flags & EP_Distinct ){
78048               pItem->iDistinct = pParse->nTab++;
78049             }else{
78050               pItem->iDistinct = -1;
78051             }
78052           }
78053         }
78054         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
78055         */
78056         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
78057         ExprSetIrreducible(pExpr);
78058         pExpr->iAgg = (i16)i;
78059         pExpr->pAggInfo = pAggInfo;
78060         return WRC_Prune;
78061       }else{
78062         return WRC_Continue;
78063       }
78064     }
78065   }
78066   return WRC_Continue;
78067 }
78068 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
78069   UNUSED_PARAMETER(pWalker);
78070   UNUSED_PARAMETER(pSelect);
78071   return WRC_Continue;
78072 }
78073
78074 /*
78075 ** Analyze the pExpr expression looking for aggregate functions and
78076 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
78077 ** points to.  Additional entries are made on the AggInfo object as
78078 ** necessary.
78079 **
78080 ** This routine should only be called after the expression has been
78081 ** analyzed by sqlite3ResolveExprNames().
78082 */
78083 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
78084   Walker w;
78085   memset(&w, 0, sizeof(w));
78086   w.xExprCallback = analyzeAggregate;
78087   w.xSelectCallback = analyzeAggregatesInSelect;
78088   w.u.pNC = pNC;
78089   assert( pNC->pSrcList!=0 );
78090   sqlite3WalkExpr(&w, pExpr);
78091 }
78092
78093 /*
78094 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
78095 ** expression list.  Return the number of errors.
78096 **
78097 ** If an error is found, the analysis is cut short.
78098 */
78099 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
78100   struct ExprList_item *pItem;
78101   int i;
78102   if( pList ){
78103     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
78104       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
78105     }
78106   }
78107 }
78108
78109 /*
78110 ** Allocate a single new register for use to hold some intermediate result.
78111 */
78112 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
78113   if( pParse->nTempReg==0 ){
78114     return ++pParse->nMem;
78115   }
78116   return pParse->aTempReg[--pParse->nTempReg];
78117 }
78118
78119 /*
78120 ** Deallocate a register, making available for reuse for some other
78121 ** purpose.
78122 **
78123 ** If a register is currently being used by the column cache, then
78124 ** the dallocation is deferred until the column cache line that uses
78125 ** the register becomes stale.
78126 */
78127 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
78128   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
78129     int i;
78130     struct yColCache *p;
78131     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78132       if( p->iReg==iReg ){
78133         p->tempReg = 1;
78134         return;
78135       }
78136     }
78137     pParse->aTempReg[pParse->nTempReg++] = iReg;
78138   }
78139 }
78140
78141 /*
78142 ** Allocate or deallocate a block of nReg consecutive registers
78143 */
78144 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
78145   int i, n;
78146   i = pParse->iRangeReg;
78147   n = pParse->nRangeReg;
78148   if( nReg<=n ){
78149     assert( !usedAsColumnCache(pParse, i, i+n-1) );
78150     pParse->iRangeReg += nReg;
78151     pParse->nRangeReg -= nReg;
78152   }else{
78153     i = pParse->nMem+1;
78154     pParse->nMem += nReg;
78155   }
78156   return i;
78157 }
78158 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
78159   sqlite3ExprCacheRemove(pParse, iReg, nReg);
78160   if( nReg>pParse->nRangeReg ){
78161     pParse->nRangeReg = nReg;
78162     pParse->iRangeReg = iReg;
78163   }
78164 }
78165
78166 /*
78167 ** Mark all temporary registers as being unavailable for reuse.
78168 */
78169 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
78170   pParse->nTempReg = 0;
78171   pParse->nRangeReg = 0;
78172 }
78173
78174 /************** End of expr.c ************************************************/
78175 /************** Begin file alter.c *******************************************/
78176 /*
78177 ** 2005 February 15
78178 **
78179 ** The author disclaims copyright to this source code.  In place of
78180 ** a legal notice, here is a blessing:
78181 **
78182 **    May you do good and not evil.
78183 **    May you find forgiveness for yourself and forgive others.
78184 **    May you share freely, never taking more than you give.
78185 **
78186 *************************************************************************
78187 ** This file contains C code routines that used to generate VDBE code
78188 ** that implements the ALTER TABLE command.
78189 */
78190
78191 /*
78192 ** The code in this file only exists if we are not omitting the
78193 ** ALTER TABLE logic from the build.
78194 */
78195 #ifndef SQLITE_OMIT_ALTERTABLE
78196
78197
78198 /*
78199 ** This function is used by SQL generated to implement the 
78200 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
78201 ** CREATE INDEX command. The second is a table name. The table name in 
78202 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
78203 ** argument and the result returned. Examples:
78204 **
78205 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
78206 **     -> 'CREATE TABLE def(a, b, c)'
78207 **
78208 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
78209 **     -> 'CREATE INDEX i ON def(a, b, c)'
78210 */
78211 static void renameTableFunc(
78212   sqlite3_context *context,
78213   int NotUsed,
78214   sqlite3_value **argv
78215 ){
78216   unsigned char const *zSql = sqlite3_value_text(argv[0]);
78217   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
78218
78219   int token;
78220   Token tname;
78221   unsigned char const *zCsr = zSql;
78222   int len = 0;
78223   char *zRet;
78224
78225   sqlite3 *db = sqlite3_context_db_handle(context);
78226
78227   UNUSED_PARAMETER(NotUsed);
78228
78229   /* The principle used to locate the table name in the CREATE TABLE 
78230   ** statement is that the table name is the first non-space token that
78231   ** is immediately followed by a TK_LP or TK_USING token.
78232   */
78233   if( zSql ){
78234     do {
78235       if( !*zCsr ){
78236         /* Ran out of input before finding an opening bracket. Return NULL. */
78237         return;
78238       }
78239
78240       /* Store the token that zCsr points to in tname. */
78241       tname.z = (char*)zCsr;
78242       tname.n = len;
78243
78244       /* Advance zCsr to the next token. Store that token type in 'token',
78245       ** and its length in 'len' (to be used next iteration of this loop).
78246       */
78247       do {
78248         zCsr += len;
78249         len = sqlite3GetToken(zCsr, &token);
78250       } while( token==TK_SPACE );
78251       assert( len>0 );
78252     } while( token!=TK_LP && token!=TK_USING );
78253
78254     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
78255        zTableName, tname.z+tname.n);
78256     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
78257   }
78258 }
78259
78260 /*
78261 ** This C function implements an SQL user function that is used by SQL code
78262 ** generated by the ALTER TABLE ... RENAME command to modify the definition
78263 ** of any foreign key constraints that use the table being renamed as the 
78264 ** parent table. It is passed three arguments:
78265 **
78266 **   1) The complete text of the CREATE TABLE statement being modified,
78267 **   2) The old name of the table being renamed, and
78268 **   3) The new name of the table being renamed.
78269 **
78270 ** It returns the new CREATE TABLE statement. For example:
78271 **
78272 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
78273 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
78274 */
78275 #ifndef SQLITE_OMIT_FOREIGN_KEY
78276 static void renameParentFunc(
78277   sqlite3_context *context,
78278   int NotUsed,
78279   sqlite3_value **argv
78280 ){
78281   sqlite3 *db = sqlite3_context_db_handle(context);
78282   char *zOutput = 0;
78283   char *zResult;
78284   unsigned char const *zInput = sqlite3_value_text(argv[0]);
78285   unsigned char const *zOld = sqlite3_value_text(argv[1]);
78286   unsigned char const *zNew = sqlite3_value_text(argv[2]);
78287
78288   unsigned const char *z;         /* Pointer to token */
78289   int n;                          /* Length of token z */
78290   int token;                      /* Type of token */
78291
78292   UNUSED_PARAMETER(NotUsed);
78293   for(z=zInput; *z; z=z+n){
78294     n = sqlite3GetToken(z, &token);
78295     if( token==TK_REFERENCES ){
78296       char *zParent;
78297       do {
78298         z += n;
78299         n = sqlite3GetToken(z, &token);
78300       }while( token==TK_SPACE );
78301
78302       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
78303       if( zParent==0 ) break;
78304       sqlite3Dequote(zParent);
78305       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
78306         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
78307             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
78308         );
78309         sqlite3DbFree(db, zOutput);
78310         zOutput = zOut;
78311         zInput = &z[n];
78312       }
78313       sqlite3DbFree(db, zParent);
78314     }
78315   }
78316
78317   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
78318   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
78319   sqlite3DbFree(db, zOutput);
78320 }
78321 #endif
78322
78323 #ifndef SQLITE_OMIT_TRIGGER
78324 /* This function is used by SQL generated to implement the
78325 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
78326 ** statement. The second is a table name. The table name in the CREATE 
78327 ** TRIGGER statement is replaced with the third argument and the result 
78328 ** returned. This is analagous to renameTableFunc() above, except for CREATE
78329 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
78330 */
78331 static void renameTriggerFunc(
78332   sqlite3_context *context,
78333   int NotUsed,
78334   sqlite3_value **argv
78335 ){
78336   unsigned char const *zSql = sqlite3_value_text(argv[0]);
78337   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
78338
78339   int token;
78340   Token tname;
78341   int dist = 3;
78342   unsigned char const *zCsr = zSql;
78343   int len = 0;
78344   char *zRet;
78345   sqlite3 *db = sqlite3_context_db_handle(context);
78346
78347   UNUSED_PARAMETER(NotUsed);
78348
78349   /* The principle used to locate the table name in the CREATE TRIGGER 
78350   ** statement is that the table name is the first token that is immediatedly
78351   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
78352   ** of TK_WHEN, TK_BEGIN or TK_FOR.
78353   */
78354   if( zSql ){
78355     do {
78356
78357       if( !*zCsr ){
78358         /* Ran out of input before finding the table name. Return NULL. */
78359         return;
78360       }
78361
78362       /* Store the token that zCsr points to in tname. */
78363       tname.z = (char*)zCsr;
78364       tname.n = len;
78365
78366       /* Advance zCsr to the next token. Store that token type in 'token',
78367       ** and its length in 'len' (to be used next iteration of this loop).
78368       */
78369       do {
78370         zCsr += len;
78371         len = sqlite3GetToken(zCsr, &token);
78372       }while( token==TK_SPACE );
78373       assert( len>0 );
78374
78375       /* Variable 'dist' stores the number of tokens read since the most
78376       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
78377       ** token is read and 'dist' equals 2, the condition stated above
78378       ** to be met.
78379       **
78380       ** Note that ON cannot be a database, table or column name, so
78381       ** there is no need to worry about syntax like 
78382       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
78383       */
78384       dist++;
78385       if( token==TK_DOT || token==TK_ON ){
78386         dist = 0;
78387       }
78388     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
78389
78390     /* Variable tname now contains the token that is the old table-name
78391     ** in the CREATE TRIGGER statement.
78392     */
78393     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
78394        zTableName, tname.z+tname.n);
78395     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
78396   }
78397 }
78398 #endif   /* !SQLITE_OMIT_TRIGGER */
78399
78400 /*
78401 ** Register built-in functions used to help implement ALTER TABLE
78402 */
78403 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
78404   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
78405     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
78406 #ifndef SQLITE_OMIT_TRIGGER
78407     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
78408 #endif
78409 #ifndef SQLITE_OMIT_FOREIGN_KEY
78410     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
78411 #endif
78412   };
78413   int i;
78414   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
78415   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
78416
78417   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
78418     sqlite3FuncDefInsert(pHash, &aFunc[i]);
78419   }
78420 }
78421
78422 /*
78423 ** This function is used to create the text of expressions of the form:
78424 **
78425 **   name=<constant1> OR name=<constant2> OR ...
78426 **
78427 ** If argument zWhere is NULL, then a pointer string containing the text 
78428 ** "name=<constant>" is returned, where <constant> is the quoted version
78429 ** of the string passed as argument zConstant. The returned buffer is
78430 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
78431 ** caller to ensure that it is eventually freed.
78432 **
78433 ** If argument zWhere is not NULL, then the string returned is 
78434 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
78435 ** In this case zWhere is passed to sqlite3DbFree() before returning.
78436 ** 
78437 */
78438 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
78439   char *zNew;
78440   if( !zWhere ){
78441     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
78442   }else{
78443     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
78444     sqlite3DbFree(db, zWhere);
78445   }
78446   return zNew;
78447 }
78448
78449 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78450 /*
78451 ** Generate the text of a WHERE expression which can be used to select all
78452 ** tables that have foreign key constraints that refer to table pTab (i.e.
78453 ** constraints for which pTab is the parent table) from the sqlite_master
78454 ** table.
78455 */
78456 static char *whereForeignKeys(Parse *pParse, Table *pTab){
78457   FKey *p;
78458   char *zWhere = 0;
78459   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
78460     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
78461   }
78462   return zWhere;
78463 }
78464 #endif
78465
78466 /*
78467 ** Generate the text of a WHERE expression which can be used to select all
78468 ** temporary triggers on table pTab from the sqlite_temp_master table. If
78469 ** table pTab has no temporary triggers, or is itself stored in the 
78470 ** temporary database, NULL is returned.
78471 */
78472 static char *whereTempTriggers(Parse *pParse, Table *pTab){
78473   Trigger *pTrig;
78474   char *zWhere = 0;
78475   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
78476
78477   /* If the table is not located in the temp-db (in which case NULL is 
78478   ** returned, loop through the tables list of triggers. For each trigger
78479   ** that is not part of the temp-db schema, add a clause to the WHERE 
78480   ** expression being built up in zWhere.
78481   */
78482   if( pTab->pSchema!=pTempSchema ){
78483     sqlite3 *db = pParse->db;
78484     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78485       if( pTrig->pSchema==pTempSchema ){
78486         zWhere = whereOrName(db, zWhere, pTrig->zName);
78487       }
78488     }
78489   }
78490   if( zWhere ){
78491     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
78492     sqlite3DbFree(pParse->db, zWhere);
78493     zWhere = zNew;
78494   }
78495   return zWhere;
78496 }
78497
78498 /*
78499 ** Generate code to drop and reload the internal representation of table
78500 ** pTab from the database, including triggers and temporary triggers.
78501 ** Argument zName is the name of the table in the database schema at
78502 ** the time the generated code is executed. This can be different from
78503 ** pTab->zName if this function is being called to code part of an 
78504 ** "ALTER TABLE RENAME TO" statement.
78505 */
78506 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
78507   Vdbe *v;
78508   char *zWhere;
78509   int iDb;                   /* Index of database containing pTab */
78510 #ifndef SQLITE_OMIT_TRIGGER
78511   Trigger *pTrig;
78512 #endif
78513
78514   v = sqlite3GetVdbe(pParse);
78515   if( NEVER(v==0) ) return;
78516   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78517   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78518   assert( iDb>=0 );
78519
78520 #ifndef SQLITE_OMIT_TRIGGER
78521   /* Drop any table triggers from the internal schema. */
78522   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78523     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
78524     assert( iTrigDb==iDb || iTrigDb==1 );
78525     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
78526   }
78527 #endif
78528
78529   /* Drop the table and index from the internal schema.  */
78530   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
78531
78532   /* Reload the table, index and permanent trigger schemas. */
78533   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
78534   if( !zWhere ) return;
78535   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
78536
78537 #ifndef SQLITE_OMIT_TRIGGER
78538   /* Now, if the table is not stored in the temp database, reload any temp 
78539   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
78540   */
78541   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78542     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
78543   }
78544 #endif
78545 }
78546
78547 /*
78548 ** Parameter zName is the name of a table that is about to be altered
78549 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
78550 ** If the table is a system table, this function leaves an error message
78551 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
78552 **
78553 ** Or, if zName is not a system table, zero is returned.
78554 */
78555 static int isSystemTable(Parse *pParse, const char *zName){
78556   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
78557     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
78558     return 1;
78559   }
78560   return 0;
78561 }
78562
78563 /*
78564 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
78565 ** command. 
78566 */
78567 SQLITE_PRIVATE void sqlite3AlterRenameTable(
78568   Parse *pParse,            /* Parser context. */
78569   SrcList *pSrc,            /* The table to rename. */
78570   Token *pName              /* The new table name. */
78571 ){
78572   int iDb;                  /* Database that contains the table */
78573   char *zDb;                /* Name of database iDb */
78574   Table *pTab;              /* Table being renamed */
78575   char *zName = 0;          /* NULL-terminated version of pName */ 
78576   sqlite3 *db = pParse->db; /* Database connection */
78577   int nTabName;             /* Number of UTF-8 characters in zTabName */
78578   const char *zTabName;     /* Original name of the table */
78579   Vdbe *v;
78580 #ifndef SQLITE_OMIT_TRIGGER
78581   char *zWhere = 0;         /* Where clause to locate temp triggers */
78582 #endif
78583   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
78584   int savedDbFlags;         /* Saved value of db->flags */
78585
78586   savedDbFlags = db->flags;  
78587   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
78588   assert( pSrc->nSrc==1 );
78589   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78590
78591   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
78592   if( !pTab ) goto exit_rename_table;
78593   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78594   zDb = db->aDb[iDb].zName;
78595   db->flags |= SQLITE_PreferBuiltin;
78596
78597   /* Get a NULL terminated version of the new table name. */
78598   zName = sqlite3NameFromToken(db, pName);
78599   if( !zName ) goto exit_rename_table;
78600
78601   /* Check that a table or index named 'zName' does not already exist
78602   ** in database iDb. If so, this is an error.
78603   */
78604   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
78605     sqlite3ErrorMsg(pParse, 
78606         "there is already another table or index with this name: %s", zName);
78607     goto exit_rename_table;
78608   }
78609
78610   /* Make sure it is not a system table being altered, or a reserved name
78611   ** that the table is being renamed to.
78612   */
78613   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
78614     goto exit_rename_table;
78615   }
78616   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
78617     exit_rename_table;
78618   }
78619
78620 #ifndef SQLITE_OMIT_VIEW
78621   if( pTab->pSelect ){
78622     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
78623     goto exit_rename_table;
78624   }
78625 #endif
78626
78627 #ifndef SQLITE_OMIT_AUTHORIZATION
78628   /* Invoke the authorization callback. */
78629   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
78630     goto exit_rename_table;
78631   }
78632 #endif
78633
78634 #ifndef SQLITE_OMIT_VIRTUALTABLE
78635   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
78636     goto exit_rename_table;
78637   }
78638   if( IsVirtual(pTab) ){
78639     pVTab = sqlite3GetVTable(db, pTab);
78640     if( pVTab->pVtab->pModule->xRename==0 ){
78641       pVTab = 0;
78642     }
78643   }
78644 #endif
78645
78646   /* Begin a transaction and code the VerifyCookie for database iDb. 
78647   ** Then modify the schema cookie (since the ALTER TABLE modifies the
78648   ** schema). Open a statement transaction if the table is a virtual
78649   ** table.
78650   */
78651   v = sqlite3GetVdbe(pParse);
78652   if( v==0 ){
78653     goto exit_rename_table;
78654   }
78655   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
78656   sqlite3ChangeCookie(pParse, iDb);
78657
78658   /* If this is a virtual table, invoke the xRename() function if
78659   ** one is defined. The xRename() callback will modify the names
78660   ** of any resources used by the v-table implementation (including other
78661   ** SQLite tables) that are identified by the name of the virtual table.
78662   */
78663 #ifndef SQLITE_OMIT_VIRTUALTABLE
78664   if( pVTab ){
78665     int i = ++pParse->nMem;
78666     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
78667     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
78668     sqlite3MayAbort(pParse);
78669   }
78670 #endif
78671
78672   /* figure out how many UTF-8 characters are in zName */
78673   zTabName = pTab->zName;
78674   nTabName = sqlite3Utf8CharLen(zTabName, -1);
78675
78676 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78677   if( db->flags&SQLITE_ForeignKeys ){
78678     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
78679     ** statements corresponding to all child tables of foreign key constraints
78680     ** for which the renamed table is the parent table.  */
78681     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
78682       sqlite3NestedParse(pParse, 
78683           "UPDATE \"%w\".%s SET "
78684               "sql = sqlite_rename_parent(sql, %Q, %Q) "
78685               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
78686       sqlite3DbFree(db, zWhere);
78687     }
78688   }
78689 #endif
78690
78691   /* Modify the sqlite_master table to use the new table name. */
78692   sqlite3NestedParse(pParse,
78693       "UPDATE %Q.%s SET "
78694 #ifdef SQLITE_OMIT_TRIGGER
78695           "sql = sqlite_rename_table(sql, %Q), "
78696 #else
78697           "sql = CASE "
78698             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
78699             "ELSE sqlite_rename_table(sql, %Q) END, "
78700 #endif
78701           "tbl_name = %Q, "
78702           "name = CASE "
78703             "WHEN type='table' THEN %Q "
78704             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
78705              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
78706             "ELSE name END "
78707       "WHERE tbl_name=%Q COLLATE nocase AND "
78708           "(type='table' OR type='index' OR type='trigger');", 
78709       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
78710 #ifndef SQLITE_OMIT_TRIGGER
78711       zName,
78712 #endif
78713       zName, nTabName, zTabName
78714   );
78715
78716 #ifndef SQLITE_OMIT_AUTOINCREMENT
78717   /* If the sqlite_sequence table exists in this database, then update 
78718   ** it with the new table name.
78719   */
78720   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
78721     sqlite3NestedParse(pParse,
78722         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
78723         zDb, zName, pTab->zName);
78724   }
78725 #endif
78726
78727 #ifndef SQLITE_OMIT_TRIGGER
78728   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
78729   ** table. Don't do this if the table being ALTERed is itself located in
78730   ** the temp database.
78731   */
78732   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78733     sqlite3NestedParse(pParse, 
78734         "UPDATE sqlite_temp_master SET "
78735             "sql = sqlite_rename_trigger(sql, %Q), "
78736             "tbl_name = %Q "
78737             "WHERE %s;", zName, zName, zWhere);
78738     sqlite3DbFree(db, zWhere);
78739   }
78740 #endif
78741
78742 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78743   if( db->flags&SQLITE_ForeignKeys ){
78744     FKey *p;
78745     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
78746       Table *pFrom = p->pFrom;
78747       if( pFrom!=pTab ){
78748         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
78749       }
78750     }
78751   }
78752 #endif
78753
78754   /* Drop and reload the internal table schema. */
78755   reloadTableSchema(pParse, pTab, zName);
78756
78757 exit_rename_table:
78758   sqlite3SrcListDelete(db, pSrc);
78759   sqlite3DbFree(db, zName);
78760   db->flags = savedDbFlags;
78761 }
78762
78763
78764 /*
78765 ** Generate code to make sure the file format number is at least minFormat.
78766 ** The generated code will increase the file format number if necessary.
78767 */
78768 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
78769   Vdbe *v;
78770   v = sqlite3GetVdbe(pParse);
78771   /* The VDBE should have been allocated before this routine is called.
78772   ** If that allocation failed, we would have quit before reaching this
78773   ** point */
78774   if( ALWAYS(v) ){
78775     int r1 = sqlite3GetTempReg(pParse);
78776     int r2 = sqlite3GetTempReg(pParse);
78777     int j1;
78778     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
78779     sqlite3VdbeUsesBtree(v, iDb);
78780     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
78781     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
78782     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
78783     sqlite3VdbeJumpHere(v, j1);
78784     sqlite3ReleaseTempReg(pParse, r1);
78785     sqlite3ReleaseTempReg(pParse, r2);
78786   }
78787 }
78788
78789 /*
78790 ** This function is called after an "ALTER TABLE ... ADD" statement
78791 ** has been parsed. Argument pColDef contains the text of the new
78792 ** column definition.
78793 **
78794 ** The Table structure pParse->pNewTable was extended to include
78795 ** the new column during parsing.
78796 */
78797 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
78798   Table *pNew;              /* Copy of pParse->pNewTable */
78799   Table *pTab;              /* Table being altered */
78800   int iDb;                  /* Database number */
78801   const char *zDb;          /* Database name */
78802   const char *zTab;         /* Table name */
78803   char *zCol;               /* Null-terminated column definition */
78804   Column *pCol;             /* The new column */
78805   Expr *pDflt;              /* Default value for the new column */
78806   sqlite3 *db;              /* The database connection; */
78807
78808   db = pParse->db;
78809   if( pParse->nErr || db->mallocFailed ) return;
78810   pNew = pParse->pNewTable;
78811   assert( pNew );
78812
78813   assert( sqlite3BtreeHoldsAllMutexes(db) );
78814   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
78815   zDb = db->aDb[iDb].zName;
78816   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
78817   pCol = &pNew->aCol[pNew->nCol-1];
78818   pDflt = pCol->pDflt;
78819   pTab = sqlite3FindTable(db, zTab, zDb);
78820   assert( pTab );
78821
78822 #ifndef SQLITE_OMIT_AUTHORIZATION
78823   /* Invoke the authorization callback. */
78824   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
78825     return;
78826   }
78827 #endif
78828
78829   /* If the default value for the new column was specified with a 
78830   ** literal NULL, then set pDflt to 0. This simplifies checking
78831   ** for an SQL NULL default below.
78832   */
78833   if( pDflt && pDflt->op==TK_NULL ){
78834     pDflt = 0;
78835   }
78836
78837   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
78838   ** If there is a NOT NULL constraint, then the default value for the
78839   ** column must not be NULL.
78840   */
78841   if( pCol->colFlags & COLFLAG_PRIMKEY ){
78842     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
78843     return;
78844   }
78845   if( pNew->pIndex ){
78846     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
78847     return;
78848   }
78849   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
78850     sqlite3ErrorMsg(pParse, 
78851         "Cannot add a REFERENCES column with non-NULL default value");
78852     return;
78853   }
78854   if( pCol->notNull && !pDflt ){
78855     sqlite3ErrorMsg(pParse, 
78856         "Cannot add a NOT NULL column with default value NULL");
78857     return;
78858   }
78859
78860   /* Ensure the default expression is something that sqlite3ValueFromExpr()
78861   ** can handle (i.e. not CURRENT_TIME etc.)
78862   */
78863   if( pDflt ){
78864     sqlite3_value *pVal;
78865     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
78866       db->mallocFailed = 1;
78867       return;
78868     }
78869     if( !pVal ){
78870       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
78871       return;
78872     }
78873     sqlite3ValueFree(pVal);
78874   }
78875
78876   /* Modify the CREATE TABLE statement. */
78877   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
78878   if( zCol ){
78879     char *zEnd = &zCol[pColDef->n-1];
78880     int savedDbFlags = db->flags;
78881     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
78882       *zEnd-- = '\0';
78883     }
78884     db->flags |= SQLITE_PreferBuiltin;
78885     sqlite3NestedParse(pParse, 
78886         "UPDATE \"%w\".%s SET "
78887           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
78888         "WHERE type = 'table' AND name = %Q", 
78889       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
78890       zTab
78891     );
78892     sqlite3DbFree(db, zCol);
78893     db->flags = savedDbFlags;
78894   }
78895
78896   /* If the default value of the new column is NULL, then set the file
78897   ** format to 2. If the default value of the new column is not NULL,
78898   ** the file format becomes 3.
78899   */
78900   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
78901
78902   /* Reload the schema of the modified table. */
78903   reloadTableSchema(pParse, pTab, pTab->zName);
78904 }
78905
78906 /*
78907 ** This function is called by the parser after the table-name in
78908 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
78909 ** pSrc is the full-name of the table being altered.
78910 **
78911 ** This routine makes a (partial) copy of the Table structure
78912 ** for the table being altered and sets Parse.pNewTable to point
78913 ** to it. Routines called by the parser as the column definition
78914 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
78915 ** the copy. The copy of the Table structure is deleted by tokenize.c 
78916 ** after parsing is finished.
78917 **
78918 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
78919 ** coding the "ALTER TABLE ... ADD" statement.
78920 */
78921 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
78922   Table *pNew;
78923   Table *pTab;
78924   Vdbe *v;
78925   int iDb;
78926   int i;
78927   int nAlloc;
78928   sqlite3 *db = pParse->db;
78929
78930   /* Look up the table being altered. */
78931   assert( pParse->pNewTable==0 );
78932   assert( sqlite3BtreeHoldsAllMutexes(db) );
78933   if( db->mallocFailed ) goto exit_begin_add_column;
78934   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
78935   if( !pTab ) goto exit_begin_add_column;
78936
78937 #ifndef SQLITE_OMIT_VIRTUALTABLE
78938   if( IsVirtual(pTab) ){
78939     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
78940     goto exit_begin_add_column;
78941   }
78942 #endif
78943
78944   /* Make sure this is not an attempt to ALTER a view. */
78945   if( pTab->pSelect ){
78946     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
78947     goto exit_begin_add_column;
78948   }
78949   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
78950     goto exit_begin_add_column;
78951   }
78952
78953   assert( pTab->addColOffset>0 );
78954   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78955
78956   /* Put a copy of the Table struct in Parse.pNewTable for the
78957   ** sqlite3AddColumn() function and friends to modify.  But modify
78958   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
78959   ** prefix, we insure that the name will not collide with an existing
78960   ** table because user table are not allowed to have the "sqlite_"
78961   ** prefix on their name.
78962   */
78963   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
78964   if( !pNew ) goto exit_begin_add_column;
78965   pParse->pNewTable = pNew;
78966   pNew->nRef = 1;
78967   pNew->nCol = pTab->nCol;
78968   assert( pNew->nCol>0 );
78969   nAlloc = (((pNew->nCol-1)/8)*8)+8;
78970   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
78971   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
78972   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
78973   if( !pNew->aCol || !pNew->zName ){
78974     db->mallocFailed = 1;
78975     goto exit_begin_add_column;
78976   }
78977   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
78978   for(i=0; i<pNew->nCol; i++){
78979     Column *pCol = &pNew->aCol[i];
78980     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
78981     pCol->zColl = 0;
78982     pCol->zType = 0;
78983     pCol->pDflt = 0;
78984     pCol->zDflt = 0;
78985   }
78986   pNew->pSchema = db->aDb[iDb].pSchema;
78987   pNew->addColOffset = pTab->addColOffset;
78988   pNew->nRef = 1;
78989
78990   /* Begin a transaction and increment the schema cookie.  */
78991   sqlite3BeginWriteOperation(pParse, 0, iDb);
78992   v = sqlite3GetVdbe(pParse);
78993   if( !v ) goto exit_begin_add_column;
78994   sqlite3ChangeCookie(pParse, iDb);
78995
78996 exit_begin_add_column:
78997   sqlite3SrcListDelete(db, pSrc);
78998   return;
78999 }
79000 #endif  /* SQLITE_ALTER_TABLE */
79001
79002 /************** End of alter.c ***********************************************/
79003 /************** Begin file analyze.c *****************************************/
79004 /*
79005 ** 2005 July 8
79006 **
79007 ** The author disclaims copyright to this source code.  In place of
79008 ** a legal notice, here is a blessing:
79009 **
79010 **    May you do good and not evil.
79011 **    May you find forgiveness for yourself and forgive others.
79012 **    May you share freely, never taking more than you give.
79013 **
79014 *************************************************************************
79015 ** This file contains code associated with the ANALYZE command.
79016 **
79017 ** The ANALYZE command gather statistics about the content of tables
79018 ** and indices.  These statistics are made available to the query planner
79019 ** to help it make better decisions about how to perform queries.
79020 **
79021 ** The following system tables are or have been supported:
79022 **
79023 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
79024 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
79025 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
79026 **
79027 ** Additional tables might be added in future releases of SQLite.
79028 ** The sqlite_stat2 table is not created or used unless the SQLite version
79029 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
79030 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
79031 ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
79032 ** created and used by SQLite versions 3.7.9 and later and with
79033 ** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3
79034 ** is a superset of sqlite_stat2.  
79035 **
79036 ** Format of sqlite_stat1:
79037 **
79038 ** There is normally one row per index, with the index identified by the
79039 ** name in the idx column.  The tbl column is the name of the table to
79040 ** which the index belongs.  In each such row, the stat column will be
79041 ** a string consisting of a list of integers.  The first integer in this
79042 ** list is the number of rows in the index and in the table.  The second
79043 ** integer is the average number of rows in the index that have the same
79044 ** value in the first column of the index.  The third integer is the average
79045 ** number of rows in the index that have the same value for the first two
79046 ** columns.  The N-th integer (for N>1) is the average number of rows in 
79047 ** the index which have the same value for the first N-1 columns.  For
79048 ** a K-column index, there will be K+1 integers in the stat column.  If
79049 ** the index is unique, then the last integer will be 1.
79050 **
79051 ** The list of integers in the stat column can optionally be followed
79052 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
79053 ** must be separated from the last integer by a single space.  If the
79054 ** "unordered" keyword is present, then the query planner assumes that
79055 ** the index is unordered and will not use the index for a range query.
79056 ** 
79057 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
79058 ** column contains a single integer which is the (estimated) number of
79059 ** rows in the table identified by sqlite_stat1.tbl.
79060 **
79061 ** Format of sqlite_stat2:
79062 **
79063 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
79064 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
79065 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
79066 ** about the distribution of keys within an index.  The index is identified by
79067 ** the "idx" column and the "tbl" column is the name of the table to which
79068 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
79069 ** table for each index.
79070 **
79071 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
79072 ** inclusive are samples of the left-most key value in the index taken at
79073 ** evenly spaced points along the index.  Let the number of samples be S
79074 ** (10 in the standard build) and let C be the number of rows in the index.
79075 ** Then the sampled rows are given by:
79076 **
79077 **     rownumber = (i*C*2 + C)/(S*2)
79078 **
79079 ** For i between 0 and S-1.  Conceptually, the index space is divided into
79080 ** S uniform buckets and the samples are the middle row from each bucket.
79081 **
79082 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
79083 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
79084 ** writes the sqlite_stat2 table.  This version of SQLite only supports
79085 ** sqlite_stat3.
79086 **
79087 ** Format for sqlite_stat3:
79088 **
79089 ** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is
79090 ** used to avoid compatibility problems.  
79091 **
79092 ** The format of the sqlite_stat3 table is similar to the format of
79093 ** the sqlite_stat2 table.  There are multiple entries for each index.
79094 ** The idx column names the index and the tbl column is the table of the
79095 ** index.  If the idx and tbl columns are the same, then the sample is
79096 ** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
79097 ** the left-most column of the index.  The nEq column is the approximate
79098 ** number of entires in the index whose left-most column exactly matches
79099 ** the sample.  nLt is the approximate number of entires whose left-most
79100 ** column is less than the sample.  The nDLt column is the approximate
79101 ** number of distinct left-most entries in the index that are less than
79102 ** the sample.
79103 **
79104 ** Future versions of SQLite might change to store a string containing
79105 ** multiple integers values in the nDLt column of sqlite_stat3.  The first
79106 ** integer will be the number of prior index entires that are distinct in
79107 ** the left-most column.  The second integer will be the number of prior index
79108 ** entries that are distinct in the first two columns.  The third integer
79109 ** will be the number of prior index entries that are distinct in the first
79110 ** three columns.  And so forth.  With that extension, the nDLt field is
79111 ** similar in function to the sqlite_stat1.stat field.
79112 **
79113 ** There can be an arbitrary number of sqlite_stat3 entries per index.
79114 ** The ANALYZE command will typically generate sqlite_stat3 tables
79115 ** that contain between 10 and 40 samples which are distributed across
79116 ** the key space, though not uniformly, and which include samples with
79117 ** largest possible nEq values.
79118 */
79119 #ifndef SQLITE_OMIT_ANALYZE
79120
79121 /*
79122 ** This routine generates code that opens the sqlite_stat1 table for
79123 ** writing with cursor iStatCur. If the library was built with the
79124 ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
79125 ** opened for writing using cursor (iStatCur+1)
79126 **
79127 ** If the sqlite_stat1 tables does not previously exist, it is created.
79128 ** Similarly, if the sqlite_stat3 table does not exist and the library
79129 ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created. 
79130 **
79131 ** Argument zWhere may be a pointer to a buffer containing a table name,
79132 ** or it may be a NULL pointer. If it is not NULL, then all entries in
79133 ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
79134 ** with the named table are deleted. If zWhere==0, then code is generated
79135 ** to delete all stat table entries.
79136 */
79137 static void openStatTable(
79138   Parse *pParse,          /* Parsing context */
79139   int iDb,                /* The database we are looking in */
79140   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
79141   const char *zWhere,     /* Delete entries for this table or index */
79142   const char *zWhereType  /* Either "tbl" or "idx" */
79143 ){
79144   static const struct {
79145     const char *zName;
79146     const char *zCols;
79147   } aTable[] = {
79148     { "sqlite_stat1", "tbl,idx,stat" },
79149 #ifdef SQLITE_ENABLE_STAT3
79150     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
79151 #endif
79152   };
79153
79154   int aRoot[] = {0, 0};
79155   u8 aCreateTbl[] = {0, 0};
79156
79157   int i;
79158   sqlite3 *db = pParse->db;
79159   Db *pDb;
79160   Vdbe *v = sqlite3GetVdbe(pParse);
79161   if( v==0 ) return;
79162   assert( sqlite3BtreeHoldsAllMutexes(db) );
79163   assert( sqlite3VdbeDb(v)==db );
79164   pDb = &db->aDb[iDb];
79165
79166   /* Create new statistic tables if they do not exist, or clear them
79167   ** if they do already exist.
79168   */
79169   for(i=0; i<ArraySize(aTable); i++){
79170     const char *zTab = aTable[i].zName;
79171     Table *pStat;
79172     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
79173       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
79174       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
79175       ** of the new table in register pParse->regRoot. This is important 
79176       ** because the OpenWrite opcode below will be needing it. */
79177       sqlite3NestedParse(pParse,
79178           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
79179       );
79180       aRoot[i] = pParse->regRoot;
79181       aCreateTbl[i] = OPFLAG_P2ISREG;
79182     }else{
79183       /* The table already exists. If zWhere is not NULL, delete all entries 
79184       ** associated with the table zWhere. If zWhere is NULL, delete the
79185       ** entire contents of the table. */
79186       aRoot[i] = pStat->tnum;
79187       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
79188       if( zWhere ){
79189         sqlite3NestedParse(pParse,
79190            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
79191         );
79192       }else{
79193         /* The sqlite_stat[12] table already exists.  Delete all rows. */
79194         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
79195       }
79196     }
79197   }
79198
79199   /* Open the sqlite_stat[13] tables for writing. */
79200   for(i=0; i<ArraySize(aTable); i++){
79201     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
79202     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
79203     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
79204   }
79205 }
79206
79207 /*
79208 ** Recommended number of samples for sqlite_stat3
79209 */
79210 #ifndef SQLITE_STAT3_SAMPLES
79211 # define SQLITE_STAT3_SAMPLES 24
79212 #endif
79213
79214 /*
79215 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
79216 ** share an instance of the following structure to hold their state
79217 ** information.
79218 */
79219 typedef struct Stat3Accum Stat3Accum;
79220 struct Stat3Accum {
79221   tRowcnt nRow;             /* Number of rows in the entire table */
79222   tRowcnt nPSample;         /* How often to do a periodic sample */
79223   int iMin;                 /* Index of entry with minimum nEq and hash */
79224   int mxSample;             /* Maximum number of samples to accumulate */
79225   int nSample;              /* Current number of samples */
79226   u32 iPrn;                 /* Pseudo-random number used for sampling */
79227   struct Stat3Sample {
79228     i64 iRowid;                /* Rowid in main table of the key */
79229     tRowcnt nEq;               /* sqlite_stat3.nEq */
79230     tRowcnt nLt;               /* sqlite_stat3.nLt */
79231     tRowcnt nDLt;              /* sqlite_stat3.nDLt */
79232     u8 isPSample;              /* True if a periodic sample */
79233     u32 iHash;                 /* Tiebreaker hash */
79234   } *a;                     /* An array of samples */
79235 };
79236
79237 #ifdef SQLITE_ENABLE_STAT3
79238 /*
79239 ** Implementation of the stat3_init(C,S) SQL function.  The two parameters
79240 ** are the number of rows in the table or index (C) and the number of samples
79241 ** to accumulate (S).
79242 **
79243 ** This routine allocates the Stat3Accum object.
79244 **
79245 ** The return value is the Stat3Accum object (P).
79246 */
79247 static void stat3Init(
79248   sqlite3_context *context,
79249   int argc,
79250   sqlite3_value **argv
79251 ){
79252   Stat3Accum *p;
79253   tRowcnt nRow;
79254   int mxSample;
79255   int n;
79256
79257   UNUSED_PARAMETER(argc);
79258   nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
79259   mxSample = sqlite3_value_int(argv[1]);
79260   n = sizeof(*p) + sizeof(p->a[0])*mxSample;
79261   p = sqlite3MallocZero( n );
79262   if( p==0 ){
79263     sqlite3_result_error_nomem(context);
79264     return;
79265   }
79266   p->a = (struct Stat3Sample*)&p[1];
79267   p->nRow = nRow;
79268   p->mxSample = mxSample;
79269   p->nPSample = p->nRow/(mxSample/3+1) + 1;
79270   sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
79271   sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
79272 }
79273 static const FuncDef stat3InitFuncdef = {
79274   2,                /* nArg */
79275   SQLITE_UTF8,      /* iPrefEnc */
79276   0,                /* flags */
79277   0,                /* pUserData */
79278   0,                /* pNext */
79279   stat3Init,        /* xFunc */
79280   0,                /* xStep */
79281   0,                /* xFinalize */
79282   "stat3_init",     /* zName */
79283   0,                /* pHash */
79284   0                 /* pDestructor */
79285 };
79286
79287
79288 /*
79289 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
79290 ** arguments describe a single key instance.  This routine makes the 
79291 ** decision about whether or not to retain this key for the sqlite_stat3
79292 ** table.
79293 **
79294 ** The return value is NULL.
79295 */
79296 static void stat3Push(
79297   sqlite3_context *context,
79298   int argc,
79299   sqlite3_value **argv
79300 ){
79301   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
79302   tRowcnt nEq = sqlite3_value_int64(argv[0]);
79303   tRowcnt nLt = sqlite3_value_int64(argv[1]);
79304   tRowcnt nDLt = sqlite3_value_int64(argv[2]);
79305   i64 rowid = sqlite3_value_int64(argv[3]);
79306   u8 isPSample = 0;
79307   u8 doInsert = 0;
79308   int iMin = p->iMin;
79309   struct Stat3Sample *pSample;
79310   int i;
79311   u32 h;
79312
79313   UNUSED_PARAMETER(context);
79314   UNUSED_PARAMETER(argc);
79315   if( nEq==0 ) return;
79316   h = p->iPrn = p->iPrn*1103515245 + 12345;
79317   if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
79318     doInsert = isPSample = 1;
79319   }else if( p->nSample<p->mxSample ){
79320     doInsert = 1;
79321   }else{
79322     if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
79323       doInsert = 1;
79324     }
79325   }
79326   if( !doInsert ) return;
79327   if( p->nSample==p->mxSample ){
79328     assert( p->nSample - iMin - 1 >= 0 );
79329     memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
79330     pSample = &p->a[p->nSample-1];
79331   }else{
79332     pSample = &p->a[p->nSample++];
79333   }
79334   pSample->iRowid = rowid;
79335   pSample->nEq = nEq;
79336   pSample->nLt = nLt;
79337   pSample->nDLt = nDLt;
79338   pSample->iHash = h;
79339   pSample->isPSample = isPSample;
79340
79341   /* Find the new minimum */
79342   if( p->nSample==p->mxSample ){
79343     pSample = p->a;
79344     i = 0;
79345     while( pSample->isPSample ){
79346       i++;
79347       pSample++;
79348       assert( i<p->nSample );
79349     }
79350     nEq = pSample->nEq;
79351     h = pSample->iHash;
79352     iMin = i;
79353     for(i++, pSample++; i<p->nSample; i++, pSample++){
79354       if( pSample->isPSample ) continue;
79355       if( pSample->nEq<nEq
79356        || (pSample->nEq==nEq && pSample->iHash<h)
79357       ){
79358         iMin = i;
79359         nEq = pSample->nEq;
79360         h = pSample->iHash;
79361       }
79362     }
79363     p->iMin = iMin;
79364   }
79365 }
79366 static const FuncDef stat3PushFuncdef = {
79367   5,                /* nArg */
79368   SQLITE_UTF8,      /* iPrefEnc */
79369   0,                /* flags */
79370   0,                /* pUserData */
79371   0,                /* pNext */
79372   stat3Push,        /* xFunc */
79373   0,                /* xStep */
79374   0,                /* xFinalize */
79375   "stat3_push",     /* zName */
79376   0,                /* pHash */
79377   0                 /* pDestructor */
79378 };
79379
79380 /*
79381 ** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
79382 ** used to query the results.  Content is returned for the Nth sqlite_stat3
79383 ** row where N is between 0 and S-1 and S is the number of samples.  The
79384 ** value returned depends on the number of arguments.
79385 **
79386 **   argc==2    result:  rowid
79387 **   argc==3    result:  nEq
79388 **   argc==4    result:  nLt
79389 **   argc==5    result:  nDLt
79390 */
79391 static void stat3Get(
79392   sqlite3_context *context,
79393   int argc,
79394   sqlite3_value **argv
79395 ){
79396   int n = sqlite3_value_int(argv[1]);
79397   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
79398
79399   assert( p!=0 );
79400   if( p->nSample<=n ) return;
79401   switch( argc ){
79402     case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;
79403     case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;
79404     case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;
79405     default: sqlite3_result_int64(context, p->a[n].nDLt);   break;
79406   }
79407 }
79408 static const FuncDef stat3GetFuncdef = {
79409   -1,               /* nArg */
79410   SQLITE_UTF8,      /* iPrefEnc */
79411   0,                /* flags */
79412   0,                /* pUserData */
79413   0,                /* pNext */
79414   stat3Get,         /* xFunc */
79415   0,                /* xStep */
79416   0,                /* xFinalize */
79417   "stat3_get",     /* zName */
79418   0,                /* pHash */
79419   0                 /* pDestructor */
79420 };
79421 #endif /* SQLITE_ENABLE_STAT3 */
79422
79423
79424
79425
79426 /*
79427 ** Generate code to do an analysis of all indices associated with
79428 ** a single table.
79429 */
79430 static void analyzeOneTable(
79431   Parse *pParse,   /* Parser context */
79432   Table *pTab,     /* Table whose indices are to be analyzed */
79433   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
79434   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
79435   int iMem         /* Available memory locations begin here */
79436 ){
79437   sqlite3 *db = pParse->db;    /* Database handle */
79438   Index *pIdx;                 /* An index to being analyzed */
79439   int iIdxCur;                 /* Cursor open on index being analyzed */
79440   Vdbe *v;                     /* The virtual machine being built up */
79441   int i;                       /* Loop counter */
79442   int topOfLoop;               /* The top of the loop */
79443   int endOfLoop;               /* The end of the loop */
79444   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
79445   int iDb;                     /* Index of database containing pTab */
79446   int regTabname = iMem++;     /* Register containing table name */
79447   int regIdxname = iMem++;     /* Register containing index name */
79448   int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
79449 #ifdef SQLITE_ENABLE_STAT3
79450   int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
79451   int regNumLt = iMem++;       /* Number of keys less than regSample */
79452   int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
79453   int regSample = iMem++;      /* The next sample value */
79454   int regRowid = regSample;    /* Rowid of a sample */
79455   int regAccum = iMem++;       /* Register to hold Stat3Accum object */
79456   int regLoop = iMem++;        /* Loop counter */
79457   int regCount = iMem++;       /* Number of rows in the table or index */
79458   int regTemp1 = iMem++;       /* Intermediate register */
79459   int regTemp2 = iMem++;       /* Intermediate register */
79460   int once = 1;                /* One-time initialization */
79461   int shortJump = 0;           /* Instruction address */
79462   int iTabCur = pParse->nTab++; /* Table cursor */
79463 #endif
79464   int regCol = iMem++;         /* Content of a column in analyzed table */
79465   int regRec = iMem++;         /* Register holding completed record */
79466   int regTemp = iMem++;        /* Temporary use register */
79467   int regNewRowid = iMem++;    /* Rowid for the inserted record */
79468
79469
79470   v = sqlite3GetVdbe(pParse);
79471   if( v==0 || NEVER(pTab==0) ){
79472     return;
79473   }
79474   if( pTab->tnum==0 ){
79475     /* Do not gather statistics on views or virtual tables */
79476     return;
79477   }
79478   if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
79479     /* Do not gather statistics on system tables */
79480     return;
79481   }
79482   assert( sqlite3BtreeHoldsAllMutexes(db) );
79483   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79484   assert( iDb>=0 );
79485   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79486 #ifndef SQLITE_OMIT_AUTHORIZATION
79487   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
79488       db->aDb[iDb].zName ) ){
79489     return;
79490   }
79491 #endif
79492
79493   /* Establish a read-lock on the table at the shared-cache level. */
79494   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
79495
79496   iIdxCur = pParse->nTab++;
79497   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
79498   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79499     int nCol;
79500     KeyInfo *pKey;
79501     int addrIfNot = 0;           /* address of OP_IfNot */
79502     int *aChngAddr;              /* Array of jump instruction addresses */
79503
79504     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
79505     VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
79506     nCol = pIdx->nColumn;
79507     aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
79508     if( aChngAddr==0 ) continue;
79509     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
79510     if( iMem+1+(nCol*2)>pParse->nMem ){
79511       pParse->nMem = iMem+1+(nCol*2);
79512     }
79513
79514     /* Open a cursor to the index to be analyzed. */
79515     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
79516     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
79517         (char *)pKey, P4_KEYINFO_HANDOFF);
79518     VdbeComment((v, "%s", pIdx->zName));
79519
79520     /* Populate the register containing the index name. */
79521     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
79522
79523 #ifdef SQLITE_ENABLE_STAT3
79524     if( once ){
79525       once = 0;
79526       sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
79527     }
79528     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
79529     sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
79530     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
79531     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
79532     sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
79533     sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
79534     sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
79535                       (char*)&stat3InitFuncdef, P4_FUNCDEF);
79536     sqlite3VdbeChangeP5(v, 2);
79537 #endif /* SQLITE_ENABLE_STAT3 */
79538
79539     /* The block of memory cells initialized here is used as follows.
79540     **
79541     **    iMem:                
79542     **        The total number of rows in the table.
79543     **
79544     **    iMem+1 .. iMem+nCol: 
79545     **        Number of distinct entries in index considering the 
79546     **        left-most N columns only, where N is between 1 and nCol, 
79547     **        inclusive.
79548     **
79549     **    iMem+nCol+1 .. Mem+2*nCol:  
79550     **        Previous value of indexed columns, from left to right.
79551     **
79552     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
79553     ** initialized to contain an SQL NULL.
79554     */
79555     for(i=0; i<=nCol; i++){
79556       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
79557     }
79558     for(i=0; i<nCol; i++){
79559       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
79560     }
79561
79562     /* Start the analysis loop. This loop runs through all the entries in
79563     ** the index b-tree.  */
79564     endOfLoop = sqlite3VdbeMakeLabel(v);
79565     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
79566     topOfLoop = sqlite3VdbeCurrentAddr(v);
79567     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
79568
79569     for(i=0; i<nCol; i++){
79570       CollSeq *pColl;
79571       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
79572       if( i==0 ){
79573         /* Always record the very first row */
79574         addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
79575       }
79576       assert( pIdx->azColl!=0 );
79577       assert( pIdx->azColl[i]!=0 );
79578       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
79579       aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
79580                                       (char*)pColl, P4_COLLSEQ);
79581       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
79582       VdbeComment((v, "jump if column %d changed", i));
79583 #ifdef SQLITE_ENABLE_STAT3
79584       if( i==0 ){
79585         sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
79586         VdbeComment((v, "incr repeat count"));
79587       }
79588 #endif
79589     }
79590     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
79591     for(i=0; i<nCol; i++){
79592       sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
79593       if( i==0 ){
79594         sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
79595 #ifdef SQLITE_ENABLE_STAT3
79596         sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79597                           (char*)&stat3PushFuncdef, P4_FUNCDEF);
79598         sqlite3VdbeChangeP5(v, 5);
79599         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
79600         sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
79601         sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
79602         sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
79603 #endif        
79604       }
79605       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
79606       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
79607     }
79608     sqlite3DbFree(db, aChngAddr);
79609
79610     /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
79611     sqlite3VdbeResolveLabel(v, endOfLoop);
79612
79613     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
79614     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
79615 #ifdef SQLITE_ENABLE_STAT3
79616     sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79617                       (char*)&stat3PushFuncdef, P4_FUNCDEF);
79618     sqlite3VdbeChangeP5(v, 5);
79619     sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
79620     shortJump = 
79621     sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
79622     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
79623                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79624     sqlite3VdbeChangeP5(v, 2);
79625     sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
79626     sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
79627     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
79628     sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
79629     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
79630                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79631     sqlite3VdbeChangeP5(v, 3);
79632     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
79633                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79634     sqlite3VdbeChangeP5(v, 4);
79635     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
79636                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79637     sqlite3VdbeChangeP5(v, 5);
79638     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
79639     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
79640     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
79641     sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
79642     sqlite3VdbeJumpHere(v, shortJump+2);
79643 #endif        
79644
79645     /* Store the results in sqlite_stat1.
79646     **
79647     ** The result is a single row of the sqlite_stat1 table.  The first
79648     ** two columns are the names of the table and index.  The third column
79649     ** is a string composed of a list of integer statistics about the
79650     ** index.  The first integer in the list is the total number of entries
79651     ** in the index.  There is one additional integer in the list for each
79652     ** column of the table.  This additional integer is a guess of how many
79653     ** rows of the table the index will select.  If D is the count of distinct
79654     ** values and K is the total number of rows, then the integer is computed
79655     ** as:
79656     **
79657     **        I = (K+D-1)/D
79658     **
79659     ** If K==0 then no entry is made into the sqlite_stat1 table.  
79660     ** If K>0 then it is always the case the D>0 so division by zero
79661     ** is never possible.
79662     */
79663     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
79664     if( jZeroRows<0 ){
79665       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
79666     }
79667     for(i=0; i<nCol; i++){
79668       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
79669       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79670       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
79671       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
79672       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
79673       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
79674       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79675     }
79676     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79677     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79678     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79679     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79680   }
79681
79682   /* If the table has no indices, create a single sqlite_stat1 entry
79683   ** containing NULL as the index name and the row count as the content.
79684   */
79685   if( pTab->pIndex==0 ){
79686     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
79687     VdbeComment((v, "%s", pTab->zName));
79688     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
79689     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
79690     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
79691   }else{
79692     sqlite3VdbeJumpHere(v, jZeroRows);
79693     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
79694   }
79695   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
79696   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79697   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79698   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79699   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79700   if( pParse->nMem<regRec ) pParse->nMem = regRec;
79701   sqlite3VdbeJumpHere(v, jZeroRows);
79702 }
79703
79704
79705 /*
79706 ** Generate code that will cause the most recent index analysis to
79707 ** be loaded into internal hash tables where is can be used.
79708 */
79709 static void loadAnalysis(Parse *pParse, int iDb){
79710   Vdbe *v = sqlite3GetVdbe(pParse);
79711   if( v ){
79712     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
79713   }
79714 }
79715
79716 /*
79717 ** Generate code that will do an analysis of an entire database
79718 */
79719 static void analyzeDatabase(Parse *pParse, int iDb){
79720   sqlite3 *db = pParse->db;
79721   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
79722   HashElem *k;
79723   int iStatCur;
79724   int iMem;
79725
79726   sqlite3BeginWriteOperation(pParse, 0, iDb);
79727   iStatCur = pParse->nTab;
79728   pParse->nTab += 3;
79729   openStatTable(pParse, iDb, iStatCur, 0, 0);
79730   iMem = pParse->nMem+1;
79731   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79732   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
79733     Table *pTab = (Table*)sqliteHashData(k);
79734     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
79735   }
79736   loadAnalysis(pParse, iDb);
79737 }
79738
79739 /*
79740 ** Generate code that will do an analysis of a single table in
79741 ** a database.  If pOnlyIdx is not NULL then it is a single index
79742 ** in pTab that should be analyzed.
79743 */
79744 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
79745   int iDb;
79746   int iStatCur;
79747
79748   assert( pTab!=0 );
79749   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79750   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79751   sqlite3BeginWriteOperation(pParse, 0, iDb);
79752   iStatCur = pParse->nTab;
79753   pParse->nTab += 3;
79754   if( pOnlyIdx ){
79755     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
79756   }else{
79757     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
79758   }
79759   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
79760   loadAnalysis(pParse, iDb);
79761 }
79762
79763 /*
79764 ** Generate code for the ANALYZE command.  The parser calls this routine
79765 ** when it recognizes an ANALYZE command.
79766 **
79767 **        ANALYZE                            -- 1
79768 **        ANALYZE  <database>                -- 2
79769 **        ANALYZE  ?<database>.?<tablename>  -- 3
79770 **
79771 ** Form 1 causes all indices in all attached databases to be analyzed.
79772 ** Form 2 analyzes all indices the single database named.
79773 ** Form 3 analyzes all indices associated with the named table.
79774 */
79775 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
79776   sqlite3 *db = pParse->db;
79777   int iDb;
79778   int i;
79779   char *z, *zDb;
79780   Table *pTab;
79781   Index *pIdx;
79782   Token *pTableName;
79783
79784   /* Read the database schema. If an error occurs, leave an error message
79785   ** and code in pParse and return NULL. */
79786   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79787   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79788     return;
79789   }
79790
79791   assert( pName2!=0 || pName1==0 );
79792   if( pName1==0 ){
79793     /* Form 1:  Analyze everything */
79794     for(i=0; i<db->nDb; i++){
79795       if( i==1 ) continue;  /* Do not analyze the TEMP database */
79796       analyzeDatabase(pParse, i);
79797     }
79798   }else if( pName2->n==0 ){
79799     /* Form 2:  Analyze the database or table named */
79800     iDb = sqlite3FindDb(db, pName1);
79801     if( iDb>=0 ){
79802       analyzeDatabase(pParse, iDb);
79803     }else{
79804       z = sqlite3NameFromToken(db, pName1);
79805       if( z ){
79806         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
79807           analyzeTable(pParse, pIdx->pTable, pIdx);
79808         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
79809           analyzeTable(pParse, pTab, 0);
79810         }
79811         sqlite3DbFree(db, z);
79812       }
79813     }
79814   }else{
79815     /* Form 3: Analyze the fully qualified table name */
79816     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
79817     if( iDb>=0 ){
79818       zDb = db->aDb[iDb].zName;
79819       z = sqlite3NameFromToken(db, pTableName);
79820       if( z ){
79821         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
79822           analyzeTable(pParse, pIdx->pTable, pIdx);
79823         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
79824           analyzeTable(pParse, pTab, 0);
79825         }
79826         sqlite3DbFree(db, z);
79827       }
79828     }   
79829   }
79830 }
79831
79832 /*
79833 ** Used to pass information from the analyzer reader through to the
79834 ** callback routine.
79835 */
79836 typedef struct analysisInfo analysisInfo;
79837 struct analysisInfo {
79838   sqlite3 *db;
79839   const char *zDatabase;
79840 };
79841
79842 /*
79843 ** This callback is invoked once for each index when reading the
79844 ** sqlite_stat1 table.  
79845 **
79846 **     argv[0] = name of the table
79847 **     argv[1] = name of the index (might be NULL)
79848 **     argv[2] = results of analysis - on integer for each column
79849 **
79850 ** Entries for which argv[1]==NULL simply record the number of rows in
79851 ** the table.
79852 */
79853 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
79854   analysisInfo *pInfo = (analysisInfo*)pData;
79855   Index *pIndex;
79856   Table *pTable;
79857   int i, c, n;
79858   tRowcnt v;
79859   const char *z;
79860
79861   assert( argc==3 );
79862   UNUSED_PARAMETER2(NotUsed, argc);
79863
79864   if( argv==0 || argv[0]==0 || argv[2]==0 ){
79865     return 0;
79866   }
79867   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
79868   if( pTable==0 ){
79869     return 0;
79870   }
79871   if( argv[1] ){
79872     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
79873   }else{
79874     pIndex = 0;
79875   }
79876   n = pIndex ? pIndex->nColumn : 0;
79877   z = argv[2];
79878   for(i=0; *z && i<=n; i++){
79879     v = 0;
79880     while( (c=z[0])>='0' && c<='9' ){
79881       v = v*10 + c - '0';
79882       z++;
79883     }
79884     if( i==0 ) pTable->nRowEst = v;
79885     if( pIndex==0 ) break;
79886     pIndex->aiRowEst[i] = v;
79887     if( *z==' ' ) z++;
79888     if( strcmp(z, "unordered")==0 ){
79889       pIndex->bUnordered = 1;
79890       break;
79891     }
79892   }
79893   return 0;
79894 }
79895
79896 /*
79897 ** If the Index.aSample variable is not NULL, delete the aSample[] array
79898 ** and its contents.
79899 */
79900 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
79901 #ifdef SQLITE_ENABLE_STAT3
79902   if( pIdx->aSample ){
79903     int j;
79904     for(j=0; j<pIdx->nSample; j++){
79905       IndexSample *p = &pIdx->aSample[j];
79906       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
79907         sqlite3DbFree(db, p->u.z);
79908       }
79909     }
79910     sqlite3DbFree(db, pIdx->aSample);
79911   }
79912   if( db && db->pnBytesFreed==0 ){
79913     pIdx->nSample = 0;
79914     pIdx->aSample = 0;
79915   }
79916 #else
79917   UNUSED_PARAMETER(db);
79918   UNUSED_PARAMETER(pIdx);
79919 #endif
79920 }
79921
79922 #ifdef SQLITE_ENABLE_STAT3
79923 /*
79924 ** Load content from the sqlite_stat3 table into the Index.aSample[]
79925 ** arrays of all indices.
79926 */
79927 static int loadStat3(sqlite3 *db, const char *zDb){
79928   int rc;                       /* Result codes from subroutines */
79929   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
79930   char *zSql;                   /* Text of the SQL statement */
79931   Index *pPrevIdx = 0;          /* Previous index in the loop */
79932   int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
79933   int eType;                    /* Datatype of a sample */
79934   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
79935
79936   assert( db->lookaside.bEnabled==0 );
79937   if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
79938     return SQLITE_OK;
79939   }
79940
79941   zSql = sqlite3MPrintf(db, 
79942       "SELECT idx,count(*) FROM %Q.sqlite_stat3"
79943       " GROUP BY idx", zDb);
79944   if( !zSql ){
79945     return SQLITE_NOMEM;
79946   }
79947   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
79948   sqlite3DbFree(db, zSql);
79949   if( rc ) return rc;
79950
79951   while( sqlite3_step(pStmt)==SQLITE_ROW ){
79952     char *zIndex;   /* Index name */
79953     Index *pIdx;    /* Pointer to the index object */
79954     int nSample;    /* Number of samples */
79955
79956     zIndex = (char *)sqlite3_column_text(pStmt, 0);
79957     if( zIndex==0 ) continue;
79958     nSample = sqlite3_column_int(pStmt, 1);
79959     pIdx = sqlite3FindIndex(db, zIndex, zDb);
79960     if( pIdx==0 ) continue;
79961     assert( pIdx->nSample==0 );
79962     pIdx->nSample = nSample;
79963     pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
79964     pIdx->avgEq = pIdx->aiRowEst[1];
79965     if( pIdx->aSample==0 ){
79966       db->mallocFailed = 1;
79967       sqlite3_finalize(pStmt);
79968       return SQLITE_NOMEM;
79969     }
79970   }
79971   rc = sqlite3_finalize(pStmt);
79972   if( rc ) return rc;
79973
79974   zSql = sqlite3MPrintf(db, 
79975       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
79976   if( !zSql ){
79977     return SQLITE_NOMEM;
79978   }
79979   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
79980   sqlite3DbFree(db, zSql);
79981   if( rc ) return rc;
79982
79983   while( sqlite3_step(pStmt)==SQLITE_ROW ){
79984     char *zIndex;   /* Index name */
79985     Index *pIdx;    /* Pointer to the index object */
79986     int i;          /* Loop counter */
79987     tRowcnt sumEq;  /* Sum of the nEq values */
79988
79989     zIndex = (char *)sqlite3_column_text(pStmt, 0);
79990     if( zIndex==0 ) continue;
79991     pIdx = sqlite3FindIndex(db, zIndex, zDb);
79992     if( pIdx==0 ) continue;
79993     if( pIdx==pPrevIdx ){
79994       idx++;
79995     }else{
79996       pPrevIdx = pIdx;
79997       idx = 0;
79998     }
79999     assert( idx<pIdx->nSample );
80000     pSample = &pIdx->aSample[idx];
80001     pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
80002     pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
80003     pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
80004     if( idx==pIdx->nSample-1 ){
80005       if( pSample->nDLt>0 ){
80006         for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
80007         pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
80008       }
80009       if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
80010     }
80011     eType = sqlite3_column_type(pStmt, 4);
80012     pSample->eType = (u8)eType;
80013     switch( eType ){
80014       case SQLITE_INTEGER: {
80015         pSample->u.i = sqlite3_column_int64(pStmt, 4);
80016         break;
80017       }
80018       case SQLITE_FLOAT: {
80019         pSample->u.r = sqlite3_column_double(pStmt, 4);
80020         break;
80021       }
80022       case SQLITE_NULL: {
80023         break;
80024       }
80025       default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
80026         const char *z = (const char *)(
80027               (eType==SQLITE_BLOB) ?
80028               sqlite3_column_blob(pStmt, 4):
80029               sqlite3_column_text(pStmt, 4)
80030            );
80031         int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
80032         pSample->nByte = n;
80033         if( n < 1){
80034           pSample->u.z = 0;
80035         }else{
80036           pSample->u.z = sqlite3DbMallocRaw(db, n);
80037           if( pSample->u.z==0 ){
80038             db->mallocFailed = 1;
80039             sqlite3_finalize(pStmt);
80040             return SQLITE_NOMEM;
80041           }
80042           memcpy(pSample->u.z, z, n);
80043         }
80044       }
80045     }
80046   }
80047   return sqlite3_finalize(pStmt);
80048 }
80049 #endif /* SQLITE_ENABLE_STAT3 */
80050
80051 /*
80052 ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
80053 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
80054 ** arrays. The contents of sqlite_stat3 are used to populate the
80055 ** Index.aSample[] arrays.
80056 **
80057 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
80058 ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined 
80059 ** during compilation and the sqlite_stat3 table is present, no data is 
80060 ** read from it.
80061 **
80062 ** If SQLITE_ENABLE_STAT3 was defined during compilation and the 
80063 ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
80064 ** returned. However, in this case, data is read from the sqlite_stat1
80065 ** table (if it is present) before returning.
80066 **
80067 ** If an OOM error occurs, this function always sets db->mallocFailed.
80068 ** This means if the caller does not care about other errors, the return
80069 ** code may be ignored.
80070 */
80071 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
80072   analysisInfo sInfo;
80073   HashElem *i;
80074   char *zSql;
80075   int rc;
80076
80077   assert( iDb>=0 && iDb<db->nDb );
80078   assert( db->aDb[iDb].pBt!=0 );
80079
80080   /* Clear any prior statistics */
80081   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80082   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
80083     Index *pIdx = sqliteHashData(i);
80084     sqlite3DefaultRowEst(pIdx);
80085 #ifdef SQLITE_ENABLE_STAT3
80086     sqlite3DeleteIndexSamples(db, pIdx);
80087     pIdx->aSample = 0;
80088 #endif
80089   }
80090
80091   /* Check to make sure the sqlite_stat1 table exists */
80092   sInfo.db = db;
80093   sInfo.zDatabase = db->aDb[iDb].zName;
80094   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
80095     return SQLITE_ERROR;
80096   }
80097
80098   /* Load new statistics out of the sqlite_stat1 table */
80099   zSql = sqlite3MPrintf(db, 
80100       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
80101   if( zSql==0 ){
80102     rc = SQLITE_NOMEM;
80103   }else{
80104     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
80105     sqlite3DbFree(db, zSql);
80106   }
80107
80108
80109   /* Load the statistics from the sqlite_stat3 table. */
80110 #ifdef SQLITE_ENABLE_STAT3
80111   if( rc==SQLITE_OK ){
80112     int lookasideEnabled = db->lookaside.bEnabled;
80113     db->lookaside.bEnabled = 0;
80114     rc = loadStat3(db, sInfo.zDatabase);
80115     db->lookaside.bEnabled = lookasideEnabled;
80116   }
80117 #endif
80118
80119   if( rc==SQLITE_NOMEM ){
80120     db->mallocFailed = 1;
80121   }
80122   return rc;
80123 }
80124
80125
80126 #endif /* SQLITE_OMIT_ANALYZE */
80127
80128 /************** End of analyze.c *********************************************/
80129 /************** Begin file attach.c ******************************************/
80130 /*
80131 ** 2003 April 6
80132 **
80133 ** The author disclaims copyright to this source code.  In place of
80134 ** a legal notice, here is a blessing:
80135 **
80136 **    May you do good and not evil.
80137 **    May you find forgiveness for yourself and forgive others.
80138 **    May you share freely, never taking more than you give.
80139 **
80140 *************************************************************************
80141 ** This file contains code used to implement the ATTACH and DETACH commands.
80142 */
80143
80144 #ifndef SQLITE_OMIT_ATTACH
80145 /*
80146 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
80147 ** is slightly different from resolving a normal SQL expression, because simple
80148 ** identifiers are treated as strings, not possible column names or aliases.
80149 **
80150 ** i.e. if the parser sees:
80151 **
80152 **     ATTACH DATABASE abc AS def
80153 **
80154 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
80155 ** looking for columns of the same name.
80156 **
80157 ** This only applies to the root node of pExpr, so the statement:
80158 **
80159 **     ATTACH DATABASE abc||def AS 'db2'
80160 **
80161 ** will fail because neither abc or def can be resolved.
80162 */
80163 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
80164 {
80165   int rc = SQLITE_OK;
80166   if( pExpr ){
80167     if( pExpr->op!=TK_ID ){
80168       rc = sqlite3ResolveExprNames(pName, pExpr);
80169       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
80170         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
80171         return SQLITE_ERROR;
80172       }
80173     }else{
80174       pExpr->op = TK_STRING;
80175     }
80176   }
80177   return rc;
80178 }
80179
80180 /*
80181 ** An SQL user-function registered to do the work of an ATTACH statement. The
80182 ** three arguments to the function come directly from an attach statement:
80183 **
80184 **     ATTACH DATABASE x AS y KEY z
80185 **
80186 **     SELECT sqlite_attach(x, y, z)
80187 **
80188 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
80189 ** third argument.
80190 */
80191 static void attachFunc(
80192   sqlite3_context *context,
80193   int NotUsed,
80194   sqlite3_value **argv
80195 ){
80196   int i;
80197   int rc = 0;
80198   sqlite3 *db = sqlite3_context_db_handle(context);
80199   const char *zName;
80200   const char *zFile;
80201   char *zPath = 0;
80202   char *zErr = 0;
80203   unsigned int flags;
80204   Db *aNew;
80205   char *zErrDyn = 0;
80206   sqlite3_vfs *pVfs;
80207
80208   UNUSED_PARAMETER(NotUsed);
80209
80210   zFile = (const char *)sqlite3_value_text(argv[0]);
80211   zName = (const char *)sqlite3_value_text(argv[1]);
80212   if( zFile==0 ) zFile = "";
80213   if( zName==0 ) zName = "";
80214
80215   /* Check for the following errors:
80216   **
80217   **     * Too many attached databases,
80218   **     * Transaction currently open
80219   **     * Specified database name already being used.
80220   */
80221   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
80222     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
80223       db->aLimit[SQLITE_LIMIT_ATTACHED]
80224     );
80225     goto attach_error;
80226   }
80227   if( !db->autoCommit ){
80228     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
80229     goto attach_error;
80230   }
80231   for(i=0; i<db->nDb; i++){
80232     char *z = db->aDb[i].zName;
80233     assert( z && zName );
80234     if( sqlite3StrICmp(z, zName)==0 ){
80235       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
80236       goto attach_error;
80237     }
80238   }
80239
80240   /* Allocate the new entry in the db->aDb[] array and initialize the schema
80241   ** hash tables.
80242   */
80243   if( db->aDb==db->aDbStatic ){
80244     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
80245     if( aNew==0 ) return;
80246     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
80247   }else{
80248     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
80249     if( aNew==0 ) return;
80250   }
80251   db->aDb = aNew;
80252   aNew = &db->aDb[db->nDb];
80253   memset(aNew, 0, sizeof(*aNew));
80254
80255   /* Open the database file. If the btree is successfully opened, use
80256   ** it to obtain the database schema. At this point the schema may
80257   ** or may not be initialized.
80258   */
80259   flags = db->openFlags;
80260   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
80261   if( rc!=SQLITE_OK ){
80262     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
80263     sqlite3_result_error(context, zErr, -1);
80264     sqlite3_free(zErr);
80265     return;
80266   }
80267   assert( pVfs );
80268   flags |= SQLITE_OPEN_MAIN_DB;
80269   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
80270   sqlite3_free( zPath );
80271   db->nDb++;
80272   if( rc==SQLITE_CONSTRAINT ){
80273     rc = SQLITE_ERROR;
80274     zErrDyn = sqlite3MPrintf(db, "database is already attached");
80275   }else if( rc==SQLITE_OK ){
80276     Pager *pPager;
80277     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
80278     if( !aNew->pSchema ){
80279       rc = SQLITE_NOMEM;
80280     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
80281       zErrDyn = sqlite3MPrintf(db, 
80282         "attached databases must use the same text encoding as main database");
80283       rc = SQLITE_ERROR;
80284     }
80285     pPager = sqlite3BtreePager(aNew->pBt);
80286     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
80287     sqlite3BtreeSecureDelete(aNew->pBt,
80288                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
80289   }
80290   aNew->safety_level = 3;
80291   aNew->zName = sqlite3DbStrDup(db, zName);
80292   if( rc==SQLITE_OK && aNew->zName==0 ){
80293     rc = SQLITE_NOMEM;
80294   }
80295
80296
80297 #ifdef SQLITE_HAS_CODEC
80298   if( rc==SQLITE_OK ){
80299     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
80300     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
80301     int nKey;
80302     char *zKey;
80303     int t = sqlite3_value_type(argv[2]);
80304     switch( t ){
80305       case SQLITE_INTEGER:
80306       case SQLITE_FLOAT:
80307         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
80308         rc = SQLITE_ERROR;
80309         break;
80310         
80311       case SQLITE_TEXT:
80312       case SQLITE_BLOB:
80313         nKey = sqlite3_value_bytes(argv[2]);
80314         zKey = (char *)sqlite3_value_blob(argv[2]);
80315         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
80316         break;
80317
80318       case SQLITE_NULL:
80319         /* No key specified.  Use the key from the main database */
80320         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
80321         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
80322           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
80323         }
80324         break;
80325     }
80326   }
80327 #endif
80328
80329   /* If the file was opened successfully, read the schema for the new database.
80330   ** If this fails, or if opening the file failed, then close the file and 
80331   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
80332   ** we found it.
80333   */
80334   if( rc==SQLITE_OK ){
80335     sqlite3BtreeEnterAll(db);
80336     rc = sqlite3Init(db, &zErrDyn);
80337     sqlite3BtreeLeaveAll(db);
80338   }
80339   if( rc ){
80340     int iDb = db->nDb - 1;
80341     assert( iDb>=2 );
80342     if( db->aDb[iDb].pBt ){
80343       sqlite3BtreeClose(db->aDb[iDb].pBt);
80344       db->aDb[iDb].pBt = 0;
80345       db->aDb[iDb].pSchema = 0;
80346     }
80347     sqlite3ResetAllSchemasOfConnection(db);
80348     db->nDb = iDb;
80349     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
80350       db->mallocFailed = 1;
80351       sqlite3DbFree(db, zErrDyn);
80352       zErrDyn = sqlite3MPrintf(db, "out of memory");
80353     }else if( zErrDyn==0 ){
80354       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
80355     }
80356     goto attach_error;
80357   }
80358   
80359   return;
80360
80361 attach_error:
80362   /* Return an error if we get here */
80363   if( zErrDyn ){
80364     sqlite3_result_error(context, zErrDyn, -1);
80365     sqlite3DbFree(db, zErrDyn);
80366   }
80367   if( rc ) sqlite3_result_error_code(context, rc);
80368 }
80369
80370 /*
80371 ** An SQL user-function registered to do the work of an DETACH statement. The
80372 ** three arguments to the function come directly from a detach statement:
80373 **
80374 **     DETACH DATABASE x
80375 **
80376 **     SELECT sqlite_detach(x)
80377 */
80378 static void detachFunc(
80379   sqlite3_context *context,
80380   int NotUsed,
80381   sqlite3_value **argv
80382 ){
80383   const char *zName = (const char *)sqlite3_value_text(argv[0]);
80384   sqlite3 *db = sqlite3_context_db_handle(context);
80385   int i;
80386   Db *pDb = 0;
80387   char zErr[128];
80388
80389   UNUSED_PARAMETER(NotUsed);
80390
80391   if( zName==0 ) zName = "";
80392   for(i=0; i<db->nDb; i++){
80393     pDb = &db->aDb[i];
80394     if( pDb->pBt==0 ) continue;
80395     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
80396   }
80397
80398   if( i>=db->nDb ){
80399     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
80400     goto detach_error;
80401   }
80402   if( i<2 ){
80403     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
80404     goto detach_error;
80405   }
80406   if( !db->autoCommit ){
80407     sqlite3_snprintf(sizeof(zErr), zErr,
80408                      "cannot DETACH database within transaction");
80409     goto detach_error;
80410   }
80411   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
80412     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
80413     goto detach_error;
80414   }
80415
80416   sqlite3BtreeClose(pDb->pBt);
80417   pDb->pBt = 0;
80418   pDb->pSchema = 0;
80419   sqlite3ResetAllSchemasOfConnection(db);
80420   return;
80421
80422 detach_error:
80423   sqlite3_result_error(context, zErr, -1);
80424 }
80425
80426 /*
80427 ** This procedure generates VDBE code for a single invocation of either the
80428 ** sqlite_detach() or sqlite_attach() SQL user functions.
80429 */
80430 static void codeAttach(
80431   Parse *pParse,       /* The parser context */
80432   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
80433   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
80434   Expr *pAuthArg,      /* Expression to pass to authorization callback */
80435   Expr *pFilename,     /* Name of database file */
80436   Expr *pDbname,       /* Name of the database to use internally */
80437   Expr *pKey           /* Database key for encryption extension */
80438 ){
80439   int rc;
80440   NameContext sName;
80441   Vdbe *v;
80442   sqlite3* db = pParse->db;
80443   int regArgs;
80444
80445   memset(&sName, 0, sizeof(NameContext));
80446   sName.pParse = pParse;
80447
80448   if( 
80449       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
80450       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
80451       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
80452   ){
80453     pParse->nErr++;
80454     goto attach_end;
80455   }
80456
80457 #ifndef SQLITE_OMIT_AUTHORIZATION
80458   if( pAuthArg ){
80459     char *zAuthArg;
80460     if( pAuthArg->op==TK_STRING ){
80461       zAuthArg = pAuthArg->u.zToken;
80462     }else{
80463       zAuthArg = 0;
80464     }
80465     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
80466     if(rc!=SQLITE_OK ){
80467       goto attach_end;
80468     }
80469   }
80470 #endif /* SQLITE_OMIT_AUTHORIZATION */
80471
80472
80473   v = sqlite3GetVdbe(pParse);
80474   regArgs = sqlite3GetTempRange(pParse, 4);
80475   sqlite3ExprCode(pParse, pFilename, regArgs);
80476   sqlite3ExprCode(pParse, pDbname, regArgs+1);
80477   sqlite3ExprCode(pParse, pKey, regArgs+2);
80478
80479   assert( v || db->mallocFailed );
80480   if( v ){
80481     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
80482     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
80483     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
80484     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
80485
80486     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
80487     ** statement only). For DETACH, set it to false (expire all existing
80488     ** statements).
80489     */
80490     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
80491   }
80492   
80493 attach_end:
80494   sqlite3ExprDelete(db, pFilename);
80495   sqlite3ExprDelete(db, pDbname);
80496   sqlite3ExprDelete(db, pKey);
80497 }
80498
80499 /*
80500 ** Called by the parser to compile a DETACH statement.
80501 **
80502 **     DETACH pDbname
80503 */
80504 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
80505   static const FuncDef detach_func = {
80506     1,                /* nArg */
80507     SQLITE_UTF8,      /* iPrefEnc */
80508     0,                /* flags */
80509     0,                /* pUserData */
80510     0,                /* pNext */
80511     detachFunc,       /* xFunc */
80512     0,                /* xStep */
80513     0,                /* xFinalize */
80514     "sqlite_detach",  /* zName */
80515     0,                /* pHash */
80516     0                 /* pDestructor */
80517   };
80518   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
80519 }
80520
80521 /*
80522 ** Called by the parser to compile an ATTACH statement.
80523 **
80524 **     ATTACH p AS pDbname KEY pKey
80525 */
80526 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
80527   static const FuncDef attach_func = {
80528     3,                /* nArg */
80529     SQLITE_UTF8,      /* iPrefEnc */
80530     0,                /* flags */
80531     0,                /* pUserData */
80532     0,                /* pNext */
80533     attachFunc,       /* xFunc */
80534     0,                /* xStep */
80535     0,                /* xFinalize */
80536     "sqlite_attach",  /* zName */
80537     0,                /* pHash */
80538     0                 /* pDestructor */
80539   };
80540   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
80541 }
80542 #endif /* SQLITE_OMIT_ATTACH */
80543
80544 /*
80545 ** Initialize a DbFixer structure.  This routine must be called prior
80546 ** to passing the structure to one of the sqliteFixAAAA() routines below.
80547 **
80548 ** The return value indicates whether or not fixation is required.  TRUE
80549 ** means we do need to fix the database references, FALSE means we do not.
80550 */
80551 SQLITE_PRIVATE int sqlite3FixInit(
80552   DbFixer *pFix,      /* The fixer to be initialized */
80553   Parse *pParse,      /* Error messages will be written here */
80554   int iDb,            /* This is the database that must be used */
80555   const char *zType,  /* "view", "trigger", or "index" */
80556   const Token *pName  /* Name of the view, trigger, or index */
80557 ){
80558   sqlite3 *db;
80559
80560   if( NEVER(iDb<0) || iDb==1 ) return 0;
80561   db = pParse->db;
80562   assert( db->nDb>iDb );
80563   pFix->pParse = pParse;
80564   pFix->zDb = db->aDb[iDb].zName;
80565   pFix->pSchema = db->aDb[iDb].pSchema;
80566   pFix->zType = zType;
80567   pFix->pName = pName;
80568   return 1;
80569 }
80570
80571 /*
80572 ** The following set of routines walk through the parse tree and assign
80573 ** a specific database to all table references where the database name
80574 ** was left unspecified in the original SQL statement.  The pFix structure
80575 ** must have been initialized by a prior call to sqlite3FixInit().
80576 **
80577 ** These routines are used to make sure that an index, trigger, or
80578 ** view in one database does not refer to objects in a different database.
80579 ** (Exception: indices, triggers, and views in the TEMP database are
80580 ** allowed to refer to anything.)  If a reference is explicitly made
80581 ** to an object in a different database, an error message is added to
80582 ** pParse->zErrMsg and these routines return non-zero.  If everything
80583 ** checks out, these routines return 0.
80584 */
80585 SQLITE_PRIVATE int sqlite3FixSrcList(
80586   DbFixer *pFix,       /* Context of the fixation */
80587   SrcList *pList       /* The Source list to check and modify */
80588 ){
80589   int i;
80590   const char *zDb;
80591   struct SrcList_item *pItem;
80592
80593   if( NEVER(pList==0) ) return 0;
80594   zDb = pFix->zDb;
80595   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
80596     if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
80597       sqlite3ErrorMsg(pFix->pParse,
80598          "%s %T cannot reference objects in database %s",
80599          pFix->zType, pFix->pName, pItem->zDatabase);
80600       return 1;
80601     }
80602     sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
80603     pItem->zDatabase = 0;
80604     pItem->pSchema = pFix->pSchema;
80605 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
80606     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
80607     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
80608 #endif
80609   }
80610   return 0;
80611 }
80612 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
80613 SQLITE_PRIVATE int sqlite3FixSelect(
80614   DbFixer *pFix,       /* Context of the fixation */
80615   Select *pSelect      /* The SELECT statement to be fixed to one database */
80616 ){
80617   while( pSelect ){
80618     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
80619       return 1;
80620     }
80621     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
80622       return 1;
80623     }
80624     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
80625       return 1;
80626     }
80627     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
80628       return 1;
80629     }
80630     pSelect = pSelect->pPrior;
80631   }
80632   return 0;
80633 }
80634 SQLITE_PRIVATE int sqlite3FixExpr(
80635   DbFixer *pFix,     /* Context of the fixation */
80636   Expr *pExpr        /* The expression to be fixed to one database */
80637 ){
80638   while( pExpr ){
80639     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
80640     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80641       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
80642     }else{
80643       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
80644     }
80645     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
80646       return 1;
80647     }
80648     pExpr = pExpr->pLeft;
80649   }
80650   return 0;
80651 }
80652 SQLITE_PRIVATE int sqlite3FixExprList(
80653   DbFixer *pFix,     /* Context of the fixation */
80654   ExprList *pList    /* The expression to be fixed to one database */
80655 ){
80656   int i;
80657   struct ExprList_item *pItem;
80658   if( pList==0 ) return 0;
80659   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
80660     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
80661       return 1;
80662     }
80663   }
80664   return 0;
80665 }
80666 #endif
80667
80668 #ifndef SQLITE_OMIT_TRIGGER
80669 SQLITE_PRIVATE int sqlite3FixTriggerStep(
80670   DbFixer *pFix,     /* Context of the fixation */
80671   TriggerStep *pStep /* The trigger step be fixed to one database */
80672 ){
80673   while( pStep ){
80674     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
80675       return 1;
80676     }
80677     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
80678       return 1;
80679     }
80680     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
80681       return 1;
80682     }
80683     pStep = pStep->pNext;
80684   }
80685   return 0;
80686 }
80687 #endif
80688
80689 /************** End of attach.c **********************************************/
80690 /************** Begin file auth.c ********************************************/
80691 /*
80692 ** 2003 January 11
80693 **
80694 ** The author disclaims copyright to this source code.  In place of
80695 ** a legal notice, here is a blessing:
80696 **
80697 **    May you do good and not evil.
80698 **    May you find forgiveness for yourself and forgive others.
80699 **    May you share freely, never taking more than you give.
80700 **
80701 *************************************************************************
80702 ** This file contains code used to implement the sqlite3_set_authorizer()
80703 ** API.  This facility is an optional feature of the library.  Embedded
80704 ** systems that do not need this facility may omit it by recompiling
80705 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
80706 */
80707
80708 /*
80709 ** All of the code in this file may be omitted by defining a single
80710 ** macro.
80711 */
80712 #ifndef SQLITE_OMIT_AUTHORIZATION
80713
80714 /*
80715 ** Set or clear the access authorization function.
80716 **
80717 ** The access authorization function is be called during the compilation
80718 ** phase to verify that the user has read and/or write access permission on
80719 ** various fields of the database.  The first argument to the auth function
80720 ** is a copy of the 3rd argument to this routine.  The second argument
80721 ** to the auth function is one of these constants:
80722 **
80723 **       SQLITE_CREATE_INDEX
80724 **       SQLITE_CREATE_TABLE
80725 **       SQLITE_CREATE_TEMP_INDEX
80726 **       SQLITE_CREATE_TEMP_TABLE
80727 **       SQLITE_CREATE_TEMP_TRIGGER
80728 **       SQLITE_CREATE_TEMP_VIEW
80729 **       SQLITE_CREATE_TRIGGER
80730 **       SQLITE_CREATE_VIEW
80731 **       SQLITE_DELETE
80732 **       SQLITE_DROP_INDEX
80733 **       SQLITE_DROP_TABLE
80734 **       SQLITE_DROP_TEMP_INDEX
80735 **       SQLITE_DROP_TEMP_TABLE
80736 **       SQLITE_DROP_TEMP_TRIGGER
80737 **       SQLITE_DROP_TEMP_VIEW
80738 **       SQLITE_DROP_TRIGGER
80739 **       SQLITE_DROP_VIEW
80740 **       SQLITE_INSERT
80741 **       SQLITE_PRAGMA
80742 **       SQLITE_READ
80743 **       SQLITE_SELECT
80744 **       SQLITE_TRANSACTION
80745 **       SQLITE_UPDATE
80746 **
80747 ** The third and fourth arguments to the auth function are the name of
80748 ** the table and the column that are being accessed.  The auth function
80749 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
80750 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
80751 ** means that the SQL statement will never-run - the sqlite3_exec() call
80752 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
80753 ** should run but attempts to read the specified column will return NULL
80754 ** and attempts to write the column will be ignored.
80755 **
80756 ** Setting the auth function to NULL disables this hook.  The default
80757 ** setting of the auth function is NULL.
80758 */
80759 SQLITE_API int sqlite3_set_authorizer(
80760   sqlite3 *db,
80761   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
80762   void *pArg
80763 ){
80764   sqlite3_mutex_enter(db->mutex);
80765   db->xAuth = xAuth;
80766   db->pAuthArg = pArg;
80767   sqlite3ExpirePreparedStatements(db);
80768   sqlite3_mutex_leave(db->mutex);
80769   return SQLITE_OK;
80770 }
80771
80772 /*
80773 ** Write an error message into pParse->zErrMsg that explains that the
80774 ** user-supplied authorization function returned an illegal value.
80775 */
80776 static void sqliteAuthBadReturnCode(Parse *pParse){
80777   sqlite3ErrorMsg(pParse, "authorizer malfunction");
80778   pParse->rc = SQLITE_ERROR;
80779 }
80780
80781 /*
80782 ** Invoke the authorization callback for permission to read column zCol from
80783 ** table zTab in database zDb. This function assumes that an authorization
80784 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
80785 **
80786 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
80787 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
80788 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
80789 */
80790 SQLITE_PRIVATE int sqlite3AuthReadCol(
80791   Parse *pParse,                  /* The parser context */
80792   const char *zTab,               /* Table name */
80793   const char *zCol,               /* Column name */
80794   int iDb                         /* Index of containing database. */
80795 ){
80796   sqlite3 *db = pParse->db;       /* Database handle */
80797   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
80798   int rc;                         /* Auth callback return code */
80799
80800   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
80801   if( rc==SQLITE_DENY ){
80802     if( db->nDb>2 || iDb!=0 ){
80803       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
80804     }else{
80805       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
80806     }
80807     pParse->rc = SQLITE_AUTH;
80808   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
80809     sqliteAuthBadReturnCode(pParse);
80810   }
80811   return rc;
80812 }
80813
80814 /*
80815 ** The pExpr should be a TK_COLUMN expression.  The table referred to
80816 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
80817 ** Check to see if it is OK to read this particular column.
80818 **
80819 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
80820 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
80821 ** then generate an error.
80822 */
80823 SQLITE_PRIVATE void sqlite3AuthRead(
80824   Parse *pParse,        /* The parser context */
80825   Expr *pExpr,          /* The expression to check authorization on */
80826   Schema *pSchema,      /* The schema of the expression */
80827   SrcList *pTabList     /* All table that pExpr might refer to */
80828 ){
80829   sqlite3 *db = pParse->db;
80830   Table *pTab = 0;      /* The table being read */
80831   const char *zCol;     /* Name of the column of the table */
80832   int iSrc;             /* Index in pTabList->a[] of table being read */
80833   int iDb;              /* The index of the database the expression refers to */
80834   int iCol;             /* Index of column in table */
80835
80836   if( db->xAuth==0 ) return;
80837   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
80838   if( iDb<0 ){
80839     /* An attempt to read a column out of a subquery or other
80840     ** temporary table. */
80841     return;
80842   }
80843
80844   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
80845   if( pExpr->op==TK_TRIGGER ){
80846     pTab = pParse->pTriggerTab;
80847   }else{
80848     assert( pTabList );
80849     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
80850       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
80851         pTab = pTabList->a[iSrc].pTab;
80852         break;
80853       }
80854     }
80855   }
80856   iCol = pExpr->iColumn;
80857   if( NEVER(pTab==0) ) return;
80858
80859   if( iCol>=0 ){
80860     assert( iCol<pTab->nCol );
80861     zCol = pTab->aCol[iCol].zName;
80862   }else if( pTab->iPKey>=0 ){
80863     assert( pTab->iPKey<pTab->nCol );
80864     zCol = pTab->aCol[pTab->iPKey].zName;
80865   }else{
80866     zCol = "ROWID";
80867   }
80868   assert( iDb>=0 && iDb<db->nDb );
80869   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
80870     pExpr->op = TK_NULL;
80871   }
80872 }
80873
80874 /*
80875 ** Do an authorization check using the code and arguments given.  Return
80876 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
80877 ** is returned, then the error count and error message in pParse are
80878 ** modified appropriately.
80879 */
80880 SQLITE_PRIVATE int sqlite3AuthCheck(
80881   Parse *pParse,
80882   int code,
80883   const char *zArg1,
80884   const char *zArg2,
80885   const char *zArg3
80886 ){
80887   sqlite3 *db = pParse->db;
80888   int rc;
80889
80890   /* Don't do any authorization checks if the database is initialising
80891   ** or if the parser is being invoked from within sqlite3_declare_vtab.
80892   */
80893   if( db->init.busy || IN_DECLARE_VTAB ){
80894     return SQLITE_OK;
80895   }
80896
80897   if( db->xAuth==0 ){
80898     return SQLITE_OK;
80899   }
80900   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
80901   if( rc==SQLITE_DENY ){
80902     sqlite3ErrorMsg(pParse, "not authorized");
80903     pParse->rc = SQLITE_AUTH;
80904   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
80905     rc = SQLITE_DENY;
80906     sqliteAuthBadReturnCode(pParse);
80907   }
80908   return rc;
80909 }
80910
80911 /*
80912 ** Push an authorization context.  After this routine is called, the
80913 ** zArg3 argument to authorization callbacks will be zContext until
80914 ** popped.  Or if pParse==0, this routine is a no-op.
80915 */
80916 SQLITE_PRIVATE void sqlite3AuthContextPush(
80917   Parse *pParse,
80918   AuthContext *pContext, 
80919   const char *zContext
80920 ){
80921   assert( pParse );
80922   pContext->pParse = pParse;
80923   pContext->zAuthContext = pParse->zAuthContext;
80924   pParse->zAuthContext = zContext;
80925 }
80926
80927 /*
80928 ** Pop an authorization context that was previously pushed
80929 ** by sqlite3AuthContextPush
80930 */
80931 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
80932   if( pContext->pParse ){
80933     pContext->pParse->zAuthContext = pContext->zAuthContext;
80934     pContext->pParse = 0;
80935   }
80936 }
80937
80938 #endif /* SQLITE_OMIT_AUTHORIZATION */
80939
80940 /************** End of auth.c ************************************************/
80941 /************** Begin file build.c *******************************************/
80942 /*
80943 ** 2001 September 15
80944 **
80945 ** The author disclaims copyright to this source code.  In place of
80946 ** a legal notice, here is a blessing:
80947 **
80948 **    May you do good and not evil.
80949 **    May you find forgiveness for yourself and forgive others.
80950 **    May you share freely, never taking more than you give.
80951 **
80952 *************************************************************************
80953 ** This file contains C code routines that are called by the SQLite parser
80954 ** when syntax rules are reduced.  The routines in this file handle the
80955 ** following kinds of SQL syntax:
80956 **
80957 **     CREATE TABLE
80958 **     DROP TABLE
80959 **     CREATE INDEX
80960 **     DROP INDEX
80961 **     creating ID lists
80962 **     BEGIN TRANSACTION
80963 **     COMMIT
80964 **     ROLLBACK
80965 */
80966
80967 /*
80968 ** This routine is called when a new SQL statement is beginning to
80969 ** be parsed.  Initialize the pParse structure as needed.
80970 */
80971 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
80972   pParse->explain = (u8)explainFlag;
80973   pParse->nVar = 0;
80974 }
80975
80976 #ifndef SQLITE_OMIT_SHARED_CACHE
80977 /*
80978 ** The TableLock structure is only used by the sqlite3TableLock() and
80979 ** codeTableLocks() functions.
80980 */
80981 struct TableLock {
80982   int iDb;             /* The database containing the table to be locked */
80983   int iTab;            /* The root page of the table to be locked */
80984   u8 isWriteLock;      /* True for write lock.  False for a read lock */
80985   const char *zName;   /* Name of the table */
80986 };
80987
80988 /*
80989 ** Record the fact that we want to lock a table at run-time.  
80990 **
80991 ** The table to be locked has root page iTab and is found in database iDb.
80992 ** A read or a write lock can be taken depending on isWritelock.
80993 **
80994 ** This routine just records the fact that the lock is desired.  The
80995 ** code to make the lock occur is generated by a later call to
80996 ** codeTableLocks() which occurs during sqlite3FinishCoding().
80997 */
80998 SQLITE_PRIVATE void sqlite3TableLock(
80999   Parse *pParse,     /* Parsing context */
81000   int iDb,           /* Index of the database containing the table to lock */
81001   int iTab,          /* Root page number of the table to be locked */
81002   u8 isWriteLock,    /* True for a write lock */
81003   const char *zName  /* Name of the table to be locked */
81004 ){
81005   Parse *pToplevel = sqlite3ParseToplevel(pParse);
81006   int i;
81007   int nBytes;
81008   TableLock *p;
81009   assert( iDb>=0 );
81010
81011   for(i=0; i<pToplevel->nTableLock; i++){
81012     p = &pToplevel->aTableLock[i];
81013     if( p->iDb==iDb && p->iTab==iTab ){
81014       p->isWriteLock = (p->isWriteLock || isWriteLock);
81015       return;
81016     }
81017   }
81018
81019   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
81020   pToplevel->aTableLock =
81021       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
81022   if( pToplevel->aTableLock ){
81023     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
81024     p->iDb = iDb;
81025     p->iTab = iTab;
81026     p->isWriteLock = isWriteLock;
81027     p->zName = zName;
81028   }else{
81029     pToplevel->nTableLock = 0;
81030     pToplevel->db->mallocFailed = 1;
81031   }
81032 }
81033
81034 /*
81035 ** Code an OP_TableLock instruction for each table locked by the
81036 ** statement (configured by calls to sqlite3TableLock()).
81037 */
81038 static void codeTableLocks(Parse *pParse){
81039   int i;
81040   Vdbe *pVdbe; 
81041
81042   pVdbe = sqlite3GetVdbe(pParse);
81043   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
81044
81045   for(i=0; i<pParse->nTableLock; i++){
81046     TableLock *p = &pParse->aTableLock[i];
81047     int p1 = p->iDb;
81048     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
81049                       p->zName, P4_STATIC);
81050   }
81051 }
81052 #else
81053   #define codeTableLocks(x)
81054 #endif
81055
81056 /*
81057 ** This routine is called after a single SQL statement has been
81058 ** parsed and a VDBE program to execute that statement has been
81059 ** prepared.  This routine puts the finishing touches on the
81060 ** VDBE program and resets the pParse structure for the next
81061 ** parse.
81062 **
81063 ** Note that if an error occurred, it might be the case that
81064 ** no VDBE code was generated.
81065 */
81066 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
81067   sqlite3 *db;
81068   Vdbe *v;
81069
81070   assert( pParse->pToplevel==0 );
81071   db = pParse->db;
81072   if( db->mallocFailed ) return;
81073   if( pParse->nested ) return;
81074   if( pParse->nErr ) return;
81075
81076   /* Begin by generating some termination code at the end of the
81077   ** vdbe program
81078   */
81079   v = sqlite3GetVdbe(pParse);
81080   assert( !pParse->isMultiWrite 
81081        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
81082   if( v ){
81083     sqlite3VdbeAddOp0(v, OP_Halt);
81084
81085     /* The cookie mask contains one bit for each database file open.
81086     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
81087     ** set for each database that is used.  Generate code to start a
81088     ** transaction on each used database and to verify the schema cookie
81089     ** on each used database.
81090     */
81091     if( pParse->cookieGoto>0 ){
81092       yDbMask mask;
81093       int iDb;
81094       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
81095       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
81096         if( (mask & pParse->cookieMask)==0 ) continue;
81097         sqlite3VdbeUsesBtree(v, iDb);
81098         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
81099         if( db->init.busy==0 ){
81100           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81101           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
81102                             iDb, pParse->cookieValue[iDb],
81103                             db->aDb[iDb].pSchema->iGeneration);
81104         }
81105       }
81106 #ifndef SQLITE_OMIT_VIRTUALTABLE
81107       {
81108         int i;
81109         for(i=0; i<pParse->nVtabLock; i++){
81110           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
81111           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
81112         }
81113         pParse->nVtabLock = 0;
81114       }
81115 #endif
81116
81117       /* Once all the cookies have been verified and transactions opened, 
81118       ** obtain the required table-locks. This is a no-op unless the 
81119       ** shared-cache feature is enabled.
81120       */
81121       codeTableLocks(pParse);
81122
81123       /* Initialize any AUTOINCREMENT data structures required.
81124       */
81125       sqlite3AutoincrementBegin(pParse);
81126
81127       /* Finally, jump back to the beginning of the executable code. */
81128       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
81129     }
81130   }
81131
81132
81133   /* Get the VDBE program ready for execution
81134   */
81135   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
81136 #ifdef SQLITE_DEBUG
81137     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
81138     sqlite3VdbeTrace(v, trace);
81139 #endif
81140     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
81141     /* A minimum of one cursor is required if autoincrement is used
81142     *  See ticket [a696379c1f08866] */
81143     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
81144     sqlite3VdbeMakeReady(v, pParse);
81145     pParse->rc = SQLITE_DONE;
81146     pParse->colNamesSet = 0;
81147   }else{
81148     pParse->rc = SQLITE_ERROR;
81149   }
81150   pParse->nTab = 0;
81151   pParse->nMem = 0;
81152   pParse->nSet = 0;
81153   pParse->nVar = 0;
81154   pParse->cookieMask = 0;
81155   pParse->cookieGoto = 0;
81156 }
81157
81158 /*
81159 ** Run the parser and code generator recursively in order to generate
81160 ** code for the SQL statement given onto the end of the pParse context
81161 ** currently under construction.  When the parser is run recursively
81162 ** this way, the final OP_Halt is not appended and other initialization
81163 ** and finalization steps are omitted because those are handling by the
81164 ** outermost parser.
81165 **
81166 ** Not everything is nestable.  This facility is designed to permit
81167 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
81168 ** care if you decide to try to use this routine for some other purposes.
81169 */
81170 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
81171   va_list ap;
81172   char *zSql;
81173   char *zErrMsg = 0;
81174   sqlite3 *db = pParse->db;
81175 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
81176   char saveBuf[SAVE_SZ];
81177
81178   if( pParse->nErr ) return;
81179   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
81180   va_start(ap, zFormat);
81181   zSql = sqlite3VMPrintf(db, zFormat, ap);
81182   va_end(ap);
81183   if( zSql==0 ){
81184     return;   /* A malloc must have failed */
81185   }
81186   pParse->nested++;
81187   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
81188   memset(&pParse->nVar, 0, SAVE_SZ);
81189   sqlite3RunParser(pParse, zSql, &zErrMsg);
81190   sqlite3DbFree(db, zErrMsg);
81191   sqlite3DbFree(db, zSql);
81192   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
81193   pParse->nested--;
81194 }
81195
81196 /*
81197 ** Locate the in-memory structure that describes a particular database
81198 ** table given the name of that table and (optionally) the name of the
81199 ** database containing the table.  Return NULL if not found.
81200 **
81201 ** If zDatabase is 0, all databases are searched for the table and the
81202 ** first matching table is returned.  (No checking for duplicate table
81203 ** names is done.)  The search order is TEMP first, then MAIN, then any
81204 ** auxiliary databases added using the ATTACH command.
81205 **
81206 ** See also sqlite3LocateTable().
81207 */
81208 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
81209   Table *p = 0;
81210   int i;
81211   int nName;
81212   assert( zName!=0 );
81213   nName = sqlite3Strlen30(zName);
81214   /* All mutexes are required for schema access.  Make sure we hold them. */
81215   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
81216   for(i=OMIT_TEMPDB; i<db->nDb; i++){
81217     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
81218     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
81219     assert( sqlite3SchemaMutexHeld(db, j, 0) );
81220     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
81221     if( p ) break;
81222   }
81223   return p;
81224 }
81225
81226 /*
81227 ** Locate the in-memory structure that describes a particular database
81228 ** table given the name of that table and (optionally) the name of the
81229 ** database containing the table.  Return NULL if not found.  Also leave an
81230 ** error message in pParse->zErrMsg.
81231 **
81232 ** The difference between this routine and sqlite3FindTable() is that this
81233 ** routine leaves an error message in pParse->zErrMsg where
81234 ** sqlite3FindTable() does not.
81235 */
81236 SQLITE_PRIVATE Table *sqlite3LocateTable(
81237   Parse *pParse,         /* context in which to report errors */
81238   int isView,            /* True if looking for a VIEW rather than a TABLE */
81239   const char *zName,     /* Name of the table we are looking for */
81240   const char *zDbase     /* Name of the database.  Might be NULL */
81241 ){
81242   Table *p;
81243
81244   /* Read the database schema. If an error occurs, leave an error message
81245   ** and code in pParse and return NULL. */
81246   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81247     return 0;
81248   }
81249
81250   p = sqlite3FindTable(pParse->db, zName, zDbase);
81251   if( p==0 ){
81252     const char *zMsg = isView ? "no such view" : "no such table";
81253     if( zDbase ){
81254       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
81255     }else{
81256       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
81257     }
81258     pParse->checkSchema = 1;
81259   }
81260   return p;
81261 }
81262
81263 /*
81264 ** Locate the table identified by *p.
81265 **
81266 ** This is a wrapper around sqlite3LocateTable(). The difference between
81267 ** sqlite3LocateTable() and this function is that this function restricts
81268 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
81269 ** non-NULL if it is part of a view or trigger program definition. See
81270 ** sqlite3FixSrcList() for details.
81271 */
81272 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
81273   Parse *pParse, 
81274   int isView, 
81275   struct SrcList_item *p
81276 ){
81277   const char *zDb;
81278   assert( p->pSchema==0 || p->zDatabase==0 );
81279   if( p->pSchema ){
81280     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
81281     zDb = pParse->db->aDb[iDb].zName;
81282   }else{
81283     zDb = p->zDatabase;
81284   }
81285   return sqlite3LocateTable(pParse, isView, p->zName, zDb);
81286 }
81287
81288 /*
81289 ** Locate the in-memory structure that describes 
81290 ** a particular index given the name of that index
81291 ** and the name of the database that contains the index.
81292 ** Return NULL if not found.
81293 **
81294 ** If zDatabase is 0, all databases are searched for the
81295 ** table and the first matching index is returned.  (No checking
81296 ** for duplicate index names is done.)  The search order is
81297 ** TEMP first, then MAIN, then any auxiliary databases added
81298 ** using the ATTACH command.
81299 */
81300 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
81301   Index *p = 0;
81302   int i;
81303   int nName = sqlite3Strlen30(zName);
81304   /* All mutexes are required for schema access.  Make sure we hold them. */
81305   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
81306   for(i=OMIT_TEMPDB; i<db->nDb; i++){
81307     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
81308     Schema *pSchema = db->aDb[j].pSchema;
81309     assert( pSchema );
81310     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
81311     assert( sqlite3SchemaMutexHeld(db, j, 0) );
81312     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
81313     if( p ) break;
81314   }
81315   return p;
81316 }
81317
81318 /*
81319 ** Reclaim the memory used by an index
81320 */
81321 static void freeIndex(sqlite3 *db, Index *p){
81322 #ifndef SQLITE_OMIT_ANALYZE
81323   sqlite3DeleteIndexSamples(db, p);
81324 #endif
81325   sqlite3DbFree(db, p->zColAff);
81326   sqlite3DbFree(db, p);
81327 }
81328
81329 /*
81330 ** For the index called zIdxName which is found in the database iDb,
81331 ** unlike that index from its Table then remove the index from
81332 ** the index hash table and free all memory structures associated
81333 ** with the index.
81334 */
81335 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
81336   Index *pIndex;
81337   int len;
81338   Hash *pHash;
81339
81340   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81341   pHash = &db->aDb[iDb].pSchema->idxHash;
81342   len = sqlite3Strlen30(zIdxName);
81343   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
81344   if( ALWAYS(pIndex) ){
81345     if( pIndex->pTable->pIndex==pIndex ){
81346       pIndex->pTable->pIndex = pIndex->pNext;
81347     }else{
81348       Index *p;
81349       /* Justification of ALWAYS();  The index must be on the list of
81350       ** indices. */
81351       p = pIndex->pTable->pIndex;
81352       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
81353       if( ALWAYS(p && p->pNext==pIndex) ){
81354         p->pNext = pIndex->pNext;
81355       }
81356     }
81357     freeIndex(db, pIndex);
81358   }
81359   db->flags |= SQLITE_InternChanges;
81360 }
81361
81362 /*
81363 ** Look through the list of open database files in db->aDb[] and if
81364 ** any have been closed, remove them from the list.  Reallocate the
81365 ** db->aDb[] structure to a smaller size, if possible.
81366 **
81367 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
81368 ** are never candidates for being collapsed.
81369 */
81370 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
81371   int i, j;
81372   for(i=j=2; i<db->nDb; i++){
81373     struct Db *pDb = &db->aDb[i];
81374     if( pDb->pBt==0 ){
81375       sqlite3DbFree(db, pDb->zName);
81376       pDb->zName = 0;
81377       continue;
81378     }
81379     if( j<i ){
81380       db->aDb[j] = db->aDb[i];
81381     }
81382     j++;
81383   }
81384   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
81385   db->nDb = j;
81386   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
81387     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
81388     sqlite3DbFree(db, db->aDb);
81389     db->aDb = db->aDbStatic;
81390   }
81391 }
81392
81393 /*
81394 ** Reset the schema for the database at index iDb.  Also reset the
81395 ** TEMP schema.
81396 */
81397 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
81398   Db *pDb;
81399   assert( iDb<db->nDb );
81400
81401   /* Case 1:  Reset the single schema identified by iDb */
81402   pDb = &db->aDb[iDb];
81403   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81404   assert( pDb->pSchema!=0 );
81405   sqlite3SchemaClear(pDb->pSchema);
81406
81407   /* If any database other than TEMP is reset, then also reset TEMP
81408   ** since TEMP might be holding triggers that reference tables in the
81409   ** other database.
81410   */
81411   if( iDb!=1 ){
81412     pDb = &db->aDb[1];
81413     assert( pDb->pSchema!=0 );
81414     sqlite3SchemaClear(pDb->pSchema);
81415   }
81416   return;
81417 }
81418
81419 /*
81420 ** Erase all schema information from all attached databases (including
81421 ** "main" and "temp") for a single database connection.
81422 */
81423 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
81424   int i;
81425   sqlite3BtreeEnterAll(db);
81426   for(i=0; i<db->nDb; i++){
81427     Db *pDb = &db->aDb[i];
81428     if( pDb->pSchema ){
81429       sqlite3SchemaClear(pDb->pSchema);
81430     }
81431   }
81432   db->flags &= ~SQLITE_InternChanges;
81433   sqlite3VtabUnlockList(db);
81434   sqlite3BtreeLeaveAll(db);
81435   sqlite3CollapseDatabaseArray(db);
81436 }
81437
81438 /*
81439 ** This routine is called when a commit occurs.
81440 */
81441 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
81442   db->flags &= ~SQLITE_InternChanges;
81443 }
81444
81445 /*
81446 ** Delete memory allocated for the column names of a table or view (the
81447 ** Table.aCol[] array).
81448 */
81449 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
81450   int i;
81451   Column *pCol;
81452   assert( pTable!=0 );
81453   if( (pCol = pTable->aCol)!=0 ){
81454     for(i=0; i<pTable->nCol; i++, pCol++){
81455       sqlite3DbFree(db, pCol->zName);
81456       sqlite3ExprDelete(db, pCol->pDflt);
81457       sqlite3DbFree(db, pCol->zDflt);
81458       sqlite3DbFree(db, pCol->zType);
81459       sqlite3DbFree(db, pCol->zColl);
81460     }
81461     sqlite3DbFree(db, pTable->aCol);
81462   }
81463 }
81464
81465 /*
81466 ** Remove the memory data structures associated with the given
81467 ** Table.  No changes are made to disk by this routine.
81468 **
81469 ** This routine just deletes the data structure.  It does not unlink
81470 ** the table data structure from the hash table.  But it does destroy
81471 ** memory structures of the indices and foreign keys associated with 
81472 ** the table.
81473 **
81474 ** The db parameter is optional.  It is needed if the Table object 
81475 ** contains lookaside memory.  (Table objects in the schema do not use
81476 ** lookaside memory, but some ephemeral Table objects do.)  Or the
81477 ** db parameter can be used with db->pnBytesFreed to measure the memory
81478 ** used by the Table object.
81479 */
81480 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
81481   Index *pIndex, *pNext;
81482   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
81483
81484   assert( !pTable || pTable->nRef>0 );
81485
81486   /* Do not delete the table until the reference count reaches zero. */
81487   if( !pTable ) return;
81488   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
81489
81490   /* Record the number of outstanding lookaside allocations in schema Tables
81491   ** prior to doing any free() operations.  Since schema Tables do not use
81492   ** lookaside, this number should not change. */
81493   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
81494                          db->lookaside.nOut : 0 );
81495
81496   /* Delete all indices associated with this table. */
81497   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
81498     pNext = pIndex->pNext;
81499     assert( pIndex->pSchema==pTable->pSchema );
81500     if( !db || db->pnBytesFreed==0 ){
81501       char *zName = pIndex->zName; 
81502       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
81503          &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
81504       );
81505       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
81506       assert( pOld==pIndex || pOld==0 );
81507     }
81508     freeIndex(db, pIndex);
81509   }
81510
81511   /* Delete any foreign keys attached to this table. */
81512   sqlite3FkDelete(db, pTable);
81513
81514   /* Delete the Table structure itself.
81515   */
81516   sqliteDeleteColumnNames(db, pTable);
81517   sqlite3DbFree(db, pTable->zName);
81518   sqlite3DbFree(db, pTable->zColAff);
81519   sqlite3SelectDelete(db, pTable->pSelect);
81520 #ifndef SQLITE_OMIT_CHECK
81521   sqlite3ExprListDelete(db, pTable->pCheck);
81522 #endif
81523 #ifndef SQLITE_OMIT_VIRTUALTABLE
81524   sqlite3VtabClear(db, pTable);
81525 #endif
81526   sqlite3DbFree(db, pTable);
81527
81528   /* Verify that no lookaside memory was used by schema tables */
81529   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
81530 }
81531
81532 /*
81533 ** Unlink the given table from the hash tables and the delete the
81534 ** table structure with all its indices and foreign keys.
81535 */
81536 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
81537   Table *p;
81538   Db *pDb;
81539
81540   assert( db!=0 );
81541   assert( iDb>=0 && iDb<db->nDb );
81542   assert( zTabName );
81543   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81544   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
81545   pDb = &db->aDb[iDb];
81546   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
81547                         sqlite3Strlen30(zTabName),0);
81548   sqlite3DeleteTable(db, p);
81549   db->flags |= SQLITE_InternChanges;
81550 }
81551
81552 /*
81553 ** Given a token, return a string that consists of the text of that
81554 ** token.  Space to hold the returned string
81555 ** is obtained from sqliteMalloc() and must be freed by the calling
81556 ** function.
81557 **
81558 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
81559 ** surround the body of the token are removed.
81560 **
81561 ** Tokens are often just pointers into the original SQL text and so
81562 ** are not \000 terminated and are not persistent.  The returned string
81563 ** is \000 terminated and is persistent.
81564 */
81565 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
81566   char *zName;
81567   if( pName ){
81568     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
81569     sqlite3Dequote(zName);
81570   }else{
81571     zName = 0;
81572   }
81573   return zName;
81574 }
81575
81576 /*
81577 ** Open the sqlite_master table stored in database number iDb for
81578 ** writing. The table is opened using cursor 0.
81579 */
81580 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
81581   Vdbe *v = sqlite3GetVdbe(p);
81582   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
81583   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
81584   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
81585   if( p->nTab==0 ){
81586     p->nTab = 1;
81587   }
81588 }
81589
81590 /*
81591 ** Parameter zName points to a nul-terminated buffer containing the name
81592 ** of a database ("main", "temp" or the name of an attached db). This
81593 ** function returns the index of the named database in db->aDb[], or
81594 ** -1 if the named db cannot be found.
81595 */
81596 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
81597   int i = -1;         /* Database number */
81598   if( zName ){
81599     Db *pDb;
81600     int n = sqlite3Strlen30(zName);
81601     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
81602       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
81603           0==sqlite3StrICmp(pDb->zName, zName) ){
81604         break;
81605       }
81606     }
81607   }
81608   return i;
81609 }
81610
81611 /*
81612 ** The token *pName contains the name of a database (either "main" or
81613 ** "temp" or the name of an attached db). This routine returns the
81614 ** index of the named database in db->aDb[], or -1 if the named db 
81615 ** does not exist.
81616 */
81617 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
81618   int i;                               /* Database number */
81619   char *zName;                         /* Name we are searching for */
81620   zName = sqlite3NameFromToken(db, pName);
81621   i = sqlite3FindDbName(db, zName);
81622   sqlite3DbFree(db, zName);
81623   return i;
81624 }
81625
81626 /* The table or view or trigger name is passed to this routine via tokens
81627 ** pName1 and pName2. If the table name was fully qualified, for example:
81628 **
81629 ** CREATE TABLE xxx.yyy (...);
81630 ** 
81631 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81632 ** the table name is not fully qualified, i.e.:
81633 **
81634 ** CREATE TABLE yyy(...);
81635 **
81636 ** Then pName1 is set to "yyy" and pName2 is "".
81637 **
81638 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
81639 ** pName2) that stores the unqualified table name.  The index of the
81640 ** database "xxx" is returned.
81641 */
81642 SQLITE_PRIVATE int sqlite3TwoPartName(
81643   Parse *pParse,      /* Parsing and code generating context */
81644   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
81645   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
81646   Token **pUnqual     /* Write the unqualified object name here */
81647 ){
81648   int iDb;                    /* Database holding the object */
81649   sqlite3 *db = pParse->db;
81650
81651   if( ALWAYS(pName2!=0) && pName2->n>0 ){
81652     if( db->init.busy ) {
81653       sqlite3ErrorMsg(pParse, "corrupt database");
81654       pParse->nErr++;
81655       return -1;
81656     }
81657     *pUnqual = pName2;
81658     iDb = sqlite3FindDb(db, pName1);
81659     if( iDb<0 ){
81660       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
81661       pParse->nErr++;
81662       return -1;
81663     }
81664   }else{
81665     assert( db->init.iDb==0 || db->init.busy );
81666     iDb = db->init.iDb;
81667     *pUnqual = pName1;
81668   }
81669   return iDb;
81670 }
81671
81672 /*
81673 ** This routine is used to check if the UTF-8 string zName is a legal
81674 ** unqualified name for a new schema object (table, index, view or
81675 ** trigger). All names are legal except those that begin with the string
81676 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
81677 ** is reserved for internal use.
81678 */
81679 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
81680   if( !pParse->db->init.busy && pParse->nested==0 
81681           && (pParse->db->flags & SQLITE_WriteSchema)==0
81682           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
81683     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
81684     return SQLITE_ERROR;
81685   }
81686   return SQLITE_OK;
81687 }
81688
81689 /*
81690 ** Begin constructing a new table representation in memory.  This is
81691 ** the first of several action routines that get called in response
81692 ** to a CREATE TABLE statement.  In particular, this routine is called
81693 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
81694 ** flag is true if the table should be stored in the auxiliary database
81695 ** file instead of in the main database file.  This is normally the case
81696 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
81697 ** CREATE and TABLE.
81698 **
81699 ** The new table record is initialized and put in pParse->pNewTable.
81700 ** As more of the CREATE TABLE statement is parsed, additional action
81701 ** routines will be called to add more information to this record.
81702 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
81703 ** is called to complete the construction of the new table record.
81704 */
81705 SQLITE_PRIVATE void sqlite3StartTable(
81706   Parse *pParse,   /* Parser context */
81707   Token *pName1,   /* First part of the name of the table or view */
81708   Token *pName2,   /* Second part of the name of the table or view */
81709   int isTemp,      /* True if this is a TEMP table */
81710   int isView,      /* True if this is a VIEW */
81711   int isVirtual,   /* True if this is a VIRTUAL table */
81712   int noErr        /* Do nothing if table already exists */
81713 ){
81714   Table *pTable;
81715   char *zName = 0; /* The name of the new table */
81716   sqlite3 *db = pParse->db;
81717   Vdbe *v;
81718   int iDb;         /* Database number to create the table in */
81719   Token *pName;    /* Unqualified name of the table to create */
81720
81721   /* The table or view name to create is passed to this routine via tokens
81722   ** pName1 and pName2. If the table name was fully qualified, for example:
81723   **
81724   ** CREATE TABLE xxx.yyy (...);
81725   ** 
81726   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81727   ** the table name is not fully qualified, i.e.:
81728   **
81729   ** CREATE TABLE yyy(...);
81730   **
81731   ** Then pName1 is set to "yyy" and pName2 is "".
81732   **
81733   ** The call below sets the pName pointer to point at the token (pName1 or
81734   ** pName2) that stores the unqualified table name. The variable iDb is
81735   ** set to the index of the database that the table or view is to be
81736   ** created in.
81737   */
81738   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
81739   if( iDb<0 ) return;
81740   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
81741     /* If creating a temp table, the name may not be qualified. Unless 
81742     ** the database name is "temp" anyway.  */
81743     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
81744     return;
81745   }
81746   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
81747
81748   pParse->sNameToken = *pName;
81749   zName = sqlite3NameFromToken(db, pName);
81750   if( zName==0 ) return;
81751   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
81752     goto begin_table_error;
81753   }
81754   if( db->init.iDb==1 ) isTemp = 1;
81755 #ifndef SQLITE_OMIT_AUTHORIZATION
81756   assert( (isTemp & 1)==isTemp );
81757   {
81758     int code;
81759     char *zDb = db->aDb[iDb].zName;
81760     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
81761       goto begin_table_error;
81762     }
81763     if( isView ){
81764       if( !OMIT_TEMPDB && isTemp ){
81765         code = SQLITE_CREATE_TEMP_VIEW;
81766       }else{
81767         code = SQLITE_CREATE_VIEW;
81768       }
81769     }else{
81770       if( !OMIT_TEMPDB && isTemp ){
81771         code = SQLITE_CREATE_TEMP_TABLE;
81772       }else{
81773         code = SQLITE_CREATE_TABLE;
81774       }
81775     }
81776     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
81777       goto begin_table_error;
81778     }
81779   }
81780 #endif
81781
81782   /* Make sure the new table name does not collide with an existing
81783   ** index or table name in the same database.  Issue an error message if
81784   ** it does. The exception is if the statement being parsed was passed
81785   ** to an sqlite3_declare_vtab() call. In that case only the column names
81786   ** and types will be used, so there is no need to test for namespace
81787   ** collisions.
81788   */
81789   if( !IN_DECLARE_VTAB ){
81790     char *zDb = db->aDb[iDb].zName;
81791     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81792       goto begin_table_error;
81793     }
81794     pTable = sqlite3FindTable(db, zName, zDb);
81795     if( pTable ){
81796       if( !noErr ){
81797         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
81798       }else{
81799         assert( !db->init.busy );
81800         sqlite3CodeVerifySchema(pParse, iDb);
81801       }
81802       goto begin_table_error;
81803     }
81804     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
81805       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
81806       goto begin_table_error;
81807     }
81808   }
81809
81810   pTable = sqlite3DbMallocZero(db, sizeof(Table));
81811   if( pTable==0 ){
81812     db->mallocFailed = 1;
81813     pParse->rc = SQLITE_NOMEM;
81814     pParse->nErr++;
81815     goto begin_table_error;
81816   }
81817   pTable->zName = zName;
81818   pTable->iPKey = -1;
81819   pTable->pSchema = db->aDb[iDb].pSchema;
81820   pTable->nRef = 1;
81821   pTable->nRowEst = 1000000;
81822   assert( pParse->pNewTable==0 );
81823   pParse->pNewTable = pTable;
81824
81825   /* If this is the magic sqlite_sequence table used by autoincrement,
81826   ** then record a pointer to this table in the main database structure
81827   ** so that INSERT can find the table easily.
81828   */
81829 #ifndef SQLITE_OMIT_AUTOINCREMENT
81830   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
81831     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81832     pTable->pSchema->pSeqTab = pTable;
81833   }
81834 #endif
81835
81836   /* Begin generating the code that will insert the table record into
81837   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
81838   ** and allocate the record number for the table entry now.  Before any
81839   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
81840   ** indices to be created and the table record must come before the 
81841   ** indices.  Hence, the record number for the table must be allocated
81842   ** now.
81843   */
81844   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
81845     int j1;
81846     int fileFormat;
81847     int reg1, reg2, reg3;
81848     sqlite3BeginWriteOperation(pParse, 0, iDb);
81849
81850 #ifndef SQLITE_OMIT_VIRTUALTABLE
81851     if( isVirtual ){
81852       sqlite3VdbeAddOp0(v, OP_VBegin);
81853     }
81854 #endif
81855
81856     /* If the file format and encoding in the database have not been set, 
81857     ** set them now.
81858     */
81859     reg1 = pParse->regRowid = ++pParse->nMem;
81860     reg2 = pParse->regRoot = ++pParse->nMem;
81861     reg3 = ++pParse->nMem;
81862     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
81863     sqlite3VdbeUsesBtree(v, iDb);
81864     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
81865     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
81866                   1 : SQLITE_MAX_FILE_FORMAT;
81867     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
81868     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
81869     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
81870     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
81871     sqlite3VdbeJumpHere(v, j1);
81872
81873     /* This just creates a place-holder record in the sqlite_master table.
81874     ** The record created does not contain anything yet.  It will be replaced
81875     ** by the real entry in code generated at sqlite3EndTable().
81876     **
81877     ** The rowid for the new entry is left in register pParse->regRowid.
81878     ** The root page number of the new table is left in reg pParse->regRoot.
81879     ** The rowid and root page number values are needed by the code that
81880     ** sqlite3EndTable will generate.
81881     */
81882 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
81883     if( isView || isVirtual ){
81884       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
81885     }else
81886 #endif
81887     {
81888       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
81889     }
81890     sqlite3OpenMasterTable(pParse, iDb);
81891     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
81892     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
81893     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
81894     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
81895     sqlite3VdbeAddOp0(v, OP_Close);
81896   }
81897
81898   /* Normal (non-error) return. */
81899   return;
81900
81901   /* If an error occurs, we jump here */
81902 begin_table_error:
81903   sqlite3DbFree(db, zName);
81904   return;
81905 }
81906
81907 /*
81908 ** This macro is used to compare two strings in a case-insensitive manner.
81909 ** It is slightly faster than calling sqlite3StrICmp() directly, but
81910 ** produces larger code.
81911 **
81912 ** WARNING: This macro is not compatible with the strcmp() family. It
81913 ** returns true if the two strings are equal, otherwise false.
81914 */
81915 #define STRICMP(x, y) (\
81916 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
81917 sqlite3UpperToLower[*(unsigned char *)(y)]     \
81918 && sqlite3StrICmp((x)+1,(y)+1)==0 )
81919
81920 /*
81921 ** Add a new column to the table currently being constructed.
81922 **
81923 ** The parser calls this routine once for each column declaration
81924 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
81925 ** first to get things going.  Then this routine is called for each
81926 ** column.
81927 */
81928 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
81929   Table *p;
81930   int i;
81931   char *z;
81932   Column *pCol;
81933   sqlite3 *db = pParse->db;
81934   if( (p = pParse->pNewTable)==0 ) return;
81935 #if SQLITE_MAX_COLUMN
81936   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
81937     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
81938     return;
81939   }
81940 #endif
81941   z = sqlite3NameFromToken(db, pName);
81942   if( z==0 ) return;
81943   for(i=0; i<p->nCol; i++){
81944     if( STRICMP(z, p->aCol[i].zName) ){
81945       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
81946       sqlite3DbFree(db, z);
81947       return;
81948     }
81949   }
81950   if( (p->nCol & 0x7)==0 ){
81951     Column *aNew;
81952     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
81953     if( aNew==0 ){
81954       sqlite3DbFree(db, z);
81955       return;
81956     }
81957     p->aCol = aNew;
81958   }
81959   pCol = &p->aCol[p->nCol];
81960   memset(pCol, 0, sizeof(p->aCol[0]));
81961   pCol->zName = z;
81962  
81963   /* If there is no type specified, columns have the default affinity
81964   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
81965   ** be called next to set pCol->affinity correctly.
81966   */
81967   pCol->affinity = SQLITE_AFF_NONE;
81968   p->nCol++;
81969 }
81970
81971 /*
81972 ** This routine is called by the parser while in the middle of
81973 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
81974 ** been seen on a column.  This routine sets the notNull flag on
81975 ** the column currently under construction.
81976 */
81977 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
81978   Table *p;
81979   p = pParse->pNewTable;
81980   if( p==0 || NEVER(p->nCol<1) ) return;
81981   p->aCol[p->nCol-1].notNull = (u8)onError;
81982 }
81983
81984 /*
81985 ** Scan the column type name zType (length nType) and return the
81986 ** associated affinity type.
81987 **
81988 ** This routine does a case-independent search of zType for the 
81989 ** substrings in the following table. If one of the substrings is
81990 ** found, the corresponding affinity is returned. If zType contains
81991 ** more than one of the substrings, entries toward the top of 
81992 ** the table take priority. For example, if zType is 'BLOBINT', 
81993 ** SQLITE_AFF_INTEGER is returned.
81994 **
81995 ** Substring     | Affinity
81996 ** --------------------------------
81997 ** 'INT'         | SQLITE_AFF_INTEGER
81998 ** 'CHAR'        | SQLITE_AFF_TEXT
81999 ** 'CLOB'        | SQLITE_AFF_TEXT
82000 ** 'TEXT'        | SQLITE_AFF_TEXT
82001 ** 'BLOB'        | SQLITE_AFF_NONE
82002 ** 'REAL'        | SQLITE_AFF_REAL
82003 ** 'FLOA'        | SQLITE_AFF_REAL
82004 ** 'DOUB'        | SQLITE_AFF_REAL
82005 **
82006 ** If none of the substrings in the above table are found,
82007 ** SQLITE_AFF_NUMERIC is returned.
82008 */
82009 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
82010   u32 h = 0;
82011   char aff = SQLITE_AFF_NUMERIC;
82012
82013   if( zIn ) while( zIn[0] ){
82014     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
82015     zIn++;
82016     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
82017       aff = SQLITE_AFF_TEXT; 
82018     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
82019       aff = SQLITE_AFF_TEXT;
82020     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
82021       aff = SQLITE_AFF_TEXT;
82022     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
82023         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
82024       aff = SQLITE_AFF_NONE;
82025 #ifndef SQLITE_OMIT_FLOATING_POINT
82026     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
82027         && aff==SQLITE_AFF_NUMERIC ){
82028       aff = SQLITE_AFF_REAL;
82029     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
82030         && aff==SQLITE_AFF_NUMERIC ){
82031       aff = SQLITE_AFF_REAL;
82032     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
82033         && aff==SQLITE_AFF_NUMERIC ){
82034       aff = SQLITE_AFF_REAL;
82035 #endif
82036     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
82037       aff = SQLITE_AFF_INTEGER;
82038       break;
82039     }
82040   }
82041
82042   return aff;
82043 }
82044
82045 /*
82046 ** This routine is called by the parser while in the middle of
82047 ** parsing a CREATE TABLE statement.  The pFirst token is the first
82048 ** token in the sequence of tokens that describe the type of the
82049 ** column currently under construction.   pLast is the last token
82050 ** in the sequence.  Use this information to construct a string
82051 ** that contains the typename of the column and store that string
82052 ** in zType.
82053 */ 
82054 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
82055   Table *p;
82056   Column *pCol;
82057
82058   p = pParse->pNewTable;
82059   if( p==0 || NEVER(p->nCol<1) ) return;
82060   pCol = &p->aCol[p->nCol-1];
82061   assert( pCol->zType==0 );
82062   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
82063   pCol->affinity = sqlite3AffinityType(pCol->zType);
82064 }
82065
82066 /*
82067 ** The expression is the default value for the most recently added column
82068 ** of the table currently under construction.
82069 **
82070 ** Default value expressions must be constant.  Raise an exception if this
82071 ** is not the case.
82072 **
82073 ** This routine is called by the parser while in the middle of
82074 ** parsing a CREATE TABLE statement.
82075 */
82076 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
82077   Table *p;
82078   Column *pCol;
82079   sqlite3 *db = pParse->db;
82080   p = pParse->pNewTable;
82081   if( p!=0 ){
82082     pCol = &(p->aCol[p->nCol-1]);
82083     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
82084       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
82085           pCol->zName);
82086     }else{
82087       /* A copy of pExpr is used instead of the original, as pExpr contains
82088       ** tokens that point to volatile memory. The 'span' of the expression
82089       ** is required by pragma table_info.
82090       */
82091       sqlite3ExprDelete(db, pCol->pDflt);
82092       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
82093       sqlite3DbFree(db, pCol->zDflt);
82094       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
82095                                      (int)(pSpan->zEnd - pSpan->zStart));
82096     }
82097   }
82098   sqlite3ExprDelete(db, pSpan->pExpr);
82099 }
82100
82101 /*
82102 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
82103 ** of columns that form the primary key.  If pList is NULL, then the
82104 ** most recently added column of the table is the primary key.
82105 **
82106 ** A table can have at most one primary key.  If the table already has
82107 ** a primary key (and this is the second primary key) then create an
82108 ** error.
82109 **
82110 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
82111 ** then we will try to use that column as the rowid.  Set the Table.iPKey
82112 ** field of the table under construction to be the index of the
82113 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
82114 ** no INTEGER PRIMARY KEY.
82115 **
82116 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
82117 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
82118 */
82119 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
82120   Parse *pParse,    /* Parsing context */
82121   ExprList *pList,  /* List of field names to be indexed */
82122   int onError,      /* What to do with a uniqueness conflict */
82123   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
82124   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
82125 ){
82126   Table *pTab = pParse->pNewTable;
82127   char *zType = 0;
82128   int iCol = -1, i;
82129   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
82130   if( pTab->tabFlags & TF_HasPrimaryKey ){
82131     sqlite3ErrorMsg(pParse, 
82132       "table \"%s\" has more than one primary key", pTab->zName);
82133     goto primary_key_exit;
82134   }
82135   pTab->tabFlags |= TF_HasPrimaryKey;
82136   if( pList==0 ){
82137     iCol = pTab->nCol - 1;
82138     pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
82139   }else{
82140     for(i=0; i<pList->nExpr; i++){
82141       for(iCol=0; iCol<pTab->nCol; iCol++){
82142         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
82143           break;
82144         }
82145       }
82146       if( iCol<pTab->nCol ){
82147         pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
82148       }
82149     }
82150     if( pList->nExpr>1 ) iCol = -1;
82151   }
82152   if( iCol>=0 && iCol<pTab->nCol ){
82153     zType = pTab->aCol[iCol].zType;
82154   }
82155   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
82156         && sortOrder==SQLITE_SO_ASC ){
82157     pTab->iPKey = iCol;
82158     pTab->keyConf = (u8)onError;
82159     assert( autoInc==0 || autoInc==1 );
82160     pTab->tabFlags |= autoInc*TF_Autoincrement;
82161   }else if( autoInc ){
82162 #ifndef SQLITE_OMIT_AUTOINCREMENT
82163     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
82164        "INTEGER PRIMARY KEY");
82165 #endif
82166   }else{
82167     Index *p;
82168     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
82169     if( p ){
82170       p->autoIndex = 2;
82171     }
82172     pList = 0;
82173   }
82174
82175 primary_key_exit:
82176   sqlite3ExprListDelete(pParse->db, pList);
82177   return;
82178 }
82179
82180 /*
82181 ** Add a new CHECK constraint to the table currently under construction.
82182 */
82183 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
82184   Parse *pParse,    /* Parsing context */
82185   Expr *pCheckExpr  /* The check expression */
82186 ){
82187 #ifndef SQLITE_OMIT_CHECK
82188   Table *pTab = pParse->pNewTable;
82189   if( pTab && !IN_DECLARE_VTAB ){
82190     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
82191     if( pParse->constraintName.n ){
82192       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
82193     }
82194   }else
82195 #endif
82196   {
82197     sqlite3ExprDelete(pParse->db, pCheckExpr);
82198   }
82199 }
82200
82201 /*
82202 ** Set the collation function of the most recently parsed table column
82203 ** to the CollSeq given.
82204 */
82205 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
82206   Table *p;
82207   int i;
82208   char *zColl;              /* Dequoted name of collation sequence */
82209   sqlite3 *db;
82210
82211   if( (p = pParse->pNewTable)==0 ) return;
82212   i = p->nCol-1;
82213   db = pParse->db;
82214   zColl = sqlite3NameFromToken(db, pToken);
82215   if( !zColl ) return;
82216
82217   if( sqlite3LocateCollSeq(pParse, zColl) ){
82218     Index *pIdx;
82219     p->aCol[i].zColl = zColl;
82220   
82221     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
82222     ** then an index may have been created on this column before the
82223     ** collation type was added. Correct this if it is the case.
82224     */
82225     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
82226       assert( pIdx->nColumn==1 );
82227       if( pIdx->aiColumn[0]==i ){
82228         pIdx->azColl[0] = p->aCol[i].zColl;
82229       }
82230     }
82231   }else{
82232     sqlite3DbFree(db, zColl);
82233   }
82234 }
82235
82236 /*
82237 ** This function returns the collation sequence for database native text
82238 ** encoding identified by the string zName, length nName.
82239 **
82240 ** If the requested collation sequence is not available, or not available
82241 ** in the database native encoding, the collation factory is invoked to
82242 ** request it. If the collation factory does not supply such a sequence,
82243 ** and the sequence is available in another text encoding, then that is
82244 ** returned instead.
82245 **
82246 ** If no versions of the requested collations sequence are available, or
82247 ** another error occurs, NULL is returned and an error message written into
82248 ** pParse.
82249 **
82250 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
82251 ** invokes the collation factory if the named collation cannot be found
82252 ** and generates an error message.
82253 **
82254 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
82255 */
82256 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
82257   sqlite3 *db = pParse->db;
82258   u8 enc = ENC(db);
82259   u8 initbusy = db->init.busy;
82260   CollSeq *pColl;
82261
82262   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
82263   if( !initbusy && (!pColl || !pColl->xCmp) ){
82264     pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
82265   }
82266
82267   return pColl;
82268 }
82269
82270
82271 /*
82272 ** Generate code that will increment the schema cookie.
82273 **
82274 ** The schema cookie is used to determine when the schema for the
82275 ** database changes.  After each schema change, the cookie value
82276 ** changes.  When a process first reads the schema it records the
82277 ** cookie.  Thereafter, whenever it goes to access the database,
82278 ** it checks the cookie to make sure the schema has not changed
82279 ** since it was last read.
82280 **
82281 ** This plan is not completely bullet-proof.  It is possible for
82282 ** the schema to change multiple times and for the cookie to be
82283 ** set back to prior value.  But schema changes are infrequent
82284 ** and the probability of hitting the same cookie value is only
82285 ** 1 chance in 2^32.  So we're safe enough.
82286 */
82287 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
82288   int r1 = sqlite3GetTempReg(pParse);
82289   sqlite3 *db = pParse->db;
82290   Vdbe *v = pParse->pVdbe;
82291   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82292   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
82293   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
82294   sqlite3ReleaseTempReg(pParse, r1);
82295 }
82296
82297 /*
82298 ** Measure the number of characters needed to output the given
82299 ** identifier.  The number returned includes any quotes used
82300 ** but does not include the null terminator.
82301 **
82302 ** The estimate is conservative.  It might be larger that what is
82303 ** really needed.
82304 */
82305 static int identLength(const char *z){
82306   int n;
82307   for(n=0; *z; n++, z++){
82308     if( *z=='"' ){ n++; }
82309   }
82310   return n + 2;
82311 }
82312
82313 /*
82314 ** The first parameter is a pointer to an output buffer. The second 
82315 ** parameter is a pointer to an integer that contains the offset at
82316 ** which to write into the output buffer. This function copies the
82317 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
82318 ** to the specified offset in the buffer and updates *pIdx to refer
82319 ** to the first byte after the last byte written before returning.
82320 ** 
82321 ** If the string zSignedIdent consists entirely of alpha-numeric
82322 ** characters, does not begin with a digit and is not an SQL keyword,
82323 ** then it is copied to the output buffer exactly as it is. Otherwise,
82324 ** it is quoted using double-quotes.
82325 */
82326 static void identPut(char *z, int *pIdx, char *zSignedIdent){
82327   unsigned char *zIdent = (unsigned char*)zSignedIdent;
82328   int i, j, needQuote;
82329   i = *pIdx;
82330
82331   for(j=0; zIdent[j]; j++){
82332     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
82333   }
82334   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
82335   if( !needQuote ){
82336     needQuote = zIdent[j];
82337   }
82338
82339   if( needQuote ) z[i++] = '"';
82340   for(j=0; zIdent[j]; j++){
82341     z[i++] = zIdent[j];
82342     if( zIdent[j]=='"' ) z[i++] = '"';
82343   }
82344   if( needQuote ) z[i++] = '"';
82345   z[i] = 0;
82346   *pIdx = i;
82347 }
82348
82349 /*
82350 ** Generate a CREATE TABLE statement appropriate for the given
82351 ** table.  Memory to hold the text of the statement is obtained
82352 ** from sqliteMalloc() and must be freed by the calling function.
82353 */
82354 static char *createTableStmt(sqlite3 *db, Table *p){
82355   int i, k, n;
82356   char *zStmt;
82357   char *zSep, *zSep2, *zEnd;
82358   Column *pCol;
82359   n = 0;
82360   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
82361     n += identLength(pCol->zName) + 5;
82362   }
82363   n += identLength(p->zName);
82364   if( n<50 ){ 
82365     zSep = "";
82366     zSep2 = ",";
82367     zEnd = ")";
82368   }else{
82369     zSep = "\n  ";
82370     zSep2 = ",\n  ";
82371     zEnd = "\n)";
82372   }
82373   n += 35 + 6*p->nCol;
82374   zStmt = sqlite3DbMallocRaw(0, n);
82375   if( zStmt==0 ){
82376     db->mallocFailed = 1;
82377     return 0;
82378   }
82379   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
82380   k = sqlite3Strlen30(zStmt);
82381   identPut(zStmt, &k, p->zName);
82382   zStmt[k++] = '(';
82383   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
82384     static const char * const azType[] = {
82385         /* SQLITE_AFF_TEXT    */ " TEXT",
82386         /* SQLITE_AFF_NONE    */ "",
82387         /* SQLITE_AFF_NUMERIC */ " NUM",
82388         /* SQLITE_AFF_INTEGER */ " INT",
82389         /* SQLITE_AFF_REAL    */ " REAL"
82390     };
82391     int len;
82392     const char *zType;
82393
82394     sqlite3_snprintf(n-k, &zStmt[k], zSep);
82395     k += sqlite3Strlen30(&zStmt[k]);
82396     zSep = zSep2;
82397     identPut(zStmt, &k, pCol->zName);
82398     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
82399     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
82400     testcase( pCol->affinity==SQLITE_AFF_TEXT );
82401     testcase( pCol->affinity==SQLITE_AFF_NONE );
82402     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
82403     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
82404     testcase( pCol->affinity==SQLITE_AFF_REAL );
82405     
82406     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
82407     len = sqlite3Strlen30(zType);
82408     assert( pCol->affinity==SQLITE_AFF_NONE 
82409             || pCol->affinity==sqlite3AffinityType(zType) );
82410     memcpy(&zStmt[k], zType, len);
82411     k += len;
82412     assert( k<=n );
82413   }
82414   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
82415   return zStmt;
82416 }
82417
82418 /*
82419 ** This routine is called to report the final ")" that terminates
82420 ** a CREATE TABLE statement.
82421 **
82422 ** The table structure that other action routines have been building
82423 ** is added to the internal hash tables, assuming no errors have
82424 ** occurred.
82425 **
82426 ** An entry for the table is made in the master table on disk, unless
82427 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
82428 ** it means we are reading the sqlite_master table because we just
82429 ** connected to the database or because the sqlite_master table has
82430 ** recently changed, so the entry for this table already exists in
82431 ** the sqlite_master table.  We do not want to create it again.
82432 **
82433 ** If the pSelect argument is not NULL, it means that this routine
82434 ** was called to create a table generated from a 
82435 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
82436 ** the new table will match the result set of the SELECT.
82437 */
82438 SQLITE_PRIVATE void sqlite3EndTable(
82439   Parse *pParse,          /* Parse context */
82440   Token *pCons,           /* The ',' token after the last column defn. */
82441   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
82442   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
82443 ){
82444   Table *p;
82445   sqlite3 *db = pParse->db;
82446   int iDb;
82447
82448   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
82449     return;
82450   }
82451   p = pParse->pNewTable;
82452   if( p==0 ) return;
82453
82454   assert( !db->init.busy || !pSelect );
82455
82456   iDb = sqlite3SchemaToIndex(db, p->pSchema);
82457
82458 #ifndef SQLITE_OMIT_CHECK
82459   /* Resolve names in all CHECK constraint expressions.
82460   */
82461   if( p->pCheck ){
82462     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
82463     NameContext sNC;                /* Name context for pParse->pNewTable */
82464     ExprList *pList;                /* List of all CHECK constraints */
82465     int i;                          /* Loop counter */
82466
82467     memset(&sNC, 0, sizeof(sNC));
82468     memset(&sSrc, 0, sizeof(sSrc));
82469     sSrc.nSrc = 1;
82470     sSrc.a[0].zName = p->zName;
82471     sSrc.a[0].pTab = p;
82472     sSrc.a[0].iCursor = -1;
82473     sNC.pParse = pParse;
82474     sNC.pSrcList = &sSrc;
82475     sNC.ncFlags = NC_IsCheck;
82476     pList = p->pCheck;
82477     for(i=0; i<pList->nExpr; i++){
82478       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
82479         return;
82480       }
82481     }
82482   }
82483 #endif /* !defined(SQLITE_OMIT_CHECK) */
82484
82485   /* If the db->init.busy is 1 it means we are reading the SQL off the
82486   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
82487   ** So do not write to the disk again.  Extract the root page number
82488   ** for the table from the db->init.newTnum field.  (The page number
82489   ** should have been put there by the sqliteOpenCb routine.)
82490   */
82491   if( db->init.busy ){
82492     p->tnum = db->init.newTnum;
82493   }
82494
82495   /* If not initializing, then create a record for the new table
82496   ** in the SQLITE_MASTER table of the database.
82497   **
82498   ** If this is a TEMPORARY table, write the entry into the auxiliary
82499   ** file instead of into the main database file.
82500   */
82501   if( !db->init.busy ){
82502     int n;
82503     Vdbe *v;
82504     char *zType;    /* "view" or "table" */
82505     char *zType2;   /* "VIEW" or "TABLE" */
82506     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
82507
82508     v = sqlite3GetVdbe(pParse);
82509     if( NEVER(v==0) ) return;
82510
82511     sqlite3VdbeAddOp1(v, OP_Close, 0);
82512
82513     /* 
82514     ** Initialize zType for the new view or table.
82515     */
82516     if( p->pSelect==0 ){
82517       /* A regular table */
82518       zType = "table";
82519       zType2 = "TABLE";
82520 #ifndef SQLITE_OMIT_VIEW
82521     }else{
82522       /* A view */
82523       zType = "view";
82524       zType2 = "VIEW";
82525 #endif
82526     }
82527
82528     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
82529     ** statement to populate the new table. The root-page number for the
82530     ** new table is in register pParse->regRoot.
82531     **
82532     ** Once the SELECT has been coded by sqlite3Select(), it is in a
82533     ** suitable state to query for the column names and types to be used
82534     ** by the new table.
82535     **
82536     ** A shared-cache write-lock is not required to write to the new table,
82537     ** as a schema-lock must have already been obtained to create it. Since
82538     ** a schema-lock excludes all other database users, the write-lock would
82539     ** be redundant.
82540     */
82541     if( pSelect ){
82542       SelectDest dest;
82543       Table *pSelTab;
82544
82545       assert(pParse->nTab==1);
82546       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
82547       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
82548       pParse->nTab = 2;
82549       sqlite3SelectDestInit(&dest, SRT_Table, 1);
82550       sqlite3Select(pParse, pSelect, &dest);
82551       sqlite3VdbeAddOp1(v, OP_Close, 1);
82552       if( pParse->nErr==0 ){
82553         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
82554         if( pSelTab==0 ) return;
82555         assert( p->aCol==0 );
82556         p->nCol = pSelTab->nCol;
82557         p->aCol = pSelTab->aCol;
82558         pSelTab->nCol = 0;
82559         pSelTab->aCol = 0;
82560         sqlite3DeleteTable(db, pSelTab);
82561       }
82562     }
82563
82564     /* Compute the complete text of the CREATE statement */
82565     if( pSelect ){
82566       zStmt = createTableStmt(db, p);
82567     }else{
82568       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
82569       zStmt = sqlite3MPrintf(db, 
82570           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
82571       );
82572     }
82573
82574     /* A slot for the record has already been allocated in the 
82575     ** SQLITE_MASTER table.  We just need to update that slot with all
82576     ** the information we've collected.
82577     */
82578     sqlite3NestedParse(pParse,
82579       "UPDATE %Q.%s "
82580          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
82581        "WHERE rowid=#%d",
82582       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
82583       zType,
82584       p->zName,
82585       p->zName,
82586       pParse->regRoot,
82587       zStmt,
82588       pParse->regRowid
82589     );
82590     sqlite3DbFree(db, zStmt);
82591     sqlite3ChangeCookie(pParse, iDb);
82592
82593 #ifndef SQLITE_OMIT_AUTOINCREMENT
82594     /* Check to see if we need to create an sqlite_sequence table for
82595     ** keeping track of autoincrement keys.
82596     */
82597     if( p->tabFlags & TF_Autoincrement ){
82598       Db *pDb = &db->aDb[iDb];
82599       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82600       if( pDb->pSchema->pSeqTab==0 ){
82601         sqlite3NestedParse(pParse,
82602           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
82603           pDb->zName
82604         );
82605       }
82606     }
82607 #endif
82608
82609     /* Reparse everything to update our internal data structures */
82610     sqlite3VdbeAddParseSchemaOp(v, iDb,
82611                sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
82612   }
82613
82614
82615   /* Add the table to the in-memory representation of the database.
82616   */
82617   if( db->init.busy ){
82618     Table *pOld;
82619     Schema *pSchema = p->pSchema;
82620     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82621     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
82622                              sqlite3Strlen30(p->zName),p);
82623     if( pOld ){
82624       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
82625       db->mallocFailed = 1;
82626       return;
82627     }
82628     pParse->pNewTable = 0;
82629     db->flags |= SQLITE_InternChanges;
82630
82631 #ifndef SQLITE_OMIT_ALTERTABLE
82632     if( !p->pSelect ){
82633       const char *zName = (const char *)pParse->sNameToken.z;
82634       int nName;
82635       assert( !pSelect && pCons && pEnd );
82636       if( pCons->z==0 ){
82637         pCons = pEnd;
82638       }
82639       nName = (int)((const char *)pCons->z - zName);
82640       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
82641     }
82642 #endif
82643   }
82644 }
82645
82646 #ifndef SQLITE_OMIT_VIEW
82647 /*
82648 ** The parser calls this routine in order to create a new VIEW
82649 */
82650 SQLITE_PRIVATE void sqlite3CreateView(
82651   Parse *pParse,     /* The parsing context */
82652   Token *pBegin,     /* The CREATE token that begins the statement */
82653   Token *pName1,     /* The token that holds the name of the view */
82654   Token *pName2,     /* The token that holds the name of the view */
82655   Select *pSelect,   /* A SELECT statement that will become the new view */
82656   int isTemp,        /* TRUE for a TEMPORARY view */
82657   int noErr          /* Suppress error messages if VIEW already exists */
82658 ){
82659   Table *p;
82660   int n;
82661   const char *z;
82662   Token sEnd;
82663   DbFixer sFix;
82664   Token *pName = 0;
82665   int iDb;
82666   sqlite3 *db = pParse->db;
82667
82668   if( pParse->nVar>0 ){
82669     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
82670     sqlite3SelectDelete(db, pSelect);
82671     return;
82672   }
82673   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
82674   p = pParse->pNewTable;
82675   if( p==0 || pParse->nErr ){
82676     sqlite3SelectDelete(db, pSelect);
82677     return;
82678   }
82679   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
82680   iDb = sqlite3SchemaToIndex(db, p->pSchema);
82681   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
82682     && sqlite3FixSelect(&sFix, pSelect)
82683   ){
82684     sqlite3SelectDelete(db, pSelect);
82685     return;
82686   }
82687
82688   /* Make a copy of the entire SELECT statement that defines the view.
82689   ** This will force all the Expr.token.z values to be dynamically
82690   ** allocated rather than point to the input string - which means that
82691   ** they will persist after the current sqlite3_exec() call returns.
82692   */
82693   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
82694   sqlite3SelectDelete(db, pSelect);
82695   if( db->mallocFailed ){
82696     return;
82697   }
82698   if( !db->init.busy ){
82699     sqlite3ViewGetColumnNames(pParse, p);
82700   }
82701
82702   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
82703   ** the end.
82704   */
82705   sEnd = pParse->sLastToken;
82706   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
82707     sEnd.z += sEnd.n;
82708   }
82709   sEnd.n = 0;
82710   n = (int)(sEnd.z - pBegin->z);
82711   z = pBegin->z;
82712   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
82713   sEnd.z = &z[n-1];
82714   sEnd.n = 1;
82715
82716   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
82717   sqlite3EndTable(pParse, 0, &sEnd, 0);
82718   return;
82719 }
82720 #endif /* SQLITE_OMIT_VIEW */
82721
82722 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
82723 /*
82724 ** The Table structure pTable is really a VIEW.  Fill in the names of
82725 ** the columns of the view in the pTable structure.  Return the number
82726 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
82727 */
82728 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
82729   Table *pSelTab;   /* A fake table from which we get the result set */
82730   Select *pSel;     /* Copy of the SELECT that implements the view */
82731   int nErr = 0;     /* Number of errors encountered */
82732   int n;            /* Temporarily holds the number of cursors assigned */
82733   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
82734   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
82735
82736   assert( pTable );
82737
82738 #ifndef SQLITE_OMIT_VIRTUALTABLE
82739   if( sqlite3VtabCallConnect(pParse, pTable) ){
82740     return SQLITE_ERROR;
82741   }
82742   if( IsVirtual(pTable) ) return 0;
82743 #endif
82744
82745 #ifndef SQLITE_OMIT_VIEW
82746   /* A positive nCol means the columns names for this view are
82747   ** already known.
82748   */
82749   if( pTable->nCol>0 ) return 0;
82750
82751   /* A negative nCol is a special marker meaning that we are currently
82752   ** trying to compute the column names.  If we enter this routine with
82753   ** a negative nCol, it means two or more views form a loop, like this:
82754   **
82755   **     CREATE VIEW one AS SELECT * FROM two;
82756   **     CREATE VIEW two AS SELECT * FROM one;
82757   **
82758   ** Actually, the error above is now caught prior to reaching this point.
82759   ** But the following test is still important as it does come up
82760   ** in the following:
82761   ** 
82762   **     CREATE TABLE main.ex1(a);
82763   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
82764   **     SELECT * FROM temp.ex1;
82765   */
82766   if( pTable->nCol<0 ){
82767     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
82768     return 1;
82769   }
82770   assert( pTable->nCol>=0 );
82771
82772   /* If we get this far, it means we need to compute the table names.
82773   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
82774   ** "*" elements in the results set of the view and will assign cursors
82775   ** to the elements of the FROM clause.  But we do not want these changes
82776   ** to be permanent.  So the computation is done on a copy of the SELECT
82777   ** statement that defines the view.
82778   */
82779   assert( pTable->pSelect );
82780   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
82781   if( pSel ){
82782     u8 enableLookaside = db->lookaside.bEnabled;
82783     n = pParse->nTab;
82784     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
82785     pTable->nCol = -1;
82786     db->lookaside.bEnabled = 0;
82787 #ifndef SQLITE_OMIT_AUTHORIZATION
82788     xAuth = db->xAuth;
82789     db->xAuth = 0;
82790     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
82791     db->xAuth = xAuth;
82792 #else
82793     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
82794 #endif
82795     db->lookaside.bEnabled = enableLookaside;
82796     pParse->nTab = n;
82797     if( pSelTab ){
82798       assert( pTable->aCol==0 );
82799       pTable->nCol = pSelTab->nCol;
82800       pTable->aCol = pSelTab->aCol;
82801       pSelTab->nCol = 0;
82802       pSelTab->aCol = 0;
82803       sqlite3DeleteTable(db, pSelTab);
82804       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
82805       pTable->pSchema->flags |= DB_UnresetViews;
82806     }else{
82807       pTable->nCol = 0;
82808       nErr++;
82809     }
82810     sqlite3SelectDelete(db, pSel);
82811   } else {
82812     nErr++;
82813   }
82814 #endif /* SQLITE_OMIT_VIEW */
82815   return nErr;  
82816 }
82817 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
82818
82819 #ifndef SQLITE_OMIT_VIEW
82820 /*
82821 ** Clear the column names from every VIEW in database idx.
82822 */
82823 static void sqliteViewResetAll(sqlite3 *db, int idx){
82824   HashElem *i;
82825   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
82826   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
82827   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
82828     Table *pTab = sqliteHashData(i);
82829     if( pTab->pSelect ){
82830       sqliteDeleteColumnNames(db, pTab);
82831       pTab->aCol = 0;
82832       pTab->nCol = 0;
82833     }
82834   }
82835   DbClearProperty(db, idx, DB_UnresetViews);
82836 }
82837 #else
82838 # define sqliteViewResetAll(A,B)
82839 #endif /* SQLITE_OMIT_VIEW */
82840
82841 /*
82842 ** This function is called by the VDBE to adjust the internal schema
82843 ** used by SQLite when the btree layer moves a table root page. The
82844 ** root-page of a table or index in database iDb has changed from iFrom
82845 ** to iTo.
82846 **
82847 ** Ticket #1728:  The symbol table might still contain information
82848 ** on tables and/or indices that are the process of being deleted.
82849 ** If you are unlucky, one of those deleted indices or tables might
82850 ** have the same rootpage number as the real table or index that is
82851 ** being moved.  So we cannot stop searching after the first match 
82852 ** because the first match might be for one of the deleted indices
82853 ** or tables and not the table/index that is actually being moved.
82854 ** We must continue looping until all tables and indices with
82855 ** rootpage==iFrom have been converted to have a rootpage of iTo
82856 ** in order to be certain that we got the right one.
82857 */
82858 #ifndef SQLITE_OMIT_AUTOVACUUM
82859 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
82860   HashElem *pElem;
82861   Hash *pHash;
82862   Db *pDb;
82863
82864   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82865   pDb = &db->aDb[iDb];
82866   pHash = &pDb->pSchema->tblHash;
82867   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
82868     Table *pTab = sqliteHashData(pElem);
82869     if( pTab->tnum==iFrom ){
82870       pTab->tnum = iTo;
82871     }
82872   }
82873   pHash = &pDb->pSchema->idxHash;
82874   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
82875     Index *pIdx = sqliteHashData(pElem);
82876     if( pIdx->tnum==iFrom ){
82877       pIdx->tnum = iTo;
82878     }
82879   }
82880 }
82881 #endif
82882
82883 /*
82884 ** Write code to erase the table with root-page iTable from database iDb.
82885 ** Also write code to modify the sqlite_master table and internal schema
82886 ** if a root-page of another table is moved by the btree-layer whilst
82887 ** erasing iTable (this can happen with an auto-vacuum database).
82888 */ 
82889 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
82890   Vdbe *v = sqlite3GetVdbe(pParse);
82891   int r1 = sqlite3GetTempReg(pParse);
82892   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
82893   sqlite3MayAbort(pParse);
82894 #ifndef SQLITE_OMIT_AUTOVACUUM
82895   /* OP_Destroy stores an in integer r1. If this integer
82896   ** is non-zero, then it is the root page number of a table moved to
82897   ** location iTable. The following code modifies the sqlite_master table to
82898   ** reflect this.
82899   **
82900   ** The "#NNN" in the SQL is a special constant that means whatever value
82901   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
82902   ** token for additional information.
82903   */
82904   sqlite3NestedParse(pParse, 
82905      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
82906      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
82907 #endif
82908   sqlite3ReleaseTempReg(pParse, r1);
82909 }
82910
82911 /*
82912 ** Write VDBE code to erase table pTab and all associated indices on disk.
82913 ** Code to update the sqlite_master tables and internal schema definitions
82914 ** in case a root-page belonging to another table is moved by the btree layer
82915 ** is also added (this can happen with an auto-vacuum database).
82916 */
82917 static void destroyTable(Parse *pParse, Table *pTab){
82918 #ifdef SQLITE_OMIT_AUTOVACUUM
82919   Index *pIdx;
82920   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82921   destroyRootPage(pParse, pTab->tnum, iDb);
82922   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82923     destroyRootPage(pParse, pIdx->tnum, iDb);
82924   }
82925 #else
82926   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
82927   ** is not defined), then it is important to call OP_Destroy on the
82928   ** table and index root-pages in order, starting with the numerically 
82929   ** largest root-page number. This guarantees that none of the root-pages
82930   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
82931   ** following were coded:
82932   **
82933   ** OP_Destroy 4 0
82934   ** ...
82935   ** OP_Destroy 5 0
82936   **
82937   ** and root page 5 happened to be the largest root-page number in the
82938   ** database, then root page 5 would be moved to page 4 by the 
82939   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
82940   ** a free-list page.
82941   */
82942   int iTab = pTab->tnum;
82943   int iDestroyed = 0;
82944
82945   while( 1 ){
82946     Index *pIdx;
82947     int iLargest = 0;
82948
82949     if( iDestroyed==0 || iTab<iDestroyed ){
82950       iLargest = iTab;
82951     }
82952     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82953       int iIdx = pIdx->tnum;
82954       assert( pIdx->pSchema==pTab->pSchema );
82955       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
82956         iLargest = iIdx;
82957       }
82958     }
82959     if( iLargest==0 ){
82960       return;
82961     }else{
82962       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82963       assert( iDb>=0 && iDb<pParse->db->nDb );
82964       destroyRootPage(pParse, iLargest, iDb);
82965       iDestroyed = iLargest;
82966     }
82967   }
82968 #endif
82969 }
82970
82971 /*
82972 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
82973 ** after a DROP INDEX or DROP TABLE command.
82974 */
82975 static void sqlite3ClearStatTables(
82976   Parse *pParse,         /* The parsing context */
82977   int iDb,               /* The database number */
82978   const char *zType,     /* "idx" or "tbl" */
82979   const char *zName      /* Name of index or table */
82980 ){
82981   int i;
82982   const char *zDbName = pParse->db->aDb[iDb].zName;
82983   for(i=1; i<=3; i++){
82984     char zTab[24];
82985     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
82986     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
82987       sqlite3NestedParse(pParse,
82988         "DELETE FROM %Q.%s WHERE %s=%Q",
82989         zDbName, zTab, zType, zName
82990       );
82991     }
82992   }
82993 }
82994
82995 /*
82996 ** Generate code to drop a table.
82997 */
82998 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
82999   Vdbe *v;
83000   sqlite3 *db = pParse->db;
83001   Trigger *pTrigger;
83002   Db *pDb = &db->aDb[iDb];
83003
83004   v = sqlite3GetVdbe(pParse);
83005   assert( v!=0 );
83006   sqlite3BeginWriteOperation(pParse, 1, iDb);
83007
83008 #ifndef SQLITE_OMIT_VIRTUALTABLE
83009   if( IsVirtual(pTab) ){
83010     sqlite3VdbeAddOp0(v, OP_VBegin);
83011   }
83012 #endif
83013
83014   /* Drop all triggers associated with the table being dropped. Code
83015   ** is generated to remove entries from sqlite_master and/or
83016   ** sqlite_temp_master if required.
83017   */
83018   pTrigger = sqlite3TriggerList(pParse, pTab);
83019   while( pTrigger ){
83020     assert( pTrigger->pSchema==pTab->pSchema || 
83021         pTrigger->pSchema==db->aDb[1].pSchema );
83022     sqlite3DropTriggerPtr(pParse, pTrigger);
83023     pTrigger = pTrigger->pNext;
83024   }
83025
83026 #ifndef SQLITE_OMIT_AUTOINCREMENT
83027   /* Remove any entries of the sqlite_sequence table associated with
83028   ** the table being dropped. This is done before the table is dropped
83029   ** at the btree level, in case the sqlite_sequence table needs to
83030   ** move as a result of the drop (can happen in auto-vacuum mode).
83031   */
83032   if( pTab->tabFlags & TF_Autoincrement ){
83033     sqlite3NestedParse(pParse,
83034       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
83035       pDb->zName, pTab->zName
83036     );
83037   }
83038 #endif
83039
83040   /* Drop all SQLITE_MASTER table and index entries that refer to the
83041   ** table. The program name loops through the master table and deletes
83042   ** every row that refers to a table of the same name as the one being
83043   ** dropped. Triggers are handled separately because a trigger can be
83044   ** created in the temp database that refers to a table in another
83045   ** database.
83046   */
83047   sqlite3NestedParse(pParse, 
83048       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
83049       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
83050   if( !isView && !IsVirtual(pTab) ){
83051     destroyTable(pParse, pTab);
83052   }
83053
83054   /* Remove the table entry from SQLite's internal schema and modify
83055   ** the schema cookie.
83056   */
83057   if( IsVirtual(pTab) ){
83058     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
83059   }
83060   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
83061   sqlite3ChangeCookie(pParse, iDb);
83062   sqliteViewResetAll(db, iDb);
83063 }
83064
83065 /*
83066 ** This routine is called to do the work of a DROP TABLE statement.
83067 ** pName is the name of the table to be dropped.
83068 */
83069 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
83070   Table *pTab;
83071   Vdbe *v;
83072   sqlite3 *db = pParse->db;
83073   int iDb;
83074
83075   if( db->mallocFailed ){
83076     goto exit_drop_table;
83077   }
83078   assert( pParse->nErr==0 );
83079   assert( pName->nSrc==1 );
83080   if( noErr ) db->suppressErr++;
83081   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
83082   if( noErr ) db->suppressErr--;
83083
83084   if( pTab==0 ){
83085     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
83086     goto exit_drop_table;
83087   }
83088   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83089   assert( iDb>=0 && iDb<db->nDb );
83090
83091   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
83092   ** it is initialized.
83093   */
83094   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
83095     goto exit_drop_table;
83096   }
83097 #ifndef SQLITE_OMIT_AUTHORIZATION
83098   {
83099     int code;
83100     const char *zTab = SCHEMA_TABLE(iDb);
83101     const char *zDb = db->aDb[iDb].zName;
83102     const char *zArg2 = 0;
83103     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
83104       goto exit_drop_table;
83105     }
83106     if( isView ){
83107       if( !OMIT_TEMPDB && iDb==1 ){
83108         code = SQLITE_DROP_TEMP_VIEW;
83109       }else{
83110         code = SQLITE_DROP_VIEW;
83111       }
83112 #ifndef SQLITE_OMIT_VIRTUALTABLE
83113     }else if( IsVirtual(pTab) ){
83114       code = SQLITE_DROP_VTABLE;
83115       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
83116 #endif
83117     }else{
83118       if( !OMIT_TEMPDB && iDb==1 ){
83119         code = SQLITE_DROP_TEMP_TABLE;
83120       }else{
83121         code = SQLITE_DROP_TABLE;
83122       }
83123     }
83124     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
83125       goto exit_drop_table;
83126     }
83127     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
83128       goto exit_drop_table;
83129     }
83130   }
83131 #endif
83132   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
83133     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
83134     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
83135     goto exit_drop_table;
83136   }
83137
83138 #ifndef SQLITE_OMIT_VIEW
83139   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
83140   ** on a table.
83141   */
83142   if( isView && pTab->pSelect==0 ){
83143     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
83144     goto exit_drop_table;
83145   }
83146   if( !isView && pTab->pSelect ){
83147     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
83148     goto exit_drop_table;
83149   }
83150 #endif
83151
83152   /* Generate code to remove the table from the master table
83153   ** on disk.
83154   */
83155   v = sqlite3GetVdbe(pParse);
83156   if( v ){
83157     sqlite3BeginWriteOperation(pParse, 1, iDb);
83158     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
83159     sqlite3FkDropTable(pParse, pName, pTab);
83160     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
83161   }
83162
83163 exit_drop_table:
83164   sqlite3SrcListDelete(db, pName);
83165 }
83166
83167 /*
83168 ** This routine is called to create a new foreign key on the table
83169 ** currently under construction.  pFromCol determines which columns
83170 ** in the current table point to the foreign key.  If pFromCol==0 then
83171 ** connect the key to the last column inserted.  pTo is the name of
83172 ** the table referred to.  pToCol is a list of tables in the other
83173 ** pTo table that the foreign key points to.  flags contains all
83174 ** information about the conflict resolution algorithms specified
83175 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
83176 **
83177 ** An FKey structure is created and added to the table currently
83178 ** under construction in the pParse->pNewTable field.
83179 **
83180 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
83181 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
83182 */
83183 SQLITE_PRIVATE void sqlite3CreateForeignKey(
83184   Parse *pParse,       /* Parsing context */
83185   ExprList *pFromCol,  /* Columns in this table that point to other table */
83186   Token *pTo,          /* Name of the other table */
83187   ExprList *pToCol,    /* Columns in the other table */
83188   int flags            /* Conflict resolution algorithms. */
83189 ){
83190   sqlite3 *db = pParse->db;
83191 #ifndef SQLITE_OMIT_FOREIGN_KEY
83192   FKey *pFKey = 0;
83193   FKey *pNextTo;
83194   Table *p = pParse->pNewTable;
83195   int nByte;
83196   int i;
83197   int nCol;
83198   char *z;
83199
83200   assert( pTo!=0 );
83201   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
83202   if( pFromCol==0 ){
83203     int iCol = p->nCol-1;
83204     if( NEVER(iCol<0) ) goto fk_end;
83205     if( pToCol && pToCol->nExpr!=1 ){
83206       sqlite3ErrorMsg(pParse, "foreign key on %s"
83207          " should reference only one column of table %T",
83208          p->aCol[iCol].zName, pTo);
83209       goto fk_end;
83210     }
83211     nCol = 1;
83212   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
83213     sqlite3ErrorMsg(pParse,
83214         "number of columns in foreign key does not match the number of "
83215         "columns in the referenced table");
83216     goto fk_end;
83217   }else{
83218     nCol = pFromCol->nExpr;
83219   }
83220   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
83221   if( pToCol ){
83222     for(i=0; i<pToCol->nExpr; i++){
83223       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
83224     }
83225   }
83226   pFKey = sqlite3DbMallocZero(db, nByte );
83227   if( pFKey==0 ){
83228     goto fk_end;
83229   }
83230   pFKey->pFrom = p;
83231   pFKey->pNextFrom = p->pFKey;
83232   z = (char*)&pFKey->aCol[nCol];
83233   pFKey->zTo = z;
83234   memcpy(z, pTo->z, pTo->n);
83235   z[pTo->n] = 0;
83236   sqlite3Dequote(z);
83237   z += pTo->n+1;
83238   pFKey->nCol = nCol;
83239   if( pFromCol==0 ){
83240     pFKey->aCol[0].iFrom = p->nCol-1;
83241   }else{
83242     for(i=0; i<nCol; i++){
83243       int j;
83244       for(j=0; j<p->nCol; j++){
83245         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
83246           pFKey->aCol[i].iFrom = j;
83247           break;
83248         }
83249       }
83250       if( j>=p->nCol ){
83251         sqlite3ErrorMsg(pParse, 
83252           "unknown column \"%s\" in foreign key definition", 
83253           pFromCol->a[i].zName);
83254         goto fk_end;
83255       }
83256     }
83257   }
83258   if( pToCol ){
83259     for(i=0; i<nCol; i++){
83260       int n = sqlite3Strlen30(pToCol->a[i].zName);
83261       pFKey->aCol[i].zCol = z;
83262       memcpy(z, pToCol->a[i].zName, n);
83263       z[n] = 0;
83264       z += n+1;
83265     }
83266   }
83267   pFKey->isDeferred = 0;
83268   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
83269   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
83270
83271   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
83272   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
83273       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
83274   );
83275   if( pNextTo==pFKey ){
83276     db->mallocFailed = 1;
83277     goto fk_end;
83278   }
83279   if( pNextTo ){
83280     assert( pNextTo->pPrevTo==0 );
83281     pFKey->pNextTo = pNextTo;
83282     pNextTo->pPrevTo = pFKey;
83283   }
83284
83285   /* Link the foreign key to the table as the last step.
83286   */
83287   p->pFKey = pFKey;
83288   pFKey = 0;
83289
83290 fk_end:
83291   sqlite3DbFree(db, pFKey);
83292 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
83293   sqlite3ExprListDelete(db, pFromCol);
83294   sqlite3ExprListDelete(db, pToCol);
83295 }
83296
83297 /*
83298 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
83299 ** clause is seen as part of a foreign key definition.  The isDeferred
83300 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
83301 ** The behavior of the most recently created foreign key is adjusted
83302 ** accordingly.
83303 */
83304 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
83305 #ifndef SQLITE_OMIT_FOREIGN_KEY
83306   Table *pTab;
83307   FKey *pFKey;
83308   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
83309   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
83310   pFKey->isDeferred = (u8)isDeferred;
83311 #endif
83312 }
83313
83314 /*
83315 ** Generate code that will erase and refill index *pIdx.  This is
83316 ** used to initialize a newly created index or to recompute the
83317 ** content of an index in response to a REINDEX command.
83318 **
83319 ** if memRootPage is not negative, it means that the index is newly
83320 ** created.  The register specified by memRootPage contains the
83321 ** root page number of the index.  If memRootPage is negative, then
83322 ** the index already exists and must be cleared before being refilled and
83323 ** the root page number of the index is taken from pIndex->tnum.
83324 */
83325 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
83326   Table *pTab = pIndex->pTable;  /* The table that is indexed */
83327   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
83328   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
83329   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
83330   int addr1;                     /* Address of top of loop */
83331   int addr2;                     /* Address to jump to for next iteration */
83332   int tnum;                      /* Root page of index */
83333   Vdbe *v;                       /* Generate code into this virtual machine */
83334   KeyInfo *pKey;                 /* KeyInfo for index */
83335   int regRecord;                 /* Register holding assemblied index record */
83336   sqlite3 *db = pParse->db;      /* The database connection */
83337   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
83338
83339 #ifndef SQLITE_OMIT_AUTHORIZATION
83340   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
83341       db->aDb[iDb].zName ) ){
83342     return;
83343   }
83344 #endif
83345
83346   /* Require a write-lock on the table to perform this operation */
83347   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
83348
83349   v = sqlite3GetVdbe(pParse);
83350   if( v==0 ) return;
83351   if( memRootPage>=0 ){
83352     tnum = memRootPage;
83353   }else{
83354     tnum = pIndex->tnum;
83355     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
83356   }
83357   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
83358   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
83359                     (char *)pKey, P4_KEYINFO_HANDOFF);
83360   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
83361
83362   /* Open the sorter cursor if we are to use one. */
83363   iSorter = pParse->nTab++;
83364   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
83365
83366   /* Open the table. Loop through all rows of the table, inserting index
83367   ** records into the sorter. */
83368   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
83369   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
83370   regRecord = sqlite3GetTempReg(pParse);
83371
83372   sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
83373   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
83374   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
83375   sqlite3VdbeJumpHere(v, addr1);
83376   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
83377   if( pIndex->onError!=OE_None ){
83378     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
83379     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
83380     addr2 = sqlite3VdbeCurrentAddr(v);
83381     sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
83382     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
83383         OE_Abort, "indexed columns are not unique", P4_STATIC
83384     );
83385   }else{
83386     addr2 = sqlite3VdbeCurrentAddr(v);
83387   }
83388   sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
83389   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
83390   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83391   sqlite3ReleaseTempReg(pParse, regRecord);
83392   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
83393   sqlite3VdbeJumpHere(v, addr1);
83394
83395   sqlite3VdbeAddOp1(v, OP_Close, iTab);
83396   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
83397   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
83398 }
83399
83400 /*
83401 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
83402 ** and pTblList is the name of the table that is to be indexed.  Both will 
83403 ** be NULL for a primary key or an index that is created to satisfy a
83404 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
83405 ** as the table to be indexed.  pParse->pNewTable is a table that is
83406 ** currently being constructed by a CREATE TABLE statement.
83407 **
83408 ** pList is a list of columns to be indexed.  pList will be NULL if this
83409 ** is a primary key or unique-constraint on the most recent column added
83410 ** to the table currently under construction.  
83411 **
83412 ** If the index is created successfully, return a pointer to the new Index
83413 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
83414 ** as the tables primary key (Index.autoIndex==2).
83415 */
83416 SQLITE_PRIVATE Index *sqlite3CreateIndex(
83417   Parse *pParse,     /* All information about this parse */
83418   Token *pName1,     /* First part of index name. May be NULL */
83419   Token *pName2,     /* Second part of index name. May be NULL */
83420   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
83421   ExprList *pList,   /* A list of columns to be indexed */
83422   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
83423   Token *pStart,     /* The CREATE token that begins this statement */
83424   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
83425   int sortOrder,     /* Sort order of primary key when pList==NULL */
83426   int ifNotExist     /* Omit error if index already exists */
83427 ){
83428   Index *pRet = 0;     /* Pointer to return */
83429   Table *pTab = 0;     /* Table to be indexed */
83430   Index *pIndex = 0;   /* The index to be created */
83431   char *zName = 0;     /* Name of the index */
83432   int nName;           /* Number of characters in zName */
83433   int i, j;
83434   Token nullId;        /* Fake token for an empty ID list */
83435   DbFixer sFix;        /* For assigning database names to pTable */
83436   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
83437   sqlite3 *db = pParse->db;
83438   Db *pDb;             /* The specific table containing the indexed database */
83439   int iDb;             /* Index of the database that is being written */
83440   Token *pName = 0;    /* Unqualified name of the index to create */
83441   struct ExprList_item *pListItem; /* For looping over pList */
83442   int nCol;
83443   int nExtra = 0;
83444   char *zExtra;
83445
83446   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
83447   assert( pParse->nErr==0 );      /* Never called with prior errors */
83448   if( db->mallocFailed || IN_DECLARE_VTAB ){
83449     goto exit_create_index;
83450   }
83451   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83452     goto exit_create_index;
83453   }
83454
83455   /*
83456   ** Find the table that is to be indexed.  Return early if not found.
83457   */
83458   if( pTblName!=0 ){
83459
83460     /* Use the two-part index name to determine the database 
83461     ** to search for the table. 'Fix' the table name to this db
83462     ** before looking up the table.
83463     */
83464     assert( pName1 && pName2 );
83465     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83466     if( iDb<0 ) goto exit_create_index;
83467     assert( pName && pName->z );
83468
83469 #ifndef SQLITE_OMIT_TEMPDB
83470     /* If the index name was unqualified, check if the table
83471     ** is a temp table. If so, set the database to 1. Do not do this
83472     ** if initialising a database schema.
83473     */
83474     if( !db->init.busy ){
83475       pTab = sqlite3SrcListLookup(pParse, pTblName);
83476       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
83477         iDb = 1;
83478       }
83479     }
83480 #endif
83481
83482     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
83483         sqlite3FixSrcList(&sFix, pTblName)
83484     ){
83485       /* Because the parser constructs pTblName from a single identifier,
83486       ** sqlite3FixSrcList can never fail. */
83487       assert(0);
83488     }
83489     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
83490     assert( db->mallocFailed==0 || pTab==0 );
83491     if( pTab==0 ) goto exit_create_index;
83492     assert( db->aDb[iDb].pSchema==pTab->pSchema );
83493   }else{
83494     assert( pName==0 );
83495     assert( pStart==0 );
83496     pTab = pParse->pNewTable;
83497     if( !pTab ) goto exit_create_index;
83498     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83499   }
83500   pDb = &db->aDb[iDb];
83501
83502   assert( pTab!=0 );
83503   assert( pParse->nErr==0 );
83504   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
83505        && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
83506     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
83507     goto exit_create_index;
83508   }
83509 #ifndef SQLITE_OMIT_VIEW
83510   if( pTab->pSelect ){
83511     sqlite3ErrorMsg(pParse, "views may not be indexed");
83512     goto exit_create_index;
83513   }
83514 #endif
83515 #ifndef SQLITE_OMIT_VIRTUALTABLE
83516   if( IsVirtual(pTab) ){
83517     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
83518     goto exit_create_index;
83519   }
83520 #endif
83521
83522   /*
83523   ** Find the name of the index.  Make sure there is not already another
83524   ** index or table with the same name.  
83525   **
83526   ** Exception:  If we are reading the names of permanent indices from the
83527   ** sqlite_master table (because some other process changed the schema) and
83528   ** one of the index names collides with the name of a temporary table or
83529   ** index, then we will continue to process this index.
83530   **
83531   ** If pName==0 it means that we are
83532   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
83533   ** own name.
83534   */
83535   if( pName ){
83536     zName = sqlite3NameFromToken(db, pName);
83537     if( zName==0 ) goto exit_create_index;
83538     assert( pName->z!=0 );
83539     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
83540       goto exit_create_index;
83541     }
83542     if( !db->init.busy ){
83543       if( sqlite3FindTable(db, zName, 0)!=0 ){
83544         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
83545         goto exit_create_index;
83546       }
83547     }
83548     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
83549       if( !ifNotExist ){
83550         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
83551       }else{
83552         assert( !db->init.busy );
83553         sqlite3CodeVerifySchema(pParse, iDb);
83554       }
83555       goto exit_create_index;
83556     }
83557   }else{
83558     int n;
83559     Index *pLoop;
83560     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
83561     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
83562     if( zName==0 ){
83563       goto exit_create_index;
83564     }
83565   }
83566
83567   /* Check for authorization to create an index.
83568   */
83569 #ifndef SQLITE_OMIT_AUTHORIZATION
83570   {
83571     const char *zDb = pDb->zName;
83572     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
83573       goto exit_create_index;
83574     }
83575     i = SQLITE_CREATE_INDEX;
83576     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
83577     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
83578       goto exit_create_index;
83579     }
83580   }
83581 #endif
83582
83583   /* If pList==0, it means this routine was called to make a primary
83584   ** key out of the last column added to the table under construction.
83585   ** So create a fake list to simulate this.
83586   */
83587   if( pList==0 ){
83588     nullId.z = pTab->aCol[pTab->nCol-1].zName;
83589     nullId.n = sqlite3Strlen30((char*)nullId.z);
83590     pList = sqlite3ExprListAppend(pParse, 0, 0);
83591     if( pList==0 ) goto exit_create_index;
83592     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
83593     pList->a[0].sortOrder = (u8)sortOrder;
83594   }
83595
83596   /* Figure out how many bytes of space are required to store explicitly
83597   ** specified collation sequence names.
83598   */
83599   for(i=0; i<pList->nExpr; i++){
83600     Expr *pExpr = pList->a[i].pExpr;
83601     if( pExpr ){
83602       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
83603       if( pColl ){
83604         nExtra += (1 + sqlite3Strlen30(pColl->zName));
83605       }
83606     }
83607   }
83608
83609   /* 
83610   ** Allocate the index structure. 
83611   */
83612   nName = sqlite3Strlen30(zName);
83613   nCol = pList->nExpr;
83614   pIndex = sqlite3DbMallocZero(db, 
83615       ROUND8(sizeof(Index)) +              /* Index structure  */
83616       ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
83617       sizeof(char *)*nCol +                /* Index.azColl     */
83618       sizeof(int)*nCol +                   /* Index.aiColumn   */
83619       sizeof(u8)*nCol +                    /* Index.aSortOrder */
83620       nName + 1 +                          /* Index.zName      */
83621       nExtra                               /* Collation sequence names */
83622   );
83623   if( db->mallocFailed ){
83624     goto exit_create_index;
83625   }
83626   zExtra = (char*)pIndex;
83627   pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
83628   pIndex->azColl = (char**)
83629      ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
83630   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
83631   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
83632   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
83633   pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
83634   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
83635   zExtra = (char *)(&pIndex->zName[nName+1]);
83636   memcpy(pIndex->zName, zName, nName+1);
83637   pIndex->pTable = pTab;
83638   pIndex->nColumn = pList->nExpr;
83639   pIndex->onError = (u8)onError;
83640   pIndex->autoIndex = (u8)(pName==0);
83641   pIndex->pSchema = db->aDb[iDb].pSchema;
83642   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83643
83644   /* Check to see if we should honor DESC requests on index columns
83645   */
83646   if( pDb->pSchema->file_format>=4 ){
83647     sortOrderMask = -1;   /* Honor DESC */
83648   }else{
83649     sortOrderMask = 0;    /* Ignore DESC */
83650   }
83651
83652   /* Scan the names of the columns of the table to be indexed and
83653   ** load the column indices into the Index structure.  Report an error
83654   ** if any column is not found.
83655   **
83656   ** TODO:  Add a test to make sure that the same column is not named
83657   ** more than once within the same index.  Only the first instance of
83658   ** the column will ever be used by the optimizer.  Note that using the
83659   ** same column more than once cannot be an error because that would 
83660   ** break backwards compatibility - it needs to be a warning.
83661   */
83662   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
83663     const char *zColName = pListItem->zName;
83664     Column *pTabCol;
83665     int requestedSortOrder;
83666     CollSeq *pColl;                /* Collating sequence */
83667     char *zColl;                   /* Collation sequence name */
83668
83669     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
83670       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
83671     }
83672     if( j>=pTab->nCol ){
83673       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
83674         pTab->zName, zColName);
83675       pParse->checkSchema = 1;
83676       goto exit_create_index;
83677     }
83678     pIndex->aiColumn[i] = j;
83679     if( pListItem->pExpr
83680      && (pColl = sqlite3ExprCollSeq(pParse, pListItem->pExpr))!=0
83681     ){
83682       int nColl;
83683       zColl = pColl->zName;
83684       nColl = sqlite3Strlen30(zColl) + 1;
83685       assert( nExtra>=nColl );
83686       memcpy(zExtra, zColl, nColl);
83687       zColl = zExtra;
83688       zExtra += nColl;
83689       nExtra -= nColl;
83690     }else{
83691       zColl = pTab->aCol[j].zColl;
83692       if( !zColl ){
83693         zColl = "BINARY";
83694       }
83695     }
83696     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
83697       goto exit_create_index;
83698     }
83699     pIndex->azColl[i] = zColl;
83700     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
83701     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
83702   }
83703   sqlite3DefaultRowEst(pIndex);
83704
83705   if( pTab==pParse->pNewTable ){
83706     /* This routine has been called to create an automatic index as a
83707     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
83708     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
83709     ** i.e. one of:
83710     **
83711     ** CREATE TABLE t(x PRIMARY KEY, y);
83712     ** CREATE TABLE t(x, y, UNIQUE(x, y));
83713     **
83714     ** Either way, check to see if the table already has such an index. If
83715     ** so, don't bother creating this one. This only applies to
83716     ** automatically created indices. Users can do as they wish with
83717     ** explicit indices.
83718     **
83719     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
83720     ** (and thus suppressing the second one) even if they have different
83721     ** sort orders.
83722     **
83723     ** If there are different collating sequences or if the columns of
83724     ** the constraint occur in different orders, then the constraints are
83725     ** considered distinct and both result in separate indices.
83726     */
83727     Index *pIdx;
83728     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83729       int k;
83730       assert( pIdx->onError!=OE_None );
83731       assert( pIdx->autoIndex );
83732       assert( pIndex->onError!=OE_None );
83733
83734       if( pIdx->nColumn!=pIndex->nColumn ) continue;
83735       for(k=0; k<pIdx->nColumn; k++){
83736         const char *z1;
83737         const char *z2;
83738         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
83739         z1 = pIdx->azColl[k];
83740         z2 = pIndex->azColl[k];
83741         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
83742       }
83743       if( k==pIdx->nColumn ){
83744         if( pIdx->onError!=pIndex->onError ){
83745           /* This constraint creates the same index as a previous
83746           ** constraint specified somewhere in the CREATE TABLE statement.
83747           ** However the ON CONFLICT clauses are different. If both this 
83748           ** constraint and the previous equivalent constraint have explicit
83749           ** ON CONFLICT clauses this is an error. Otherwise, use the
83750           ** explicitly specified behavior for the index.
83751           */
83752           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
83753             sqlite3ErrorMsg(pParse, 
83754                 "conflicting ON CONFLICT clauses specified", 0);
83755           }
83756           if( pIdx->onError==OE_Default ){
83757             pIdx->onError = pIndex->onError;
83758           }
83759         }
83760         goto exit_create_index;
83761       }
83762     }
83763   }
83764
83765   /* Link the new Index structure to its table and to the other
83766   ** in-memory database structures. 
83767   */
83768   if( db->init.busy ){
83769     Index *p;
83770     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
83771     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
83772                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
83773                           pIndex);
83774     if( p ){
83775       assert( p==pIndex );  /* Malloc must have failed */
83776       db->mallocFailed = 1;
83777       goto exit_create_index;
83778     }
83779     db->flags |= SQLITE_InternChanges;
83780     if( pTblName!=0 ){
83781       pIndex->tnum = db->init.newTnum;
83782     }
83783   }
83784
83785   /* If the db->init.busy is 0 then create the index on disk.  This
83786   ** involves writing the index into the master table and filling in the
83787   ** index with the current table contents.
83788   **
83789   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
83790   ** command.  db->init.busy is 1 when a database is opened and 
83791   ** CREATE INDEX statements are read out of the master table.  In
83792   ** the latter case the index already exists on disk, which is why
83793   ** we don't want to recreate it.
83794   **
83795   ** If pTblName==0 it means this index is generated as a primary key
83796   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
83797   ** has just been created, it contains no data and the index initialization
83798   ** step can be skipped.
83799   */
83800   else{ /* if( db->init.busy==0 ) */
83801     Vdbe *v;
83802     char *zStmt;
83803     int iMem = ++pParse->nMem;
83804
83805     v = sqlite3GetVdbe(pParse);
83806     if( v==0 ) goto exit_create_index;
83807
83808
83809     /* Create the rootpage for the index
83810     */
83811     sqlite3BeginWriteOperation(pParse, 1, iDb);
83812     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
83813
83814     /* Gather the complete text of the CREATE INDEX statement into
83815     ** the zStmt variable
83816     */
83817     if( pStart ){
83818       assert( pEnd!=0 );
83819       /* A named index with an explicit CREATE INDEX statement */
83820       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
83821         onError==OE_None ? "" : " UNIQUE",
83822         (int)(pEnd->z - pName->z) + 1,
83823         pName->z);
83824     }else{
83825       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
83826       /* zStmt = sqlite3MPrintf(""); */
83827       zStmt = 0;
83828     }
83829
83830     /* Add an entry in sqlite_master for this index
83831     */
83832     sqlite3NestedParse(pParse, 
83833         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
83834         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
83835         pIndex->zName,
83836         pTab->zName,
83837         iMem,
83838         zStmt
83839     );
83840     sqlite3DbFree(db, zStmt);
83841
83842     /* Fill the index with data and reparse the schema. Code an OP_Expire
83843     ** to invalidate all pre-compiled statements.
83844     */
83845     if( pTblName ){
83846       sqlite3RefillIndex(pParse, pIndex, iMem);
83847       sqlite3ChangeCookie(pParse, iDb);
83848       sqlite3VdbeAddParseSchemaOp(v, iDb,
83849          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
83850       sqlite3VdbeAddOp1(v, OP_Expire, 0);
83851     }
83852   }
83853
83854   /* When adding an index to the list of indices for a table, make
83855   ** sure all indices labeled OE_Replace come after all those labeled
83856   ** OE_Ignore.  This is necessary for the correct constraint check
83857   ** processing (in sqlite3GenerateConstraintChecks()) as part of
83858   ** UPDATE and INSERT statements.  
83859   */
83860   if( db->init.busy || pTblName==0 ){
83861     if( onError!=OE_Replace || pTab->pIndex==0
83862          || pTab->pIndex->onError==OE_Replace){
83863       pIndex->pNext = pTab->pIndex;
83864       pTab->pIndex = pIndex;
83865     }else{
83866       Index *pOther = pTab->pIndex;
83867       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
83868         pOther = pOther->pNext;
83869       }
83870       pIndex->pNext = pOther->pNext;
83871       pOther->pNext = pIndex;
83872     }
83873     pRet = pIndex;
83874     pIndex = 0;
83875   }
83876
83877   /* Clean up before exiting */
83878 exit_create_index:
83879   if( pIndex ){
83880     sqlite3DbFree(db, pIndex->zColAff);
83881     sqlite3DbFree(db, pIndex);
83882   }
83883   sqlite3ExprListDelete(db, pList);
83884   sqlite3SrcListDelete(db, pTblName);
83885   sqlite3DbFree(db, zName);
83886   return pRet;
83887 }
83888
83889 /*
83890 ** Fill the Index.aiRowEst[] array with default information - information
83891 ** to be used when we have not run the ANALYZE command.
83892 **
83893 ** aiRowEst[0] is suppose to contain the number of elements in the index.
83894 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
83895 ** number of rows in the table that match any particular value of the
83896 ** first column of the index.  aiRowEst[2] is an estimate of the number
83897 ** of rows that match any particular combiniation of the first 2 columns
83898 ** of the index.  And so forth.  It must always be the case that
83899 *
83900 **           aiRowEst[N]<=aiRowEst[N-1]
83901 **           aiRowEst[N]>=1
83902 **
83903 ** Apart from that, we have little to go on besides intuition as to
83904 ** how aiRowEst[] should be initialized.  The numbers generated here
83905 ** are based on typical values found in actual indices.
83906 */
83907 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
83908   tRowcnt *a = pIdx->aiRowEst;
83909   int i;
83910   tRowcnt n;
83911   assert( a!=0 );
83912   a[0] = pIdx->pTable->nRowEst;
83913   if( a[0]<10 ) a[0] = 10;
83914   n = 10;
83915   for(i=1; i<=pIdx->nColumn; i++){
83916     a[i] = n;
83917     if( n>5 ) n--;
83918   }
83919   if( pIdx->onError!=OE_None ){
83920     a[pIdx->nColumn] = 1;
83921   }
83922 }
83923
83924 /*
83925 ** This routine will drop an existing named index.  This routine
83926 ** implements the DROP INDEX statement.
83927 */
83928 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
83929   Index *pIndex;
83930   Vdbe *v;
83931   sqlite3 *db = pParse->db;
83932   int iDb;
83933
83934   assert( pParse->nErr==0 );   /* Never called with prior errors */
83935   if( db->mallocFailed ){
83936     goto exit_drop_index;
83937   }
83938   assert( pName->nSrc==1 );
83939   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83940     goto exit_drop_index;
83941   }
83942   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
83943   if( pIndex==0 ){
83944     if( !ifExists ){
83945       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
83946     }else{
83947       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
83948     }
83949     pParse->checkSchema = 1;
83950     goto exit_drop_index;
83951   }
83952   if( pIndex->autoIndex ){
83953     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
83954       "or PRIMARY KEY constraint cannot be dropped", 0);
83955     goto exit_drop_index;
83956   }
83957   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
83958 #ifndef SQLITE_OMIT_AUTHORIZATION
83959   {
83960     int code = SQLITE_DROP_INDEX;
83961     Table *pTab = pIndex->pTable;
83962     const char *zDb = db->aDb[iDb].zName;
83963     const char *zTab = SCHEMA_TABLE(iDb);
83964     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
83965       goto exit_drop_index;
83966     }
83967     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
83968     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
83969       goto exit_drop_index;
83970     }
83971   }
83972 #endif
83973
83974   /* Generate code to remove the index and from the master table */
83975   v = sqlite3GetVdbe(pParse);
83976   if( v ){
83977     sqlite3BeginWriteOperation(pParse, 1, iDb);
83978     sqlite3NestedParse(pParse,
83979        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
83980        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
83981     );
83982     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
83983     sqlite3ChangeCookie(pParse, iDb);
83984     destroyRootPage(pParse, pIndex->tnum, iDb);
83985     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
83986   }
83987
83988 exit_drop_index:
83989   sqlite3SrcListDelete(db, pName);
83990 }
83991
83992 /*
83993 ** pArray is a pointer to an array of objects. Each object in the
83994 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
83995 ** to extend the array so that there is space for a new object at the end.
83996 **
83997 ** When this function is called, *pnEntry contains the current size of
83998 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
83999 ** in total).
84000 **
84001 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
84002 ** space allocated for the new object is zeroed, *pnEntry updated to
84003 ** reflect the new size of the array and a pointer to the new allocation
84004 ** returned. *pIdx is set to the index of the new array entry in this case.
84005 **
84006 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
84007 ** unchanged and a copy of pArray returned.
84008 */
84009 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
84010   sqlite3 *db,      /* Connection to notify of malloc failures */
84011   void *pArray,     /* Array of objects.  Might be reallocated */
84012   int szEntry,      /* Size of each object in the array */
84013   int *pnEntry,     /* Number of objects currently in use */
84014   int *pIdx         /* Write the index of a new slot here */
84015 ){
84016   char *z;
84017   int n = *pnEntry;
84018   if( (n & (n-1))==0 ){
84019     int sz = (n==0) ? 1 : 2*n;
84020     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
84021     if( pNew==0 ){
84022       *pIdx = -1;
84023       return pArray;
84024     }
84025     pArray = pNew;
84026   }
84027   z = (char*)pArray;
84028   memset(&z[n * szEntry], 0, szEntry);
84029   *pIdx = n;
84030   ++*pnEntry;
84031   return pArray;
84032 }
84033
84034 /*
84035 ** Append a new element to the given IdList.  Create a new IdList if
84036 ** need be.
84037 **
84038 ** A new IdList is returned, or NULL if malloc() fails.
84039 */
84040 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
84041   int i;
84042   if( pList==0 ){
84043     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
84044     if( pList==0 ) return 0;
84045   }
84046   pList->a = sqlite3ArrayAllocate(
84047       db,
84048       pList->a,
84049       sizeof(pList->a[0]),
84050       &pList->nId,
84051       &i
84052   );
84053   if( i<0 ){
84054     sqlite3IdListDelete(db, pList);
84055     return 0;
84056   }
84057   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
84058   return pList;
84059 }
84060
84061 /*
84062 ** Delete an IdList.
84063 */
84064 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
84065   int i;
84066   if( pList==0 ) return;
84067   for(i=0; i<pList->nId; i++){
84068     sqlite3DbFree(db, pList->a[i].zName);
84069   }
84070   sqlite3DbFree(db, pList->a);
84071   sqlite3DbFree(db, pList);
84072 }
84073
84074 /*
84075 ** Return the index in pList of the identifier named zId.  Return -1
84076 ** if not found.
84077 */
84078 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
84079   int i;
84080   if( pList==0 ) return -1;
84081   for(i=0; i<pList->nId; i++){
84082     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
84083   }
84084   return -1;
84085 }
84086
84087 /*
84088 ** Expand the space allocated for the given SrcList object by
84089 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
84090 ** New slots are zeroed.
84091 **
84092 ** For example, suppose a SrcList initially contains two entries: A,B.
84093 ** To append 3 new entries onto the end, do this:
84094 **
84095 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
84096 **
84097 ** After the call above it would contain:  A, B, nil, nil, nil.
84098 ** If the iStart argument had been 1 instead of 2, then the result
84099 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
84100 ** the iStart value would be 0.  The result then would
84101 ** be: nil, nil, nil, A, B.
84102 **
84103 ** If a memory allocation fails the SrcList is unchanged.  The
84104 ** db->mallocFailed flag will be set to true.
84105 */
84106 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
84107   sqlite3 *db,       /* Database connection to notify of OOM errors */
84108   SrcList *pSrc,     /* The SrcList to be enlarged */
84109   int nExtra,        /* Number of new slots to add to pSrc->a[] */
84110   int iStart         /* Index in pSrc->a[] of first new slot */
84111 ){
84112   int i;
84113
84114   /* Sanity checking on calling parameters */
84115   assert( iStart>=0 );
84116   assert( nExtra>=1 );
84117   assert( pSrc!=0 );
84118   assert( iStart<=pSrc->nSrc );
84119
84120   /* Allocate additional space if needed */
84121   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
84122     SrcList *pNew;
84123     int nAlloc = pSrc->nSrc+nExtra;
84124     int nGot;
84125     pNew = sqlite3DbRealloc(db, pSrc,
84126                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
84127     if( pNew==0 ){
84128       assert( db->mallocFailed );
84129       return pSrc;
84130     }
84131     pSrc = pNew;
84132     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
84133     pSrc->nAlloc = (u16)nGot;
84134   }
84135
84136   /* Move existing slots that come after the newly inserted slots
84137   ** out of the way */
84138   for(i=pSrc->nSrc-1; i>=iStart; i--){
84139     pSrc->a[i+nExtra] = pSrc->a[i];
84140   }
84141   pSrc->nSrc += (i16)nExtra;
84142
84143   /* Zero the newly allocated slots */
84144   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
84145   for(i=iStart; i<iStart+nExtra; i++){
84146     pSrc->a[i].iCursor = -1;
84147   }
84148
84149   /* Return a pointer to the enlarged SrcList */
84150   return pSrc;
84151 }
84152
84153
84154 /*
84155 ** Append a new table name to the given SrcList.  Create a new SrcList if
84156 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
84157 **
84158 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
84159 ** SrcList might be the same as the SrcList that was input or it might be
84160 ** a new one.  If an OOM error does occurs, then the prior value of pList
84161 ** that is input to this routine is automatically freed.
84162 **
84163 ** If pDatabase is not null, it means that the table has an optional
84164 ** database name prefix.  Like this:  "database.table".  The pDatabase
84165 ** points to the table name and the pTable points to the database name.
84166 ** The SrcList.a[].zName field is filled with the table name which might
84167 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
84168 ** SrcList.a[].zDatabase is filled with the database name from pTable,
84169 ** or with NULL if no database is specified.
84170 **
84171 ** In other words, if call like this:
84172 **
84173 **         sqlite3SrcListAppend(D,A,B,0);
84174 **
84175 ** Then B is a table name and the database name is unspecified.  If called
84176 ** like this:
84177 **
84178 **         sqlite3SrcListAppend(D,A,B,C);
84179 **
84180 ** Then C is the table name and B is the database name.  If C is defined
84181 ** then so is B.  In other words, we never have a case where:
84182 **
84183 **         sqlite3SrcListAppend(D,A,0,C);
84184 **
84185 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
84186 ** before being added to the SrcList.
84187 */
84188 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
84189   sqlite3 *db,        /* Connection to notify of malloc failures */
84190   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
84191   Token *pTable,      /* Table to append */
84192   Token *pDatabase    /* Database of the table */
84193 ){
84194   struct SrcList_item *pItem;
84195   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
84196   if( pList==0 ){
84197     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
84198     if( pList==0 ) return 0;
84199     pList->nAlloc = 1;
84200   }
84201   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
84202   if( db->mallocFailed ){
84203     sqlite3SrcListDelete(db, pList);
84204     return 0;
84205   }
84206   pItem = &pList->a[pList->nSrc-1];
84207   if( pDatabase && pDatabase->z==0 ){
84208     pDatabase = 0;
84209   }
84210   if( pDatabase ){
84211     Token *pTemp = pDatabase;
84212     pDatabase = pTable;
84213     pTable = pTemp;
84214   }
84215   pItem->zName = sqlite3NameFromToken(db, pTable);
84216   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
84217   return pList;
84218 }
84219
84220 /*
84221 ** Assign VdbeCursor index numbers to all tables in a SrcList
84222 */
84223 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
84224   int i;
84225   struct SrcList_item *pItem;
84226   assert(pList || pParse->db->mallocFailed );
84227   if( pList ){
84228     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
84229       if( pItem->iCursor>=0 ) break;
84230       pItem->iCursor = pParse->nTab++;
84231       if( pItem->pSelect ){
84232         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
84233       }
84234     }
84235   }
84236 }
84237
84238 /*
84239 ** Delete an entire SrcList including all its substructure.
84240 */
84241 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
84242   int i;
84243   struct SrcList_item *pItem;
84244   if( pList==0 ) return;
84245   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
84246     sqlite3DbFree(db, pItem->zDatabase);
84247     sqlite3DbFree(db, pItem->zName);
84248     sqlite3DbFree(db, pItem->zAlias);
84249     sqlite3DbFree(db, pItem->zIndex);
84250     sqlite3DeleteTable(db, pItem->pTab);
84251     sqlite3SelectDelete(db, pItem->pSelect);
84252     sqlite3ExprDelete(db, pItem->pOn);
84253     sqlite3IdListDelete(db, pItem->pUsing);
84254   }
84255   sqlite3DbFree(db, pList);
84256 }
84257
84258 /*
84259 ** This routine is called by the parser to add a new term to the
84260 ** end of a growing FROM clause.  The "p" parameter is the part of
84261 ** the FROM clause that has already been constructed.  "p" is NULL
84262 ** if this is the first term of the FROM clause.  pTable and pDatabase
84263 ** are the name of the table and database named in the FROM clause term.
84264 ** pDatabase is NULL if the database name qualifier is missing - the
84265 ** usual case.  If the term has a alias, then pAlias points to the
84266 ** alias token.  If the term is a subquery, then pSubquery is the
84267 ** SELECT statement that the subquery encodes.  The pTable and
84268 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
84269 ** parameters are the content of the ON and USING clauses.
84270 **
84271 ** Return a new SrcList which encodes is the FROM with the new
84272 ** term added.
84273 */
84274 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
84275   Parse *pParse,          /* Parsing context */
84276   SrcList *p,             /* The left part of the FROM clause already seen */
84277   Token *pTable,          /* Name of the table to add to the FROM clause */
84278   Token *pDatabase,       /* Name of the database containing pTable */
84279   Token *pAlias,          /* The right-hand side of the AS subexpression */
84280   Select *pSubquery,      /* A subquery used in place of a table name */
84281   Expr *pOn,              /* The ON clause of a join */
84282   IdList *pUsing          /* The USING clause of a join */
84283 ){
84284   struct SrcList_item *pItem;
84285   sqlite3 *db = pParse->db;
84286   if( !p && (pOn || pUsing) ){
84287     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
84288       (pOn ? "ON" : "USING")
84289     );
84290     goto append_from_error;
84291   }
84292   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
84293   if( p==0 || NEVER(p->nSrc==0) ){
84294     goto append_from_error;
84295   }
84296   pItem = &p->a[p->nSrc-1];
84297   assert( pAlias!=0 );
84298   if( pAlias->n ){
84299     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
84300   }
84301   pItem->pSelect = pSubquery;
84302   pItem->pOn = pOn;
84303   pItem->pUsing = pUsing;
84304   return p;
84305
84306  append_from_error:
84307   assert( p==0 );
84308   sqlite3ExprDelete(db, pOn);
84309   sqlite3IdListDelete(db, pUsing);
84310   sqlite3SelectDelete(db, pSubquery);
84311   return 0;
84312 }
84313
84314 /*
84315 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
84316 ** element of the source-list passed as the second argument.
84317 */
84318 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
84319   assert( pIndexedBy!=0 );
84320   if( p && ALWAYS(p->nSrc>0) ){
84321     struct SrcList_item *pItem = &p->a[p->nSrc-1];
84322     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
84323     if( pIndexedBy->n==1 && !pIndexedBy->z ){
84324       /* A "NOT INDEXED" clause was supplied. See parse.y 
84325       ** construct "indexed_opt" for details. */
84326       pItem->notIndexed = 1;
84327     }else{
84328       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
84329     }
84330   }
84331 }
84332
84333 /*
84334 ** When building up a FROM clause in the parser, the join operator
84335 ** is initially attached to the left operand.  But the code generator
84336 ** expects the join operator to be on the right operand.  This routine
84337 ** Shifts all join operators from left to right for an entire FROM
84338 ** clause.
84339 **
84340 ** Example: Suppose the join is like this:
84341 **
84342 **           A natural cross join B
84343 **
84344 ** The operator is "natural cross join".  The A and B operands are stored
84345 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
84346 ** operator with A.  This routine shifts that operator over to B.
84347 */
84348 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
84349   if( p ){
84350     int i;
84351     assert( p->a || p->nSrc==0 );
84352     for(i=p->nSrc-1; i>0; i--){
84353       p->a[i].jointype = p->a[i-1].jointype;
84354     }
84355     p->a[0].jointype = 0;
84356   }
84357 }
84358
84359 /*
84360 ** Begin a transaction
84361 */
84362 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
84363   sqlite3 *db;
84364   Vdbe *v;
84365   int i;
84366
84367   assert( pParse!=0 );
84368   db = pParse->db;
84369   assert( db!=0 );
84370 /*  if( db->aDb[0].pBt==0 ) return; */
84371   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
84372     return;
84373   }
84374   v = sqlite3GetVdbe(pParse);
84375   if( !v ) return;
84376   if( type!=TK_DEFERRED ){
84377     for(i=0; i<db->nDb; i++){
84378       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
84379       sqlite3VdbeUsesBtree(v, i);
84380     }
84381   }
84382   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
84383 }
84384
84385 /*
84386 ** Commit a transaction
84387 */
84388 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
84389   Vdbe *v;
84390
84391   assert( pParse!=0 );
84392   assert( pParse->db!=0 );
84393   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
84394     return;
84395   }
84396   v = sqlite3GetVdbe(pParse);
84397   if( v ){
84398     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
84399   }
84400 }
84401
84402 /*
84403 ** Rollback a transaction
84404 */
84405 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
84406   Vdbe *v;
84407
84408   assert( pParse!=0 );
84409   assert( pParse->db!=0 );
84410   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
84411     return;
84412   }
84413   v = sqlite3GetVdbe(pParse);
84414   if( v ){
84415     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
84416   }
84417 }
84418
84419 /*
84420 ** This function is called by the parser when it parses a command to create,
84421 ** release or rollback an SQL savepoint. 
84422 */
84423 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
84424   char *zName = sqlite3NameFromToken(pParse->db, pName);
84425   if( zName ){
84426     Vdbe *v = sqlite3GetVdbe(pParse);
84427 #ifndef SQLITE_OMIT_AUTHORIZATION
84428     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
84429     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
84430 #endif
84431     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
84432       sqlite3DbFree(pParse->db, zName);
84433       return;
84434     }
84435     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
84436   }
84437 }
84438
84439 /*
84440 ** Make sure the TEMP database is open and available for use.  Return
84441 ** the number of errors.  Leave any error messages in the pParse structure.
84442 */
84443 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
84444   sqlite3 *db = pParse->db;
84445   if( db->aDb[1].pBt==0 && !pParse->explain ){
84446     int rc;
84447     Btree *pBt;
84448     static const int flags = 
84449           SQLITE_OPEN_READWRITE |
84450           SQLITE_OPEN_CREATE |
84451           SQLITE_OPEN_EXCLUSIVE |
84452           SQLITE_OPEN_DELETEONCLOSE |
84453           SQLITE_OPEN_TEMP_DB;
84454
84455     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
84456     if( rc!=SQLITE_OK ){
84457       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
84458         "file for storing temporary tables");
84459       pParse->rc = rc;
84460       return 1;
84461     }
84462     db->aDb[1].pBt = pBt;
84463     assert( db->aDb[1].pSchema );
84464     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
84465       db->mallocFailed = 1;
84466       return 1;
84467     }
84468   }
84469   return 0;
84470 }
84471
84472 /*
84473 ** Generate VDBE code that will verify the schema cookie and start
84474 ** a read-transaction for all named database files.
84475 **
84476 ** It is important that all schema cookies be verified and all
84477 ** read transactions be started before anything else happens in
84478 ** the VDBE program.  But this routine can be called after much other
84479 ** code has been generated.  So here is what we do:
84480 **
84481 ** The first time this routine is called, we code an OP_Goto that
84482 ** will jump to a subroutine at the end of the program.  Then we
84483 ** record every database that needs its schema verified in the
84484 ** pParse->cookieMask field.  Later, after all other code has been
84485 ** generated, the subroutine that does the cookie verifications and
84486 ** starts the transactions will be coded and the OP_Goto P2 value
84487 ** will be made to point to that subroutine.  The generation of the
84488 ** cookie verification subroutine code happens in sqlite3FinishCoding().
84489 **
84490 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
84491 ** schema on any databases.  This can be used to position the OP_Goto
84492 ** early in the code, before we know if any database tables will be used.
84493 */
84494 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
84495   Parse *pToplevel = sqlite3ParseToplevel(pParse);
84496
84497 #ifndef SQLITE_OMIT_TRIGGER
84498   if( pToplevel!=pParse ){
84499     /* This branch is taken if a trigger is currently being coded. In this
84500     ** case, set cookieGoto to a non-zero value to show that this function
84501     ** has been called. This is used by the sqlite3ExprCodeConstants()
84502     ** function. */
84503     pParse->cookieGoto = -1;
84504   }
84505 #endif
84506   if( pToplevel->cookieGoto==0 ){
84507     Vdbe *v = sqlite3GetVdbe(pToplevel);
84508     if( v==0 ) return;  /* This only happens if there was a prior error */
84509     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
84510   }
84511   if( iDb>=0 ){
84512     sqlite3 *db = pToplevel->db;
84513     yDbMask mask;
84514
84515     assert( iDb<db->nDb );
84516     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
84517     assert( iDb<SQLITE_MAX_ATTACHED+2 );
84518     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84519     mask = ((yDbMask)1)<<iDb;
84520     if( (pToplevel->cookieMask & mask)==0 ){
84521       pToplevel->cookieMask |= mask;
84522       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
84523       if( !OMIT_TEMPDB && iDb==1 ){
84524         sqlite3OpenTempDatabase(pToplevel);
84525       }
84526     }
84527   }
84528 }
84529
84530 /*
84531 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
84532 ** attached database. Otherwise, invoke it for the database named zDb only.
84533 */
84534 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
84535   sqlite3 *db = pParse->db;
84536   int i;
84537   for(i=0; i<db->nDb; i++){
84538     Db *pDb = &db->aDb[i];
84539     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
84540       sqlite3CodeVerifySchema(pParse, i);
84541     }
84542   }
84543 }
84544
84545 /*
84546 ** Generate VDBE code that prepares for doing an operation that
84547 ** might change the database.
84548 **
84549 ** This routine starts a new transaction if we are not already within
84550 ** a transaction.  If we are already within a transaction, then a checkpoint
84551 ** is set if the setStatement parameter is true.  A checkpoint should
84552 ** be set for operations that might fail (due to a constraint) part of
84553 ** the way through and which will need to undo some writes without having to
84554 ** rollback the whole transaction.  For operations where all constraints
84555 ** can be checked before any changes are made to the database, it is never
84556 ** necessary to undo a write and the checkpoint should not be set.
84557 */
84558 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
84559   Parse *pToplevel = sqlite3ParseToplevel(pParse);
84560   sqlite3CodeVerifySchema(pParse, iDb);
84561   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
84562   pToplevel->isMultiWrite |= setStatement;
84563 }
84564
84565 /*
84566 ** Indicate that the statement currently under construction might write
84567 ** more than one entry (example: deleting one row then inserting another,
84568 ** inserting multiple rows in a table, or inserting a row and index entries.)
84569 ** If an abort occurs after some of these writes have completed, then it will
84570 ** be necessary to undo the completed writes.
84571 */
84572 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
84573   Parse *pToplevel = sqlite3ParseToplevel(pParse);
84574   pToplevel->isMultiWrite = 1;
84575 }
84576
84577 /* 
84578 ** The code generator calls this routine if is discovers that it is
84579 ** possible to abort a statement prior to completion.  In order to 
84580 ** perform this abort without corrupting the database, we need to make
84581 ** sure that the statement is protected by a statement transaction.
84582 **
84583 ** Technically, we only need to set the mayAbort flag if the
84584 ** isMultiWrite flag was previously set.  There is a time dependency
84585 ** such that the abort must occur after the multiwrite.  This makes
84586 ** some statements involving the REPLACE conflict resolution algorithm
84587 ** go a little faster.  But taking advantage of this time dependency
84588 ** makes it more difficult to prove that the code is correct (in 
84589 ** particular, it prevents us from writing an effective
84590 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
84591 ** to take the safe route and skip the optimization.
84592 */
84593 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
84594   Parse *pToplevel = sqlite3ParseToplevel(pParse);
84595   pToplevel->mayAbort = 1;
84596 }
84597
84598 /*
84599 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
84600 ** error. The onError parameter determines which (if any) of the statement
84601 ** and/or current transaction is rolled back.
84602 */
84603 SQLITE_PRIVATE void sqlite3HaltConstraint(
84604   Parse *pParse,    /* Parsing context */
84605   int errCode,      /* extended error code */
84606   int onError,      /* Constraint type */
84607   char *p4,         /* Error message */
84608   int p4type        /* P4_STATIC or P4_TRANSIENT */
84609 ){
84610   Vdbe *v = sqlite3GetVdbe(pParse);
84611   assert( (errCode&0xff)==SQLITE_CONSTRAINT );
84612   if( onError==OE_Abort ){
84613     sqlite3MayAbort(pParse);
84614   }
84615   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
84616 }
84617
84618 /*
84619 ** Check to see if pIndex uses the collating sequence pColl.  Return
84620 ** true if it does and false if it does not.
84621 */
84622 #ifndef SQLITE_OMIT_REINDEX
84623 static int collationMatch(const char *zColl, Index *pIndex){
84624   int i;
84625   assert( zColl!=0 );
84626   for(i=0; i<pIndex->nColumn; i++){
84627     const char *z = pIndex->azColl[i];
84628     assert( z!=0 );
84629     if( 0==sqlite3StrICmp(z, zColl) ){
84630       return 1;
84631     }
84632   }
84633   return 0;
84634 }
84635 #endif
84636
84637 /*
84638 ** Recompute all indices of pTab that use the collating sequence pColl.
84639 ** If pColl==0 then recompute all indices of pTab.
84640 */
84641 #ifndef SQLITE_OMIT_REINDEX
84642 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
84643   Index *pIndex;              /* An index associated with pTab */
84644
84645   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
84646     if( zColl==0 || collationMatch(zColl, pIndex) ){
84647       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84648       sqlite3BeginWriteOperation(pParse, 0, iDb);
84649       sqlite3RefillIndex(pParse, pIndex, -1);
84650     }
84651   }
84652 }
84653 #endif
84654
84655 /*
84656 ** Recompute all indices of all tables in all databases where the
84657 ** indices use the collating sequence pColl.  If pColl==0 then recompute
84658 ** all indices everywhere.
84659 */
84660 #ifndef SQLITE_OMIT_REINDEX
84661 static void reindexDatabases(Parse *pParse, char const *zColl){
84662   Db *pDb;                    /* A single database */
84663   int iDb;                    /* The database index number */
84664   sqlite3 *db = pParse->db;   /* The database connection */
84665   HashElem *k;                /* For looping over tables in pDb */
84666   Table *pTab;                /* A table in the database */
84667
84668   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
84669   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
84670     assert( pDb!=0 );
84671     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
84672       pTab = (Table*)sqliteHashData(k);
84673       reindexTable(pParse, pTab, zColl);
84674     }
84675   }
84676 }
84677 #endif
84678
84679 /*
84680 ** Generate code for the REINDEX command.
84681 **
84682 **        REINDEX                            -- 1
84683 **        REINDEX  <collation>               -- 2
84684 **        REINDEX  ?<database>.?<tablename>  -- 3
84685 **        REINDEX  ?<database>.?<indexname>  -- 4
84686 **
84687 ** Form 1 causes all indices in all attached databases to be rebuilt.
84688 ** Form 2 rebuilds all indices in all databases that use the named
84689 ** collating function.  Forms 3 and 4 rebuild the named index or all
84690 ** indices associated with the named table.
84691 */
84692 #ifndef SQLITE_OMIT_REINDEX
84693 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
84694   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
84695   char *z;                    /* Name of a table or index */
84696   const char *zDb;            /* Name of the database */
84697   Table *pTab;                /* A table in the database */
84698   Index *pIndex;              /* An index associated with pTab */
84699   int iDb;                    /* The database index number */
84700   sqlite3 *db = pParse->db;   /* The database connection */
84701   Token *pObjName;            /* Name of the table or index to be reindexed */
84702
84703   /* Read the database schema. If an error occurs, leave an error message
84704   ** and code in pParse and return NULL. */
84705   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84706     return;
84707   }
84708
84709   if( pName1==0 ){
84710     reindexDatabases(pParse, 0);
84711     return;
84712   }else if( NEVER(pName2==0) || pName2->z==0 ){
84713     char *zColl;
84714     assert( pName1->z );
84715     zColl = sqlite3NameFromToken(pParse->db, pName1);
84716     if( !zColl ) return;
84717     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
84718     if( pColl ){
84719       reindexDatabases(pParse, zColl);
84720       sqlite3DbFree(db, zColl);
84721       return;
84722     }
84723     sqlite3DbFree(db, zColl);
84724   }
84725   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
84726   if( iDb<0 ) return;
84727   z = sqlite3NameFromToken(db, pObjName);
84728   if( z==0 ) return;
84729   zDb = db->aDb[iDb].zName;
84730   pTab = sqlite3FindTable(db, z, zDb);
84731   if( pTab ){
84732     reindexTable(pParse, pTab, 0);
84733     sqlite3DbFree(db, z);
84734     return;
84735   }
84736   pIndex = sqlite3FindIndex(db, z, zDb);
84737   sqlite3DbFree(db, z);
84738   if( pIndex ){
84739     sqlite3BeginWriteOperation(pParse, 0, iDb);
84740     sqlite3RefillIndex(pParse, pIndex, -1);
84741     return;
84742   }
84743   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
84744 }
84745 #endif
84746
84747 /*
84748 ** Return a dynamicly allocated KeyInfo structure that can be used
84749 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
84750 **
84751 ** If successful, a pointer to the new structure is returned. In this case
84752 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
84753 ** pointer. If an error occurs (out of memory or missing collation 
84754 ** sequence), NULL is returned and the state of pParse updated to reflect
84755 ** the error.
84756 */
84757 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
84758   int i;
84759   int nCol = pIdx->nColumn;
84760   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
84761   sqlite3 *db = pParse->db;
84762   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
84763
84764   if( pKey ){
84765     pKey->db = pParse->db;
84766     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
84767     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
84768     for(i=0; i<nCol; i++){
84769       char *zColl = pIdx->azColl[i];
84770       assert( zColl );
84771       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
84772       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
84773     }
84774     pKey->nField = (u16)nCol;
84775   }
84776
84777   if( pParse->nErr ){
84778     sqlite3DbFree(db, pKey);
84779     pKey = 0;
84780   }
84781   return pKey;
84782 }
84783
84784 /************** End of build.c ***********************************************/
84785 /************** Begin file callback.c ****************************************/
84786 /*
84787 ** 2005 May 23 
84788 **
84789 ** The author disclaims copyright to this source code.  In place of
84790 ** a legal notice, here is a blessing:
84791 **
84792 **    May you do good and not evil.
84793 **    May you find forgiveness for yourself and forgive others.
84794 **    May you share freely, never taking more than you give.
84795 **
84796 *************************************************************************
84797 **
84798 ** This file contains functions used to access the internal hash tables
84799 ** of user defined functions and collation sequences.
84800 */
84801
84802
84803 /*
84804 ** Invoke the 'collation needed' callback to request a collation sequence
84805 ** in the encoding enc of name zName, length nName.
84806 */
84807 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
84808   assert( !db->xCollNeeded || !db->xCollNeeded16 );
84809   if( db->xCollNeeded ){
84810     char *zExternal = sqlite3DbStrDup(db, zName);
84811     if( !zExternal ) return;
84812     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
84813     sqlite3DbFree(db, zExternal);
84814   }
84815 #ifndef SQLITE_OMIT_UTF16
84816   if( db->xCollNeeded16 ){
84817     char const *zExternal;
84818     sqlite3_value *pTmp = sqlite3ValueNew(db);
84819     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
84820     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
84821     if( zExternal ){
84822       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
84823     }
84824     sqlite3ValueFree(pTmp);
84825   }
84826 #endif
84827 }
84828
84829 /*
84830 ** This routine is called if the collation factory fails to deliver a
84831 ** collation function in the best encoding but there may be other versions
84832 ** of this collation function (for other text encodings) available. Use one
84833 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
84834 ** possible.
84835 */
84836 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
84837   CollSeq *pColl2;
84838   char *z = pColl->zName;
84839   int i;
84840   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
84841   for(i=0; i<3; i++){
84842     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
84843     if( pColl2->xCmp!=0 ){
84844       memcpy(pColl, pColl2, sizeof(CollSeq));
84845       pColl->xDel = 0;         /* Do not copy the destructor */
84846       return SQLITE_OK;
84847     }
84848   }
84849   return SQLITE_ERROR;
84850 }
84851
84852 /*
84853 ** This function is responsible for invoking the collation factory callback
84854 ** or substituting a collation sequence of a different encoding when the
84855 ** requested collation sequence is not available in the desired encoding.
84856 ** 
84857 ** If it is not NULL, then pColl must point to the database native encoding 
84858 ** collation sequence with name zName, length nName.
84859 **
84860 ** The return value is either the collation sequence to be used in database
84861 ** db for collation type name zName, length nName, or NULL, if no collation
84862 ** sequence can be found.  If no collation is found, leave an error message.
84863 **
84864 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
84865 */
84866 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
84867   Parse *pParse,        /* Parsing context */
84868   u8 enc,               /* The desired encoding for the collating sequence */
84869   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
84870   const char *zName     /* Collating sequence name */
84871 ){
84872   CollSeq *p;
84873   sqlite3 *db = pParse->db;
84874
84875   p = pColl;
84876   if( !p ){
84877     p = sqlite3FindCollSeq(db, enc, zName, 0);
84878   }
84879   if( !p || !p->xCmp ){
84880     /* No collation sequence of this type for this encoding is registered.
84881     ** Call the collation factory to see if it can supply us with one.
84882     */
84883     callCollNeeded(db, enc, zName);
84884     p = sqlite3FindCollSeq(db, enc, zName, 0);
84885   }
84886   if( p && !p->xCmp && synthCollSeq(db, p) ){
84887     p = 0;
84888   }
84889   assert( !p || p->xCmp );
84890   if( p==0 ){
84891     sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
84892   }
84893   return p;
84894 }
84895
84896 /*
84897 ** This routine is called on a collation sequence before it is used to
84898 ** check that it is defined. An undefined collation sequence exists when
84899 ** a database is loaded that contains references to collation sequences
84900 ** that have not been defined by sqlite3_create_collation() etc.
84901 **
84902 ** If required, this routine calls the 'collation needed' callback to
84903 ** request a definition of the collating sequence. If this doesn't work, 
84904 ** an equivalent collating sequence that uses a text encoding different
84905 ** from the main database is substituted, if one is available.
84906 */
84907 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
84908   if( pColl ){
84909     const char *zName = pColl->zName;
84910     sqlite3 *db = pParse->db;
84911     CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
84912     if( !p ){
84913       return SQLITE_ERROR;
84914     }
84915     assert( p==pColl );
84916   }
84917   return SQLITE_OK;
84918 }
84919
84920
84921
84922 /*
84923 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
84924 ** specified by zName and nName is not found and parameter 'create' is
84925 ** true, then create a new entry. Otherwise return NULL.
84926 **
84927 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
84928 ** array of three CollSeq structures. The first is the collation sequence
84929 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
84930 **
84931 ** Stored immediately after the three collation sequences is a copy of
84932 ** the collation sequence name. A pointer to this string is stored in
84933 ** each collation sequence structure.
84934 */
84935 static CollSeq *findCollSeqEntry(
84936   sqlite3 *db,          /* Database connection */
84937   const char *zName,    /* Name of the collating sequence */
84938   int create            /* Create a new entry if true */
84939 ){
84940   CollSeq *pColl;
84941   int nName = sqlite3Strlen30(zName);
84942   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
84943
84944   if( 0==pColl && create ){
84945     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
84946     if( pColl ){
84947       CollSeq *pDel = 0;
84948       pColl[0].zName = (char*)&pColl[3];
84949       pColl[0].enc = SQLITE_UTF8;
84950       pColl[1].zName = (char*)&pColl[3];
84951       pColl[1].enc = SQLITE_UTF16LE;
84952       pColl[2].zName = (char*)&pColl[3];
84953       pColl[2].enc = SQLITE_UTF16BE;
84954       memcpy(pColl[0].zName, zName, nName);
84955       pColl[0].zName[nName] = 0;
84956       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
84957
84958       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
84959       ** return the pColl pointer to be deleted (because it wasn't added
84960       ** to the hash table).
84961       */
84962       assert( pDel==0 || pDel==pColl );
84963       if( pDel!=0 ){
84964         db->mallocFailed = 1;
84965         sqlite3DbFree(db, pDel);
84966         pColl = 0;
84967       }
84968     }
84969   }
84970   return pColl;
84971 }
84972
84973 /*
84974 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
84975 ** Return the CollSeq* pointer for the collation sequence named zName
84976 ** for the encoding 'enc' from the database 'db'.
84977 **
84978 ** If the entry specified is not found and 'create' is true, then create a
84979 ** new entry.  Otherwise return NULL.
84980 **
84981 ** A separate function sqlite3LocateCollSeq() is a wrapper around
84982 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
84983 ** if necessary and generates an error message if the collating sequence
84984 ** cannot be found.
84985 **
84986 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
84987 */
84988 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
84989   sqlite3 *db,
84990   u8 enc,
84991   const char *zName,
84992   int create
84993 ){
84994   CollSeq *pColl;
84995   if( zName ){
84996     pColl = findCollSeqEntry(db, zName, create);
84997   }else{
84998     pColl = db->pDfltColl;
84999   }
85000   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
85001   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
85002   if( pColl ) pColl += enc-1;
85003   return pColl;
85004 }
85005
85006 /* During the search for the best function definition, this procedure
85007 ** is called to test how well the function passed as the first argument
85008 ** matches the request for a function with nArg arguments in a system
85009 ** that uses encoding enc. The value returned indicates how well the
85010 ** request is matched. A higher value indicates a better match.
85011 **
85012 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
85013 ** is also -1.  In other words, we are searching for a function that
85014 ** takes a variable number of arguments.
85015 **
85016 ** If nArg is -2 that means that we are searching for any function 
85017 ** regardless of the number of arguments it uses, so return a positive
85018 ** match score for any
85019 **
85020 ** The returned value is always between 0 and 6, as follows:
85021 **
85022 ** 0: Not a match.
85023 ** 1: UTF8/16 conversion required and function takes any number of arguments.
85024 ** 2: UTF16 byte order change required and function takes any number of args.
85025 ** 3: encoding matches and function takes any number of arguments
85026 ** 4: UTF8/16 conversion required - argument count matches exactly
85027 ** 5: UTF16 byte order conversion required - argument count matches exactly
85028 ** 6: Perfect match:  encoding and argument count match exactly.
85029 **
85030 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
85031 ** a perfect match and any function with both xStep and xFunc NULL is
85032 ** a non-match.
85033 */
85034 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
85035 static int matchQuality(
85036   FuncDef *p,     /* The function we are evaluating for match quality */
85037   int nArg,       /* Desired number of arguments.  (-1)==any */
85038   u8 enc          /* Desired text encoding */
85039 ){
85040   int match;
85041
85042   /* nArg of -2 is a special case */
85043   if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
85044
85045   /* Wrong number of arguments means "no match" */
85046   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
85047
85048   /* Give a better score to a function with a specific number of arguments
85049   ** than to function that accepts any number of arguments. */
85050   if( p->nArg==nArg ){
85051     match = 4;
85052   }else{
85053     match = 1;
85054   }
85055
85056   /* Bonus points if the text encoding matches */
85057   if( enc==p->iPrefEnc ){
85058     match += 2;  /* Exact encoding match */
85059   }else if( (enc & p->iPrefEnc & 2)!=0 ){
85060     match += 1;  /* Both are UTF16, but with different byte orders */
85061   }
85062
85063   return match;
85064 }
85065
85066 /*
85067 ** Search a FuncDefHash for a function with the given name.  Return
85068 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
85069 */
85070 static FuncDef *functionSearch(
85071   FuncDefHash *pHash,  /* Hash table to search */
85072   int h,               /* Hash of the name */
85073   const char *zFunc,   /* Name of function */
85074   int nFunc            /* Number of bytes in zFunc */
85075 ){
85076   FuncDef *p;
85077   for(p=pHash->a[h]; p; p=p->pHash){
85078     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
85079       return p;
85080     }
85081   }
85082   return 0;
85083 }
85084
85085 /*
85086 ** Insert a new FuncDef into a FuncDefHash hash table.
85087 */
85088 SQLITE_PRIVATE void sqlite3FuncDefInsert(
85089   FuncDefHash *pHash,  /* The hash table into which to insert */
85090   FuncDef *pDef        /* The function definition to insert */
85091 ){
85092   FuncDef *pOther;
85093   int nName = sqlite3Strlen30(pDef->zName);
85094   u8 c1 = (u8)pDef->zName[0];
85095   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
85096   pOther = functionSearch(pHash, h, pDef->zName, nName);
85097   if( pOther ){
85098     assert( pOther!=pDef && pOther->pNext!=pDef );
85099     pDef->pNext = pOther->pNext;
85100     pOther->pNext = pDef;
85101   }else{
85102     pDef->pNext = 0;
85103     pDef->pHash = pHash->a[h];
85104     pHash->a[h] = pDef;
85105   }
85106 }
85107   
85108   
85109
85110 /*
85111 ** Locate a user function given a name, a number of arguments and a flag
85112 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
85113 ** pointer to the FuncDef structure that defines that function, or return
85114 ** NULL if the function does not exist.
85115 **
85116 ** If the createFlag argument is true, then a new (blank) FuncDef
85117 ** structure is created and liked into the "db" structure if a
85118 ** no matching function previously existed.
85119 **
85120 ** If nArg is -2, then the first valid function found is returned.  A
85121 ** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
85122 ** case is used to see if zName is a valid function name for some number
85123 ** of arguments.  If nArg is -2, then createFlag must be 0.
85124 **
85125 ** If createFlag is false, then a function with the required name and
85126 ** number of arguments may be returned even if the eTextRep flag does not
85127 ** match that requested.
85128 */
85129 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
85130   sqlite3 *db,       /* An open database */
85131   const char *zName, /* Name of the function.  Not null-terminated */
85132   int nName,         /* Number of characters in the name */
85133   int nArg,          /* Number of arguments.  -1 means any number */
85134   u8 enc,            /* Preferred text encoding */
85135   u8 createFlag      /* Create new entry if true and does not otherwise exist */
85136 ){
85137   FuncDef *p;         /* Iterator variable */
85138   FuncDef *pBest = 0; /* Best match found so far */
85139   int bestScore = 0;  /* Score of best match */
85140   int h;              /* Hash value */
85141
85142   assert( nArg>=(-2) );
85143   assert( nArg>=(-1) || createFlag==0 );
85144   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
85145   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
85146
85147   /* First search for a match amongst the application-defined functions.
85148   */
85149   p = functionSearch(&db->aFunc, h, zName, nName);
85150   while( p ){
85151     int score = matchQuality(p, nArg, enc);
85152     if( score>bestScore ){
85153       pBest = p;
85154       bestScore = score;
85155     }
85156     p = p->pNext;
85157   }
85158
85159   /* If no match is found, search the built-in functions.
85160   **
85161   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
85162   ** functions even if a prior app-defined function was found.  And give
85163   ** priority to built-in functions.
85164   **
85165   ** Except, if createFlag is true, that means that we are trying to
85166   ** install a new function.  Whatever FuncDef structure is returned it will
85167   ** have fields overwritten with new information appropriate for the
85168   ** new function.  But the FuncDefs for built-in functions are read-only.
85169   ** So we must not search for built-ins when creating a new function.
85170   */ 
85171   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
85172     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
85173     bestScore = 0;
85174     p = functionSearch(pHash, h, zName, nName);
85175     while( p ){
85176       int score = matchQuality(p, nArg, enc);
85177       if( score>bestScore ){
85178         pBest = p;
85179         bestScore = score;
85180       }
85181       p = p->pNext;
85182     }
85183   }
85184
85185   /* If the createFlag parameter is true and the search did not reveal an
85186   ** exact match for the name, number of arguments and encoding, then add a
85187   ** new entry to the hash table and return it.
85188   */
85189   if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
85190       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
85191     pBest->zName = (char *)&pBest[1];
85192     pBest->nArg = (u16)nArg;
85193     pBest->iPrefEnc = enc;
85194     memcpy(pBest->zName, zName, nName);
85195     pBest->zName[nName] = 0;
85196     sqlite3FuncDefInsert(&db->aFunc, pBest);
85197   }
85198
85199   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
85200     return pBest;
85201   }
85202   return 0;
85203 }
85204
85205 /*
85206 ** Free all resources held by the schema structure. The void* argument points
85207 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
85208 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
85209 ** of the schema hash tables).
85210 **
85211 ** The Schema.cache_size variable is not cleared.
85212 */
85213 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
85214   Hash temp1;
85215   Hash temp2;
85216   HashElem *pElem;
85217   Schema *pSchema = (Schema *)p;
85218
85219   temp1 = pSchema->tblHash;
85220   temp2 = pSchema->trigHash;
85221   sqlite3HashInit(&pSchema->trigHash);
85222   sqlite3HashClear(&pSchema->idxHash);
85223   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
85224     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
85225   }
85226   sqlite3HashClear(&temp2);
85227   sqlite3HashInit(&pSchema->tblHash);
85228   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
85229     Table *pTab = sqliteHashData(pElem);
85230     sqlite3DeleteTable(0, pTab);
85231   }
85232   sqlite3HashClear(&temp1);
85233   sqlite3HashClear(&pSchema->fkeyHash);
85234   pSchema->pSeqTab = 0;
85235   if( pSchema->flags & DB_SchemaLoaded ){
85236     pSchema->iGeneration++;
85237     pSchema->flags &= ~DB_SchemaLoaded;
85238   }
85239 }
85240
85241 /*
85242 ** Find and return the schema associated with a BTree.  Create
85243 ** a new one if necessary.
85244 */
85245 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
85246   Schema * p;
85247   if( pBt ){
85248     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
85249   }else{
85250     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
85251   }
85252   if( !p ){
85253     db->mallocFailed = 1;
85254   }else if ( 0==p->file_format ){
85255     sqlite3HashInit(&p->tblHash);
85256     sqlite3HashInit(&p->idxHash);
85257     sqlite3HashInit(&p->trigHash);
85258     sqlite3HashInit(&p->fkeyHash);
85259     p->enc = SQLITE_UTF8;
85260   }
85261   return p;
85262 }
85263
85264 /************** End of callback.c ********************************************/
85265 /************** Begin file delete.c ******************************************/
85266 /*
85267 ** 2001 September 15
85268 **
85269 ** The author disclaims copyright to this source code.  In place of
85270 ** a legal notice, here is a blessing:
85271 **
85272 **    May you do good and not evil.
85273 **    May you find forgiveness for yourself and forgive others.
85274 **    May you share freely, never taking more than you give.
85275 **
85276 *************************************************************************
85277 ** This file contains C code routines that are called by the parser
85278 ** in order to generate code for DELETE FROM statements.
85279 */
85280
85281 /*
85282 ** While a SrcList can in general represent multiple tables and subqueries
85283 ** (as in the FROM clause of a SELECT statement) in this case it contains
85284 ** the name of a single table, as one might find in an INSERT, DELETE,
85285 ** or UPDATE statement.  Look up that table in the symbol table and
85286 ** return a pointer.  Set an error message and return NULL if the table 
85287 ** name is not found or if any other error occurs.
85288 **
85289 ** The following fields are initialized appropriate in pSrc:
85290 **
85291 **    pSrc->a[0].pTab       Pointer to the Table object
85292 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
85293 **
85294 */
85295 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
85296   struct SrcList_item *pItem = pSrc->a;
85297   Table *pTab;
85298   assert( pItem && pSrc->nSrc==1 );
85299   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
85300   sqlite3DeleteTable(pParse->db, pItem->pTab);
85301   pItem->pTab = pTab;
85302   if( pTab ){
85303     pTab->nRef++;
85304   }
85305   if( sqlite3IndexedByLookup(pParse, pItem) ){
85306     pTab = 0;
85307   }
85308   return pTab;
85309 }
85310
85311 /*
85312 ** Check to make sure the given table is writable.  If it is not
85313 ** writable, generate an error message and return 1.  If it is
85314 ** writable return 0;
85315 */
85316 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
85317   /* A table is not writable under the following circumstances:
85318   **
85319   **   1) It is a virtual table and no implementation of the xUpdate method
85320   **      has been provided, or
85321   **   2) It is a system table (i.e. sqlite_master), this call is not
85322   **      part of a nested parse and writable_schema pragma has not 
85323   **      been specified.
85324   **
85325   ** In either case leave an error message in pParse and return non-zero.
85326   */
85327   if( ( IsVirtual(pTab) 
85328      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
85329    || ( (pTab->tabFlags & TF_Readonly)!=0
85330      && (pParse->db->flags & SQLITE_WriteSchema)==0
85331      && pParse->nested==0 )
85332   ){
85333     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
85334     return 1;
85335   }
85336
85337 #ifndef SQLITE_OMIT_VIEW
85338   if( !viewOk && pTab->pSelect ){
85339     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
85340     return 1;
85341   }
85342 #endif
85343   return 0;
85344 }
85345
85346
85347 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85348 /*
85349 ** Evaluate a view and store its result in an ephemeral table.  The
85350 ** pWhere argument is an optional WHERE clause that restricts the
85351 ** set of rows in the view that are to be added to the ephemeral table.
85352 */
85353 SQLITE_PRIVATE void sqlite3MaterializeView(
85354   Parse *pParse,       /* Parsing context */
85355   Table *pView,        /* View definition */
85356   Expr *pWhere,        /* Optional WHERE clause to be added */
85357   int iCur             /* Cursor number for ephemerial table */
85358 ){
85359   SelectDest dest;
85360   Select *pSel;
85361   SrcList *pFrom;
85362   sqlite3 *db = pParse->db;
85363   int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
85364
85365   pWhere = sqlite3ExprDup(db, pWhere, 0);
85366   pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
85367
85368   if( pFrom ){
85369     assert( pFrom->nSrc==1 );
85370     pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
85371     pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
85372     assert( pFrom->a[0].pOn==0 );
85373     assert( pFrom->a[0].pUsing==0 );
85374   }
85375
85376   pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
85377   if( pSel ) pSel->selFlags |= SF_Materialize;
85378
85379   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
85380   sqlite3Select(pParse, pSel, &dest);
85381   sqlite3SelectDelete(db, pSel);
85382 }
85383 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
85384
85385 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
85386 /*
85387 ** Generate an expression tree to implement the WHERE, ORDER BY,
85388 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
85389 **
85390 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
85391 **                            \__________________________/
85392 **                               pLimitWhere (pInClause)
85393 */
85394 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
85395   Parse *pParse,               /* The parser context */
85396   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
85397   Expr *pWhere,                /* The WHERE clause.  May be null */
85398   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
85399   Expr *pLimit,                /* The LIMIT clause.  May be null */
85400   Expr *pOffset,               /* The OFFSET clause.  May be null */
85401   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
85402 ){
85403   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
85404   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
85405   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
85406   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
85407   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
85408   Select *pSelect = NULL;      /* Complete SELECT tree */
85409
85410   /* Check that there isn't an ORDER BY without a LIMIT clause.
85411   */
85412   if( pOrderBy && (pLimit == 0) ) {
85413     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
85414     goto limit_where_cleanup_2;
85415   }
85416
85417   /* We only need to generate a select expression if there
85418   ** is a limit/offset term to enforce.
85419   */
85420   if( pLimit == 0 ) {
85421     /* if pLimit is null, pOffset will always be null as well. */
85422     assert( pOffset == 0 );
85423     return pWhere;
85424   }
85425
85426   /* Generate a select expression tree to enforce the limit/offset 
85427   ** term for the DELETE or UPDATE statement.  For example:
85428   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85429   ** becomes:
85430   **   DELETE FROM table_a WHERE rowid IN ( 
85431   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85432   **   );
85433   */
85434
85435   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
85436   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
85437   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
85438   if( pEList == 0 ) goto limit_where_cleanup_2;
85439
85440   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
85441   ** and the SELECT subtree. */
85442   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
85443   if( pSelectSrc == 0 ) {
85444     sqlite3ExprListDelete(pParse->db, pEList);
85445     goto limit_where_cleanup_2;
85446   }
85447
85448   /* generate the SELECT expression tree. */
85449   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
85450                              pOrderBy,0,pLimit,pOffset);
85451   if( pSelect == 0 ) return 0;
85452
85453   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
85454   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
85455   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
85456   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
85457   if( pInClause == 0 ) goto limit_where_cleanup_1;
85458
85459   pInClause->x.pSelect = pSelect;
85460   pInClause->flags |= EP_xIsSelect;
85461   sqlite3ExprSetHeight(pParse, pInClause);
85462   return pInClause;
85463
85464   /* something went wrong. clean up anything allocated. */
85465 limit_where_cleanup_1:
85466   sqlite3SelectDelete(pParse->db, pSelect);
85467   return 0;
85468
85469 limit_where_cleanup_2:
85470   sqlite3ExprDelete(pParse->db, pWhere);
85471   sqlite3ExprListDelete(pParse->db, pOrderBy);
85472   sqlite3ExprDelete(pParse->db, pLimit);
85473   sqlite3ExprDelete(pParse->db, pOffset);
85474   return 0;
85475 }
85476 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
85477
85478 /*
85479 ** Generate code for a DELETE FROM statement.
85480 **
85481 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
85482 **                 \________/       \________________/
85483 **                  pTabList              pWhere
85484 */
85485 SQLITE_PRIVATE void sqlite3DeleteFrom(
85486   Parse *pParse,         /* The parser context */
85487   SrcList *pTabList,     /* The table from which we should delete things */
85488   Expr *pWhere           /* The WHERE clause.  May be null */
85489 ){
85490   Vdbe *v;               /* The virtual database engine */
85491   Table *pTab;           /* The table from which records will be deleted */
85492   const char *zDb;       /* Name of database holding pTab */
85493   int end, addr = 0;     /* A couple addresses of generated code */
85494   int i;                 /* Loop counter */
85495   WhereInfo *pWInfo;     /* Information about the WHERE clause */
85496   Index *pIdx;           /* For looping over indices of the table */
85497   int iCur;              /* VDBE Cursor number for pTab */
85498   sqlite3 *db;           /* Main database structure */
85499   AuthContext sContext;  /* Authorization context */
85500   NameContext sNC;       /* Name context to resolve expressions in */
85501   int iDb;               /* Database number */
85502   int memCnt = -1;       /* Memory cell used for change counting */
85503   int rcauth;            /* Value returned by authorization callback */
85504
85505 #ifndef SQLITE_OMIT_TRIGGER
85506   int isView;                  /* True if attempting to delete from a view */
85507   Trigger *pTrigger;           /* List of table triggers, if required */
85508 #endif
85509
85510   memset(&sContext, 0, sizeof(sContext));
85511   db = pParse->db;
85512   if( pParse->nErr || db->mallocFailed ){
85513     goto delete_from_cleanup;
85514   }
85515   assert( pTabList->nSrc==1 );
85516
85517   /* Locate the table which we want to delete.  This table has to be
85518   ** put in an SrcList structure because some of the subroutines we
85519   ** will be calling are designed to work with multiple tables and expect
85520   ** an SrcList* parameter instead of just a Table* parameter.
85521   */
85522   pTab = sqlite3SrcListLookup(pParse, pTabList);
85523   if( pTab==0 )  goto delete_from_cleanup;
85524
85525   /* Figure out if we have any triggers and if the table being
85526   ** deleted from is a view
85527   */
85528 #ifndef SQLITE_OMIT_TRIGGER
85529   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85530   isView = pTab->pSelect!=0;
85531 #else
85532 # define pTrigger 0
85533 # define isView 0
85534 #endif
85535 #ifdef SQLITE_OMIT_VIEW
85536 # undef isView
85537 # define isView 0
85538 #endif
85539
85540   /* If pTab is really a view, make sure it has been initialized.
85541   */
85542   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85543     goto delete_from_cleanup;
85544   }
85545
85546   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
85547     goto delete_from_cleanup;
85548   }
85549   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85550   assert( iDb<db->nDb );
85551   zDb = db->aDb[iDb].zName;
85552   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
85553   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
85554   if( rcauth==SQLITE_DENY ){
85555     goto delete_from_cleanup;
85556   }
85557   assert(!isView || pTrigger);
85558
85559   /* Assign  cursor number to the table and all its indices.
85560   */
85561   assert( pTabList->nSrc==1 );
85562   iCur = pTabList->a[0].iCursor = pParse->nTab++;
85563   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85564     pParse->nTab++;
85565   }
85566
85567   /* Start the view context
85568   */
85569   if( isView ){
85570     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
85571   }
85572
85573   /* Begin generating code.
85574   */
85575   v = sqlite3GetVdbe(pParse);
85576   if( v==0 ){
85577     goto delete_from_cleanup;
85578   }
85579   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
85580   sqlite3BeginWriteOperation(pParse, 1, iDb);
85581
85582   /* If we are trying to delete from a view, realize that view into
85583   ** a ephemeral table.
85584   */
85585 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85586   if( isView ){
85587     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
85588   }
85589 #endif
85590
85591   /* Resolve the column names in the WHERE clause.
85592   */
85593   memset(&sNC, 0, sizeof(sNC));
85594   sNC.pParse = pParse;
85595   sNC.pSrcList = pTabList;
85596   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
85597     goto delete_from_cleanup;
85598   }
85599
85600   /* Initialize the counter of the number of rows deleted, if
85601   ** we are counting rows.
85602   */
85603   if( db->flags & SQLITE_CountRows ){
85604     memCnt = ++pParse->nMem;
85605     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
85606   }
85607
85608 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
85609   /* Special case: A DELETE without a WHERE clause deletes everything.
85610   ** It is easier just to erase the whole table. Prior to version 3.6.5,
85611   ** this optimization caused the row change count (the value returned by 
85612   ** API function sqlite3_count_changes) to be set incorrectly.  */
85613   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
85614    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
85615   ){
85616     assert( !isView );
85617     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
85618                       pTab->zName, P4_STATIC);
85619     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85620       assert( pIdx->pSchema==pTab->pSchema );
85621       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
85622     }
85623   }else
85624 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
85625   /* The usual case: There is a WHERE clause so we have to scan through
85626   ** the table and pick which records to delete.
85627   */
85628   {
85629     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
85630     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
85631     int regRowid;                   /* Actual register containing rowids */
85632
85633     /* Collect rowids of every row to be deleted.
85634     */
85635     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
85636     pWInfo = sqlite3WhereBegin(
85637         pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
85638     );
85639     if( pWInfo==0 ) goto delete_from_cleanup;
85640     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
85641     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
85642     if( db->flags & SQLITE_CountRows ){
85643       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
85644     }
85645     sqlite3WhereEnd(pWInfo);
85646
85647     /* Delete every item whose key was written to the list during the
85648     ** database scan.  We have to delete items after the scan is complete
85649     ** because deleting an item can change the scan order.  */
85650     end = sqlite3VdbeMakeLabel(v);
85651
85652     /* Unless this is a view, open cursors for the table we are 
85653     ** deleting from and all its indices. If this is a view, then the
85654     ** only effect this statement has is to fire the INSTEAD OF 
85655     ** triggers.  */
85656     if( !isView ){
85657       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
85658     }
85659
85660     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
85661
85662     /* Delete the row */
85663 #ifndef SQLITE_OMIT_VIRTUALTABLE
85664     if( IsVirtual(pTab) ){
85665       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
85666       sqlite3VtabMakeWritable(pParse, pTab);
85667       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
85668       sqlite3VdbeChangeP5(v, OE_Abort);
85669       sqlite3MayAbort(pParse);
85670     }else
85671 #endif
85672     {
85673       int count = (pParse->nested==0);    /* True to count changes */
85674       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
85675     }
85676
85677     /* End of the delete loop */
85678     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
85679     sqlite3VdbeResolveLabel(v, end);
85680
85681     /* Close the cursors open on the table and its indexes. */
85682     if( !isView && !IsVirtual(pTab) ){
85683       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85684         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
85685       }
85686       sqlite3VdbeAddOp1(v, OP_Close, iCur);
85687     }
85688   }
85689
85690   /* Update the sqlite_sequence table by storing the content of the
85691   ** maximum rowid counter values recorded while inserting into
85692   ** autoincrement tables.
85693   */
85694   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85695     sqlite3AutoincrementEnd(pParse);
85696   }
85697
85698   /* Return the number of rows that were deleted. If this routine is 
85699   ** generating code because of a call to sqlite3NestedParse(), do not
85700   ** invoke the callback function.
85701   */
85702   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
85703     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
85704     sqlite3VdbeSetNumCols(v, 1);
85705     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
85706   }
85707
85708 delete_from_cleanup:
85709   sqlite3AuthContextPop(&sContext);
85710   sqlite3SrcListDelete(db, pTabList);
85711   sqlite3ExprDelete(db, pWhere);
85712   return;
85713 }
85714 /* Make sure "isView" and other macros defined above are undefined. Otherwise
85715 ** thely may interfere with compilation of other functions in this file
85716 ** (or in another file, if this file becomes part of the amalgamation).  */
85717 #ifdef isView
85718  #undef isView
85719 #endif
85720 #ifdef pTrigger
85721  #undef pTrigger
85722 #endif
85723
85724 /*
85725 ** This routine generates VDBE code that causes a single row of a
85726 ** single table to be deleted.
85727 **
85728 ** The VDBE must be in a particular state when this routine is called.
85729 ** These are the requirements:
85730 **
85731 **   1.  A read/write cursor pointing to pTab, the table containing the row
85732 **       to be deleted, must be opened as cursor number $iCur.
85733 **
85734 **   2.  Read/write cursors for all indices of pTab must be open as
85735 **       cursor number base+i for the i-th index.
85736 **
85737 **   3.  The record number of the row to be deleted must be stored in
85738 **       memory cell iRowid.
85739 **
85740 ** This routine generates code to remove both the table record and all 
85741 ** index entries that point to that record.
85742 */
85743 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
85744   Parse *pParse,     /* Parsing context */
85745   Table *pTab,       /* Table containing the row to be deleted */
85746   int iCur,          /* Cursor number for the table */
85747   int iRowid,        /* Memory cell that contains the rowid to delete */
85748   int count,         /* If non-zero, increment the row change counter */
85749   Trigger *pTrigger, /* List of triggers to (potentially) fire */
85750   int onconf         /* Default ON CONFLICT policy for triggers */
85751 ){
85752   Vdbe *v = pParse->pVdbe;        /* Vdbe */
85753   int iOld = 0;                   /* First register in OLD.* array */
85754   int iLabel;                     /* Label resolved to end of generated code */
85755
85756   /* Vdbe is guaranteed to have been allocated by this stage. */
85757   assert( v );
85758
85759   /* Seek cursor iCur to the row to delete. If this row no longer exists 
85760   ** (this can happen if a trigger program has already deleted it), do
85761   ** not attempt to delete it or fire any DELETE triggers.  */
85762   iLabel = sqlite3VdbeMakeLabel(v);
85763   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
85764  
85765   /* If there are any triggers to fire, allocate a range of registers to
85766   ** use for the old.* references in the triggers.  */
85767   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
85768     u32 mask;                     /* Mask of OLD.* columns in use */
85769     int iCol;                     /* Iterator used while populating OLD.* */
85770
85771     /* TODO: Could use temporary registers here. Also could attempt to
85772     ** avoid copying the contents of the rowid register.  */
85773     mask = sqlite3TriggerColmask(
85774         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
85775     );
85776     mask |= sqlite3FkOldmask(pParse, pTab);
85777     iOld = pParse->nMem+1;
85778     pParse->nMem += (1 + pTab->nCol);
85779
85780     /* Populate the OLD.* pseudo-table register array. These values will be 
85781     ** used by any BEFORE and AFTER triggers that exist.  */
85782     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
85783     for(iCol=0; iCol<pTab->nCol; iCol++){
85784       if( mask==0xffffffff || mask&(1<<iCol) ){
85785         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
85786       }
85787     }
85788
85789     /* Invoke BEFORE DELETE trigger programs. */
85790     sqlite3CodeRowTrigger(pParse, pTrigger, 
85791         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
85792     );
85793
85794     /* Seek the cursor to the row to be deleted again. It may be that
85795     ** the BEFORE triggers coded above have already removed the row
85796     ** being deleted. Do not attempt to delete the row a second time, and 
85797     ** do not fire AFTER triggers.  */
85798     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
85799
85800     /* Do FK processing. This call checks that any FK constraints that
85801     ** refer to this table (i.e. constraints attached to other tables) 
85802     ** are not violated by deleting this row.  */
85803     sqlite3FkCheck(pParse, pTab, iOld, 0);
85804   }
85805
85806   /* Delete the index and table entries. Skip this step if pTab is really
85807   ** a view (in which case the only effect of the DELETE statement is to
85808   ** fire the INSTEAD OF triggers).  */ 
85809   if( pTab->pSelect==0 ){
85810     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
85811     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
85812     if( count ){
85813       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
85814     }
85815   }
85816
85817   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
85818   ** handle rows (possibly in other tables) that refer via a foreign key
85819   ** to the row just deleted. */ 
85820   sqlite3FkActions(pParse, pTab, 0, iOld);
85821
85822   /* Invoke AFTER DELETE trigger programs. */
85823   sqlite3CodeRowTrigger(pParse, pTrigger, 
85824       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
85825   );
85826
85827   /* Jump here if the row had already been deleted before any BEFORE
85828   ** trigger programs were invoked. Or if a trigger program throws a 
85829   ** RAISE(IGNORE) exception.  */
85830   sqlite3VdbeResolveLabel(v, iLabel);
85831 }
85832
85833 /*
85834 ** This routine generates VDBE code that causes the deletion of all
85835 ** index entries associated with a single row of a single table.
85836 **
85837 ** The VDBE must be in a particular state when this routine is called.
85838 ** These are the requirements:
85839 **
85840 **   1.  A read/write cursor pointing to pTab, the table containing the row
85841 **       to be deleted, must be opened as cursor number "iCur".
85842 **
85843 **   2.  Read/write cursors for all indices of pTab must be open as
85844 **       cursor number iCur+i for the i-th index.
85845 **
85846 **   3.  The "iCur" cursor must be pointing to the row that is to be
85847 **       deleted.
85848 */
85849 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
85850   Parse *pParse,     /* Parsing and code generating context */
85851   Table *pTab,       /* Table containing the row to be deleted */
85852   int iCur,          /* Cursor number for the table */
85853   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
85854 ){
85855   int i;
85856   Index *pIdx;
85857   int r1;
85858
85859   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85860     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
85861     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
85862     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
85863   }
85864 }
85865
85866 /*
85867 ** Generate code that will assemble an index key and put it in register
85868 ** regOut.  The key with be for index pIdx which is an index on pTab.
85869 ** iCur is the index of a cursor open on the pTab table and pointing to
85870 ** the entry that needs indexing.
85871 **
85872 ** Return a register number which is the first in a block of
85873 ** registers that holds the elements of the index key.  The
85874 ** block of registers has already been deallocated by the time
85875 ** this routine returns.
85876 */
85877 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
85878   Parse *pParse,     /* Parsing context */
85879   Index *pIdx,       /* The index for which to generate a key */
85880   int iCur,          /* Cursor number for the pIdx->pTable table */
85881   int regOut,        /* Write the new index key to this register */
85882   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
85883 ){
85884   Vdbe *v = pParse->pVdbe;
85885   int j;
85886   Table *pTab = pIdx->pTable;
85887   int regBase;
85888   int nCol;
85889
85890   nCol = pIdx->nColumn;
85891   regBase = sqlite3GetTempRange(pParse, nCol+1);
85892   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
85893   for(j=0; j<nCol; j++){
85894     int idx = pIdx->aiColumn[j];
85895     if( idx==pTab->iPKey ){
85896       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
85897     }else{
85898       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
85899       sqlite3ColumnDefault(v, pTab, idx, -1);
85900     }
85901   }
85902   if( doMakeRec ){
85903     const char *zAff;
85904     if( pTab->pSelect
85905      || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
85906     ){
85907       zAff = 0;
85908     }else{
85909       zAff = sqlite3IndexAffinityStr(v, pIdx);
85910     }
85911     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
85912     sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
85913   }
85914   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
85915   return regBase;
85916 }
85917
85918 /************** End of delete.c **********************************************/
85919 /************** Begin file func.c ********************************************/
85920 /*
85921 ** 2002 February 23
85922 **
85923 ** The author disclaims copyright to this source code.  In place of
85924 ** a legal notice, here is a blessing:
85925 **
85926 **    May you do good and not evil.
85927 **    May you find forgiveness for yourself and forgive others.
85928 **    May you share freely, never taking more than you give.
85929 **
85930 *************************************************************************
85931 ** This file contains the C functions that implement various SQL
85932 ** functions of SQLite.  
85933 **
85934 ** There is only one exported symbol in this file - the function
85935 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
85936 ** All other code has file scope.
85937 */
85938 /* #include <stdlib.h> */
85939 /* #include <assert.h> */
85940
85941 /*
85942 ** Return the collating function associated with a function.
85943 */
85944 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
85945   return context->pColl;
85946 }
85947
85948 /*
85949 ** Indicate that the accumulator load should be skipped on this
85950 ** iteration of the aggregate loop.
85951 */
85952 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
85953   context->skipFlag = 1;
85954 }
85955
85956 /*
85957 ** Implementation of the non-aggregate min() and max() functions
85958 */
85959 static void minmaxFunc(
85960   sqlite3_context *context,
85961   int argc,
85962   sqlite3_value **argv
85963 ){
85964   int i;
85965   int mask;    /* 0 for min() or 0xffffffff for max() */
85966   int iBest;
85967   CollSeq *pColl;
85968
85969   assert( argc>1 );
85970   mask = sqlite3_user_data(context)==0 ? 0 : -1;
85971   pColl = sqlite3GetFuncCollSeq(context);
85972   assert( pColl );
85973   assert( mask==-1 || mask==0 );
85974   iBest = 0;
85975   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
85976   for(i=1; i<argc; i++){
85977     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
85978     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
85979       testcase( mask==0 );
85980       iBest = i;
85981     }
85982   }
85983   sqlite3_result_value(context, argv[iBest]);
85984 }
85985
85986 /*
85987 ** Return the type of the argument.
85988 */
85989 static void typeofFunc(
85990   sqlite3_context *context,
85991   int NotUsed,
85992   sqlite3_value **argv
85993 ){
85994   const char *z = 0;
85995   UNUSED_PARAMETER(NotUsed);
85996   switch( sqlite3_value_type(argv[0]) ){
85997     case SQLITE_INTEGER: z = "integer"; break;
85998     case SQLITE_TEXT:    z = "text";    break;
85999     case SQLITE_FLOAT:   z = "real";    break;
86000     case SQLITE_BLOB:    z = "blob";    break;
86001     default:             z = "null";    break;
86002   }
86003   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
86004 }
86005
86006
86007 /*
86008 ** Implementation of the length() function
86009 */
86010 static void lengthFunc(
86011   sqlite3_context *context,
86012   int argc,
86013   sqlite3_value **argv
86014 ){
86015   int len;
86016
86017   assert( argc==1 );
86018   UNUSED_PARAMETER(argc);
86019   switch( sqlite3_value_type(argv[0]) ){
86020     case SQLITE_BLOB:
86021     case SQLITE_INTEGER:
86022     case SQLITE_FLOAT: {
86023       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
86024       break;
86025     }
86026     case SQLITE_TEXT: {
86027       const unsigned char *z = sqlite3_value_text(argv[0]);
86028       if( z==0 ) return;
86029       len = 0;
86030       while( *z ){
86031         len++;
86032         SQLITE_SKIP_UTF8(z);
86033       }
86034       sqlite3_result_int(context, len);
86035       break;
86036     }
86037     default: {
86038       sqlite3_result_null(context);
86039       break;
86040     }
86041   }
86042 }
86043
86044 /*
86045 ** Implementation of the abs() function.
86046 **
86047 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
86048 ** the numeric argument X. 
86049 */
86050 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86051   assert( argc==1 );
86052   UNUSED_PARAMETER(argc);
86053   switch( sqlite3_value_type(argv[0]) ){
86054     case SQLITE_INTEGER: {
86055       i64 iVal = sqlite3_value_int64(argv[0]);
86056       if( iVal<0 ){
86057         if( (iVal<<1)==0 ){
86058           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
86059           ** abs(X) throws an integer overflow error since there is no
86060           ** equivalent positive 64-bit two complement value. */
86061           sqlite3_result_error(context, "integer overflow", -1);
86062           return;
86063         }
86064         iVal = -iVal;
86065       } 
86066       sqlite3_result_int64(context, iVal);
86067       break;
86068     }
86069     case SQLITE_NULL: {
86070       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
86071       sqlite3_result_null(context);
86072       break;
86073     }
86074     default: {
86075       /* Because sqlite3_value_double() returns 0.0 if the argument is not
86076       ** something that can be converted into a number, we have:
86077       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
86078       ** cannot be converted to a numeric value. 
86079       */
86080       double rVal = sqlite3_value_double(argv[0]);
86081       if( rVal<0 ) rVal = -rVal;
86082       sqlite3_result_double(context, rVal);
86083       break;
86084     }
86085   }
86086 }
86087
86088 /*
86089 ** Implementation of the instr() function.
86090 **
86091 ** instr(haystack,needle) finds the first occurrence of needle
86092 ** in haystack and returns the number of previous characters plus 1,
86093 ** or 0 if needle does not occur within haystack.
86094 **
86095 ** If both haystack and needle are BLOBs, then the result is one more than
86096 ** the number of bytes in haystack prior to the first occurrence of needle,
86097 ** or 0 if needle never occurs in haystack.
86098 */
86099 static void instrFunc(
86100   sqlite3_context *context,
86101   int argc,
86102   sqlite3_value **argv
86103 ){
86104   const unsigned char *zHaystack;
86105   const unsigned char *zNeedle;
86106   int nHaystack;
86107   int nNeedle;
86108   int typeHaystack, typeNeedle;
86109   int N = 1;
86110   int isText;
86111
86112   UNUSED_PARAMETER(argc);
86113   typeHaystack = sqlite3_value_type(argv[0]);
86114   typeNeedle = sqlite3_value_type(argv[1]);
86115   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
86116   nHaystack = sqlite3_value_bytes(argv[0]);
86117   nNeedle = sqlite3_value_bytes(argv[1]);
86118   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
86119     zHaystack = sqlite3_value_blob(argv[0]);
86120     zNeedle = sqlite3_value_blob(argv[1]);
86121     isText = 0;
86122   }else{
86123     zHaystack = sqlite3_value_text(argv[0]);
86124     zNeedle = sqlite3_value_text(argv[1]);
86125     isText = 1;
86126   }
86127   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
86128     N++;
86129     do{
86130       nHaystack--;
86131       zHaystack++;
86132     }while( isText && (zHaystack[0]&0xc0)==0x80 );
86133   }
86134   if( nNeedle>nHaystack ) N = 0;
86135   sqlite3_result_int(context, N);
86136 }
86137
86138 /*
86139 ** Implementation of the substr() function.
86140 **
86141 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
86142 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
86143 ** of x.  If x is text, then we actually count UTF-8 characters.
86144 ** If x is a blob, then we count bytes.
86145 **
86146 ** If p1 is negative, then we begin abs(p1) from the end of x[].
86147 **
86148 ** If p2 is negative, return the p2 characters preceeding p1.
86149 */
86150 static void substrFunc(
86151   sqlite3_context *context,
86152   int argc,
86153   sqlite3_value **argv
86154 ){
86155   const unsigned char *z;
86156   const unsigned char *z2;
86157   int len;
86158   int p0type;
86159   i64 p1, p2;
86160   int negP2 = 0;
86161
86162   assert( argc==3 || argc==2 );
86163   if( sqlite3_value_type(argv[1])==SQLITE_NULL
86164    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
86165   ){
86166     return;
86167   }
86168   p0type = sqlite3_value_type(argv[0]);
86169   p1 = sqlite3_value_int(argv[1]);
86170   if( p0type==SQLITE_BLOB ){
86171     len = sqlite3_value_bytes(argv[0]);
86172     z = sqlite3_value_blob(argv[0]);
86173     if( z==0 ) return;
86174     assert( len==sqlite3_value_bytes(argv[0]) );
86175   }else{
86176     z = sqlite3_value_text(argv[0]);
86177     if( z==0 ) return;
86178     len = 0;
86179     if( p1<0 ){
86180       for(z2=z; *z2; len++){
86181         SQLITE_SKIP_UTF8(z2);
86182       }
86183     }
86184   }
86185   if( argc==3 ){
86186     p2 = sqlite3_value_int(argv[2]);
86187     if( p2<0 ){
86188       p2 = -p2;
86189       negP2 = 1;
86190     }
86191   }else{
86192     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
86193   }
86194   if( p1<0 ){
86195     p1 += len;
86196     if( p1<0 ){
86197       p2 += p1;
86198       if( p2<0 ) p2 = 0;
86199       p1 = 0;
86200     }
86201   }else if( p1>0 ){
86202     p1--;
86203   }else if( p2>0 ){
86204     p2--;
86205   }
86206   if( negP2 ){
86207     p1 -= p2;
86208     if( p1<0 ){
86209       p2 += p1;
86210       p1 = 0;
86211     }
86212   }
86213   assert( p1>=0 && p2>=0 );
86214   if( p0type!=SQLITE_BLOB ){
86215     while( *z && p1 ){
86216       SQLITE_SKIP_UTF8(z);
86217       p1--;
86218     }
86219     for(z2=z; *z2 && p2; p2--){
86220       SQLITE_SKIP_UTF8(z2);
86221     }
86222     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
86223   }else{
86224     if( p1+p2>len ){
86225       p2 = len-p1;
86226       if( p2<0 ) p2 = 0;
86227     }
86228     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
86229   }
86230 }
86231
86232 /*
86233 ** Implementation of the round() function
86234 */
86235 #ifndef SQLITE_OMIT_FLOATING_POINT
86236 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86237   int n = 0;
86238   double r;
86239   char *zBuf;
86240   assert( argc==1 || argc==2 );
86241   if( argc==2 ){
86242     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
86243     n = sqlite3_value_int(argv[1]);
86244     if( n>30 ) n = 30;
86245     if( n<0 ) n = 0;
86246   }
86247   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
86248   r = sqlite3_value_double(argv[0]);
86249   /* If Y==0 and X will fit in a 64-bit int,
86250   ** handle the rounding directly,
86251   ** otherwise use printf.
86252   */
86253   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
86254     r = (double)((sqlite_int64)(r+0.5));
86255   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
86256     r = -(double)((sqlite_int64)((-r)+0.5));
86257   }else{
86258     zBuf = sqlite3_mprintf("%.*f",n,r);
86259     if( zBuf==0 ){
86260       sqlite3_result_error_nomem(context);
86261       return;
86262     }
86263     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
86264     sqlite3_free(zBuf);
86265   }
86266   sqlite3_result_double(context, r);
86267 }
86268 #endif
86269
86270 /*
86271 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
86272 ** allocation fails, call sqlite3_result_error_nomem() to notify
86273 ** the database handle that malloc() has failed and return NULL.
86274 ** If nByte is larger than the maximum string or blob length, then
86275 ** raise an SQLITE_TOOBIG exception and return NULL.
86276 */
86277 static void *contextMalloc(sqlite3_context *context, i64 nByte){
86278   char *z;
86279   sqlite3 *db = sqlite3_context_db_handle(context);
86280   assert( nByte>0 );
86281   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
86282   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
86283   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
86284     sqlite3_result_error_toobig(context);
86285     z = 0;
86286   }else{
86287     z = sqlite3Malloc((int)nByte);
86288     if( !z ){
86289       sqlite3_result_error_nomem(context);
86290     }
86291   }
86292   return z;
86293 }
86294
86295 /*
86296 ** Implementation of the upper() and lower() SQL functions.
86297 */
86298 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86299   char *z1;
86300   const char *z2;
86301   int i, n;
86302   UNUSED_PARAMETER(argc);
86303   z2 = (char*)sqlite3_value_text(argv[0]);
86304   n = sqlite3_value_bytes(argv[0]);
86305   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86306   assert( z2==(char*)sqlite3_value_text(argv[0]) );
86307   if( z2 ){
86308     z1 = contextMalloc(context, ((i64)n)+1);
86309     if( z1 ){
86310       for(i=0; i<n; i++){
86311         z1[i] = (char)sqlite3Toupper(z2[i]);
86312       }
86313       sqlite3_result_text(context, z1, n, sqlite3_free);
86314     }
86315   }
86316 }
86317 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86318   char *z1;
86319   const char *z2;
86320   int i, n;
86321   UNUSED_PARAMETER(argc);
86322   z2 = (char*)sqlite3_value_text(argv[0]);
86323   n = sqlite3_value_bytes(argv[0]);
86324   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86325   assert( z2==(char*)sqlite3_value_text(argv[0]) );
86326   if( z2 ){
86327     z1 = contextMalloc(context, ((i64)n)+1);
86328     if( z1 ){
86329       for(i=0; i<n; i++){
86330         z1[i] = sqlite3Tolower(z2[i]);
86331       }
86332       sqlite3_result_text(context, z1, n, sqlite3_free);
86333     }
86334   }
86335 }
86336
86337 /*
86338 ** The COALESCE() and IFNULL() functions are implemented as VDBE code so
86339 ** that unused argument values do not have to be computed.  However, we
86340 ** still need some kind of function implementation for this routines in
86341 ** the function table.  That function implementation will never be called
86342 ** so it doesn't matter what the implementation is.  We might as well use
86343 ** the "version()" function as a substitute.
86344 */
86345 #define ifnullFunc versionFunc   /* Substitute function - never called */
86346
86347 /*
86348 ** Implementation of random().  Return a random integer.  
86349 */
86350 static void randomFunc(
86351   sqlite3_context *context,
86352   int NotUsed,
86353   sqlite3_value **NotUsed2
86354 ){
86355   sqlite_int64 r;
86356   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86357   sqlite3_randomness(sizeof(r), &r);
86358   if( r<0 ){
86359     /* We need to prevent a random number of 0x8000000000000000 
86360     ** (or -9223372036854775808) since when you do abs() of that
86361     ** number of you get the same value back again.  To do this
86362     ** in a way that is testable, mask the sign bit off of negative
86363     ** values, resulting in a positive value.  Then take the 
86364     ** 2s complement of that positive value.  The end result can
86365     ** therefore be no less than -9223372036854775807.
86366     */
86367     r = -(r & LARGEST_INT64);
86368   }
86369   sqlite3_result_int64(context, r);
86370 }
86371
86372 /*
86373 ** Implementation of randomblob(N).  Return a random blob
86374 ** that is N bytes long.
86375 */
86376 static void randomBlob(
86377   sqlite3_context *context,
86378   int argc,
86379   sqlite3_value **argv
86380 ){
86381   int n;
86382   unsigned char *p;
86383   assert( argc==1 );
86384   UNUSED_PARAMETER(argc);
86385   n = sqlite3_value_int(argv[0]);
86386   if( n<1 ){
86387     n = 1;
86388   }
86389   p = contextMalloc(context, n);
86390   if( p ){
86391     sqlite3_randomness(n, p);
86392     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
86393   }
86394 }
86395
86396 /*
86397 ** Implementation of the last_insert_rowid() SQL function.  The return
86398 ** value is the same as the sqlite3_last_insert_rowid() API function.
86399 */
86400 static void last_insert_rowid(
86401   sqlite3_context *context, 
86402   int NotUsed, 
86403   sqlite3_value **NotUsed2
86404 ){
86405   sqlite3 *db = sqlite3_context_db_handle(context);
86406   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86407   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
86408   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
86409   ** function. */
86410   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
86411 }
86412
86413 /*
86414 ** Implementation of the changes() SQL function.
86415 **
86416 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
86417 ** around the sqlite3_changes() C/C++ function and hence follows the same
86418 ** rules for counting changes.
86419 */
86420 static void changes(
86421   sqlite3_context *context,
86422   int NotUsed,
86423   sqlite3_value **NotUsed2
86424 ){
86425   sqlite3 *db = sqlite3_context_db_handle(context);
86426   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86427   sqlite3_result_int(context, sqlite3_changes(db));
86428 }
86429
86430 /*
86431 ** Implementation of the total_changes() SQL function.  The return value is
86432 ** the same as the sqlite3_total_changes() API function.
86433 */
86434 static void total_changes(
86435   sqlite3_context *context,
86436   int NotUsed,
86437   sqlite3_value **NotUsed2
86438 ){
86439   sqlite3 *db = sqlite3_context_db_handle(context);
86440   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86441   /* IMP: R-52756-41993 This function is a wrapper around the
86442   ** sqlite3_total_changes() C/C++ interface. */
86443   sqlite3_result_int(context, sqlite3_total_changes(db));
86444 }
86445
86446 /*
86447 ** A structure defining how to do GLOB-style comparisons.
86448 */
86449 struct compareInfo {
86450   u8 matchAll;
86451   u8 matchOne;
86452   u8 matchSet;
86453   u8 noCase;
86454 };
86455
86456 /*
86457 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
86458 ** character is exactly one byte in size.  Also, all characters are
86459 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
86460 ** whereas only characters less than 0x80 do in ASCII.
86461 */
86462 #if defined(SQLITE_EBCDIC)
86463 # define sqlite3Utf8Read(A)    (*((*A)++))
86464 # define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
86465 #else
86466 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
86467 #endif
86468
86469 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
86470 /* The correct SQL-92 behavior is for the LIKE operator to ignore
86471 ** case.  Thus  'a' LIKE 'A' would be true. */
86472 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
86473 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
86474 ** is case sensitive causing 'a' LIKE 'A' to be false */
86475 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
86476
86477 /*
86478 ** Compare two UTF-8 strings for equality where the first string can
86479 ** potentially be a "glob" expression.  Return true (1) if they
86480 ** are the same and false (0) if they are different.
86481 **
86482 ** Globbing rules:
86483 **
86484 **      '*'       Matches any sequence of zero or more characters.
86485 **
86486 **      '?'       Matches exactly one character.
86487 **
86488 **     [...]      Matches one character from the enclosed list of
86489 **                characters.
86490 **
86491 **     [^...]     Matches one character not in the enclosed list.
86492 **
86493 ** With the [...] and [^...] matching, a ']' character can be included
86494 ** in the list by making it the first character after '[' or '^'.  A
86495 ** range of characters can be specified using '-'.  Example:
86496 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
86497 ** it the last character in the list.
86498 **
86499 ** This routine is usually quick, but can be N**2 in the worst case.
86500 **
86501 ** Hints: to match '*' or '?', put them in "[]".  Like this:
86502 **
86503 **         abc[*]xyz        Matches "abc*xyz" only
86504 */
86505 static int patternCompare(
86506   const u8 *zPattern,              /* The glob pattern */
86507   const u8 *zString,               /* The string to compare against the glob */
86508   const struct compareInfo *pInfo, /* Information about how to do the compare */
86509   u32 esc                          /* The escape character */
86510 ){
86511   u32 c, c2;
86512   int invert;
86513   int seen;
86514   u8 matchOne = pInfo->matchOne;
86515   u8 matchAll = pInfo->matchAll;
86516   u8 matchSet = pInfo->matchSet;
86517   u8 noCase = pInfo->noCase; 
86518   int prevEscape = 0;     /* True if the previous character was 'escape' */
86519
86520   while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
86521     if( c==matchAll && !prevEscape ){
86522       while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
86523                || c == matchOne ){
86524         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
86525           return 0;
86526         }
86527       }
86528       if( c==0 ){
86529         return 1;
86530       }else if( c==esc ){
86531         c = sqlite3Utf8Read(&zPattern);
86532         if( c==0 ){
86533           return 0;
86534         }
86535       }else if( c==matchSet ){
86536         assert( esc==0 );         /* This is GLOB, not LIKE */
86537         assert( matchSet<0x80 );  /* '[' is a single-byte character */
86538         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
86539           SQLITE_SKIP_UTF8(zString);
86540         }
86541         return *zString!=0;
86542       }
86543       while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
86544         if( noCase ){
86545           GlogUpperToLower(c2);
86546           GlogUpperToLower(c);
86547           while( c2 != 0 && c2 != c ){
86548             c2 = sqlite3Utf8Read(&zString);
86549             GlogUpperToLower(c2);
86550           }
86551         }else{
86552           while( c2 != 0 && c2 != c ){
86553             c2 = sqlite3Utf8Read(&zString);
86554           }
86555         }
86556         if( c2==0 ) return 0;
86557         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
86558       }
86559       return 0;
86560     }else if( c==matchOne && !prevEscape ){
86561       if( sqlite3Utf8Read(&zString)==0 ){
86562         return 0;
86563       }
86564     }else if( c==matchSet ){
86565       u32 prior_c = 0;
86566       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
86567       seen = 0;
86568       invert = 0;
86569       c = sqlite3Utf8Read(&zString);
86570       if( c==0 ) return 0;
86571       c2 = sqlite3Utf8Read(&zPattern);
86572       if( c2=='^' ){
86573         invert = 1;
86574         c2 = sqlite3Utf8Read(&zPattern);
86575       }
86576       if( c2==']' ){
86577         if( c==']' ) seen = 1;
86578         c2 = sqlite3Utf8Read(&zPattern);
86579       }
86580       while( c2 && c2!=']' ){
86581         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
86582           c2 = sqlite3Utf8Read(&zPattern);
86583           if( c>=prior_c && c<=c2 ) seen = 1;
86584           prior_c = 0;
86585         }else{
86586           if( c==c2 ){
86587             seen = 1;
86588           }
86589           prior_c = c2;
86590         }
86591         c2 = sqlite3Utf8Read(&zPattern);
86592       }
86593       if( c2==0 || (seen ^ invert)==0 ){
86594         return 0;
86595       }
86596     }else if( esc==c && !prevEscape ){
86597       prevEscape = 1;
86598     }else{
86599       c2 = sqlite3Utf8Read(&zString);
86600       if( noCase ){
86601         GlogUpperToLower(c);
86602         GlogUpperToLower(c2);
86603       }
86604       if( c!=c2 ){
86605         return 0;
86606       }
86607       prevEscape = 0;
86608     }
86609   }
86610   return *zString==0;
86611 }
86612
86613 /*
86614 ** Count the number of times that the LIKE operator (or GLOB which is
86615 ** just a variation of LIKE) gets called.  This is used for testing
86616 ** only.
86617 */
86618 #ifdef SQLITE_TEST
86619 SQLITE_API int sqlite3_like_count = 0;
86620 #endif
86621
86622
86623 /*
86624 ** Implementation of the like() SQL function.  This function implements
86625 ** the build-in LIKE operator.  The first argument to the function is the
86626 ** pattern and the second argument is the string.  So, the SQL statements:
86627 **
86628 **       A LIKE B
86629 **
86630 ** is implemented as like(B,A).
86631 **
86632 ** This same function (with a different compareInfo structure) computes
86633 ** the GLOB operator.
86634 */
86635 static void likeFunc(
86636   sqlite3_context *context, 
86637   int argc, 
86638   sqlite3_value **argv
86639 ){
86640   const unsigned char *zA, *zB;
86641   u32 escape = 0;
86642   int nPat;
86643   sqlite3 *db = sqlite3_context_db_handle(context);
86644
86645   zB = sqlite3_value_text(argv[0]);
86646   zA = sqlite3_value_text(argv[1]);
86647
86648   /* Limit the length of the LIKE or GLOB pattern to avoid problems
86649   ** of deep recursion and N*N behavior in patternCompare().
86650   */
86651   nPat = sqlite3_value_bytes(argv[0]);
86652   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
86653   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
86654   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
86655     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
86656     return;
86657   }
86658   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
86659
86660   if( argc==3 ){
86661     /* The escape character string must consist of a single UTF-8 character.
86662     ** Otherwise, return an error.
86663     */
86664     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
86665     if( zEsc==0 ) return;
86666     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
86667       sqlite3_result_error(context, 
86668           "ESCAPE expression must be a single character", -1);
86669       return;
86670     }
86671     escape = sqlite3Utf8Read(&zEsc);
86672   }
86673   if( zA && zB ){
86674     struct compareInfo *pInfo = sqlite3_user_data(context);
86675 #ifdef SQLITE_TEST
86676     sqlite3_like_count++;
86677 #endif
86678     
86679     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
86680   }
86681 }
86682
86683 /*
86684 ** Implementation of the NULLIF(x,y) function.  The result is the first
86685 ** argument if the arguments are different.  The result is NULL if the
86686 ** arguments are equal to each other.
86687 */
86688 static void nullifFunc(
86689   sqlite3_context *context,
86690   int NotUsed,
86691   sqlite3_value **argv
86692 ){
86693   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
86694   UNUSED_PARAMETER(NotUsed);
86695   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
86696     sqlite3_result_value(context, argv[0]);
86697   }
86698 }
86699
86700 /*
86701 ** Implementation of the sqlite_version() function.  The result is the version
86702 ** of the SQLite library that is running.
86703 */
86704 static void versionFunc(
86705   sqlite3_context *context,
86706   int NotUsed,
86707   sqlite3_value **NotUsed2
86708 ){
86709   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86710   /* IMP: R-48699-48617 This function is an SQL wrapper around the
86711   ** sqlite3_libversion() C-interface. */
86712   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
86713 }
86714
86715 /*
86716 ** Implementation of the sqlite_source_id() function. The result is a string
86717 ** that identifies the particular version of the source code used to build
86718 ** SQLite.
86719 */
86720 static void sourceidFunc(
86721   sqlite3_context *context,
86722   int NotUsed,
86723   sqlite3_value **NotUsed2
86724 ){
86725   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86726   /* IMP: R-24470-31136 This function is an SQL wrapper around the
86727   ** sqlite3_sourceid() C interface. */
86728   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
86729 }
86730
86731 /*
86732 ** Implementation of the sqlite_log() function.  This is a wrapper around
86733 ** sqlite3_log().  The return value is NULL.  The function exists purely for
86734 ** its side-effects.
86735 */
86736 static void errlogFunc(
86737   sqlite3_context *context,
86738   int argc,
86739   sqlite3_value **argv
86740 ){
86741   UNUSED_PARAMETER(argc);
86742   UNUSED_PARAMETER(context);
86743   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
86744 }
86745
86746 /*
86747 ** Implementation of the sqlite_compileoption_used() function.
86748 ** The result is an integer that identifies if the compiler option
86749 ** was used to build SQLite.
86750 */
86751 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86752 static void compileoptionusedFunc(
86753   sqlite3_context *context,
86754   int argc,
86755   sqlite3_value **argv
86756 ){
86757   const char *zOptName;
86758   assert( argc==1 );
86759   UNUSED_PARAMETER(argc);
86760   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
86761   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
86762   ** function.
86763   */
86764   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
86765     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
86766   }
86767 }
86768 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86769
86770 /*
86771 ** Implementation of the sqlite_compileoption_get() function. 
86772 ** The result is a string that identifies the compiler options 
86773 ** used to build SQLite.
86774 */
86775 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86776 static void compileoptiongetFunc(
86777   sqlite3_context *context,
86778   int argc,
86779   sqlite3_value **argv
86780 ){
86781   int n;
86782   assert( argc==1 );
86783   UNUSED_PARAMETER(argc);
86784   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
86785   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
86786   */
86787   n = sqlite3_value_int(argv[0]);
86788   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
86789 }
86790 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86791
86792 /* Array for converting from half-bytes (nybbles) into ASCII hex
86793 ** digits. */
86794 static const char hexdigits[] = {
86795   '0', '1', '2', '3', '4', '5', '6', '7',
86796   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
86797 };
86798
86799 /*
86800 ** EXPERIMENTAL - This is not an official function.  The interface may
86801 ** change.  This function may disappear.  Do not write code that depends
86802 ** on this function.
86803 **
86804 ** Implementation of the QUOTE() function.  This function takes a single
86805 ** argument.  If the argument is numeric, the return value is the same as
86806 ** the argument.  If the argument is NULL, the return value is the string
86807 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
86808 ** single-quote escapes.
86809 */
86810 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86811   assert( argc==1 );
86812   UNUSED_PARAMETER(argc);
86813   switch( sqlite3_value_type(argv[0]) ){
86814     case SQLITE_FLOAT: {
86815       double r1, r2;
86816       char zBuf[50];
86817       r1 = sqlite3_value_double(argv[0]);
86818       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
86819       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
86820       if( r1!=r2 ){
86821         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
86822       }
86823       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
86824       break;
86825     }
86826     case SQLITE_INTEGER: {
86827       sqlite3_result_value(context, argv[0]);
86828       break;
86829     }
86830     case SQLITE_BLOB: {
86831       char *zText = 0;
86832       char const *zBlob = sqlite3_value_blob(argv[0]);
86833       int nBlob = sqlite3_value_bytes(argv[0]);
86834       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
86835       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
86836       if( zText ){
86837         int i;
86838         for(i=0; i<nBlob; i++){
86839           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
86840           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
86841         }
86842         zText[(nBlob*2)+2] = '\'';
86843         zText[(nBlob*2)+3] = '\0';
86844         zText[0] = 'X';
86845         zText[1] = '\'';
86846         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
86847         sqlite3_free(zText);
86848       }
86849       break;
86850     }
86851     case SQLITE_TEXT: {
86852       int i,j;
86853       u64 n;
86854       const unsigned char *zArg = sqlite3_value_text(argv[0]);
86855       char *z;
86856
86857       if( zArg==0 ) return;
86858       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
86859       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
86860       if( z ){
86861         z[0] = '\'';
86862         for(i=0, j=1; zArg[i]; i++){
86863           z[j++] = zArg[i];
86864           if( zArg[i]=='\'' ){
86865             z[j++] = '\'';
86866           }
86867         }
86868         z[j++] = '\'';
86869         z[j] = 0;
86870         sqlite3_result_text(context, z, j, sqlite3_free);
86871       }
86872       break;
86873     }
86874     default: {
86875       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
86876       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
86877       break;
86878     }
86879   }
86880 }
86881
86882 /*
86883 ** The unicode() function.  Return the integer unicode code-point value
86884 ** for the first character of the input string. 
86885 */
86886 static void unicodeFunc(
86887   sqlite3_context *context,
86888   int argc,
86889   sqlite3_value **argv
86890 ){
86891   const unsigned char *z = sqlite3_value_text(argv[0]);
86892   (void)argc;
86893   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
86894 }
86895
86896 /*
86897 ** The char() function takes zero or more arguments, each of which is
86898 ** an integer.  It constructs a string where each character of the string
86899 ** is the unicode character for the corresponding integer argument.
86900 */
86901 static void charFunc(
86902   sqlite3_context *context,
86903   int argc,
86904   sqlite3_value **argv
86905 ){
86906   unsigned char *z, *zOut;
86907   int i;
86908   zOut = z = sqlite3_malloc( argc*4 );
86909   if( z==0 ){
86910     sqlite3_result_error_nomem(context);
86911     return;
86912   }
86913   for(i=0; i<argc; i++){
86914     sqlite3_int64 x;
86915     unsigned c;
86916     x = sqlite3_value_int64(argv[i]);
86917     if( x<0 || x>0x10ffff ) x = 0xfffd;
86918     c = (unsigned)(x & 0x1fffff);
86919     if( c<0x00080 ){
86920       *zOut++ = (u8)(c&0xFF);
86921     }else if( c<0x00800 ){
86922       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
86923       *zOut++ = 0x80 + (u8)(c & 0x3F);
86924     }else if( c<0x10000 ){
86925       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
86926       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
86927       *zOut++ = 0x80 + (u8)(c & 0x3F);
86928     }else{
86929       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
86930       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
86931       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
86932       *zOut++ = 0x80 + (u8)(c & 0x3F);
86933     }                                                    \
86934   }
86935   sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
86936 }
86937
86938 /*
86939 ** The hex() function.  Interpret the argument as a blob.  Return
86940 ** a hexadecimal rendering as text.
86941 */
86942 static void hexFunc(
86943   sqlite3_context *context,
86944   int argc,
86945   sqlite3_value **argv
86946 ){
86947   int i, n;
86948   const unsigned char *pBlob;
86949   char *zHex, *z;
86950   assert( argc==1 );
86951   UNUSED_PARAMETER(argc);
86952   pBlob = sqlite3_value_blob(argv[0]);
86953   n = sqlite3_value_bytes(argv[0]);
86954   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
86955   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
86956   if( zHex ){
86957     for(i=0; i<n; i++, pBlob++){
86958       unsigned char c = *pBlob;
86959       *(z++) = hexdigits[(c>>4)&0xf];
86960       *(z++) = hexdigits[c&0xf];
86961     }
86962     *z = 0;
86963     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
86964   }
86965 }
86966
86967 /*
86968 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
86969 */
86970 static void zeroblobFunc(
86971   sqlite3_context *context,
86972   int argc,
86973   sqlite3_value **argv
86974 ){
86975   i64 n;
86976   sqlite3 *db = sqlite3_context_db_handle(context);
86977   assert( argc==1 );
86978   UNUSED_PARAMETER(argc);
86979   n = sqlite3_value_int64(argv[0]);
86980   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
86981   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
86982   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
86983     sqlite3_result_error_toobig(context);
86984   }else{
86985     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
86986   }
86987 }
86988
86989 /*
86990 ** The replace() function.  Three arguments are all strings: call
86991 ** them A, B, and C. The result is also a string which is derived
86992 ** from A by replacing every occurance of B with C.  The match
86993 ** must be exact.  Collating sequences are not used.
86994 */
86995 static void replaceFunc(
86996   sqlite3_context *context,
86997   int argc,
86998   sqlite3_value **argv
86999 ){
87000   const unsigned char *zStr;        /* The input string A */
87001   const unsigned char *zPattern;    /* The pattern string B */
87002   const unsigned char *zRep;        /* The replacement string C */
87003   unsigned char *zOut;              /* The output */
87004   int nStr;                /* Size of zStr */
87005   int nPattern;            /* Size of zPattern */
87006   int nRep;                /* Size of zRep */
87007   i64 nOut;                /* Maximum size of zOut */
87008   int loopLimit;           /* Last zStr[] that might match zPattern[] */
87009   int i, j;                /* Loop counters */
87010
87011   assert( argc==3 );
87012   UNUSED_PARAMETER(argc);
87013   zStr = sqlite3_value_text(argv[0]);
87014   if( zStr==0 ) return;
87015   nStr = sqlite3_value_bytes(argv[0]);
87016   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
87017   zPattern = sqlite3_value_text(argv[1]);
87018   if( zPattern==0 ){
87019     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
87020             || sqlite3_context_db_handle(context)->mallocFailed );
87021     return;
87022   }
87023   if( zPattern[0]==0 ){
87024     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
87025     sqlite3_result_value(context, argv[0]);
87026     return;
87027   }
87028   nPattern = sqlite3_value_bytes(argv[1]);
87029   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
87030   zRep = sqlite3_value_text(argv[2]);
87031   if( zRep==0 ) return;
87032   nRep = sqlite3_value_bytes(argv[2]);
87033   assert( zRep==sqlite3_value_text(argv[2]) );
87034   nOut = nStr + 1;
87035   assert( nOut<SQLITE_MAX_LENGTH );
87036   zOut = contextMalloc(context, (i64)nOut);
87037   if( zOut==0 ){
87038     return;
87039   }
87040   loopLimit = nStr - nPattern;  
87041   for(i=j=0; i<=loopLimit; i++){
87042     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
87043       zOut[j++] = zStr[i];
87044     }else{
87045       u8 *zOld;
87046       sqlite3 *db = sqlite3_context_db_handle(context);
87047       nOut += nRep - nPattern;
87048       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
87049       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
87050       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
87051         sqlite3_result_error_toobig(context);
87052         sqlite3_free(zOut);
87053         return;
87054       }
87055       zOld = zOut;
87056       zOut = sqlite3_realloc(zOut, (int)nOut);
87057       if( zOut==0 ){
87058         sqlite3_result_error_nomem(context);
87059         sqlite3_free(zOld);
87060         return;
87061       }
87062       memcpy(&zOut[j], zRep, nRep);
87063       j += nRep;
87064       i += nPattern-1;
87065     }
87066   }
87067   assert( j+nStr-i+1==nOut );
87068   memcpy(&zOut[j], &zStr[i], nStr-i);
87069   j += nStr - i;
87070   assert( j<=nOut );
87071   zOut[j] = 0;
87072   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
87073 }
87074
87075 /*
87076 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
87077 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
87078 */
87079 static void trimFunc(
87080   sqlite3_context *context,
87081   int argc,
87082   sqlite3_value **argv
87083 ){
87084   const unsigned char *zIn;         /* Input string */
87085   const unsigned char *zCharSet;    /* Set of characters to trim */
87086   int nIn;                          /* Number of bytes in input */
87087   int flags;                        /* 1: trimleft  2: trimright  3: trim */
87088   int i;                            /* Loop counter */
87089   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
87090   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
87091   int nChar;                        /* Number of characters in zCharSet */
87092
87093   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
87094     return;
87095   }
87096   zIn = sqlite3_value_text(argv[0]);
87097   if( zIn==0 ) return;
87098   nIn = sqlite3_value_bytes(argv[0]);
87099   assert( zIn==sqlite3_value_text(argv[0]) );
87100   if( argc==1 ){
87101     static const unsigned char lenOne[] = { 1 };
87102     static unsigned char * const azOne[] = { (u8*)" " };
87103     nChar = 1;
87104     aLen = (u8*)lenOne;
87105     azChar = (unsigned char **)azOne;
87106     zCharSet = 0;
87107   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
87108     return;
87109   }else{
87110     const unsigned char *z;
87111     for(z=zCharSet, nChar=0; *z; nChar++){
87112       SQLITE_SKIP_UTF8(z);
87113     }
87114     if( nChar>0 ){
87115       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
87116       if( azChar==0 ){
87117         return;
87118       }
87119       aLen = (unsigned char*)&azChar[nChar];
87120       for(z=zCharSet, nChar=0; *z; nChar++){
87121         azChar[nChar] = (unsigned char *)z;
87122         SQLITE_SKIP_UTF8(z);
87123         aLen[nChar] = (u8)(z - azChar[nChar]);
87124       }
87125     }
87126   }
87127   if( nChar>0 ){
87128     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
87129     if( flags & 1 ){
87130       while( nIn>0 ){
87131         int len = 0;
87132         for(i=0; i<nChar; i++){
87133           len = aLen[i];
87134           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
87135         }
87136         if( i>=nChar ) break;
87137         zIn += len;
87138         nIn -= len;
87139       }
87140     }
87141     if( flags & 2 ){
87142       while( nIn>0 ){
87143         int len = 0;
87144         for(i=0; i<nChar; i++){
87145           len = aLen[i];
87146           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
87147         }
87148         if( i>=nChar ) break;
87149         nIn -= len;
87150       }
87151     }
87152     if( zCharSet ){
87153       sqlite3_free(azChar);
87154     }
87155   }
87156   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
87157 }
87158
87159
87160 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
87161 ** is only available if the SQLITE_SOUNDEX compile-time option is used
87162 ** when SQLite is built.
87163 */
87164 #ifdef SQLITE_SOUNDEX
87165 /*
87166 ** Compute the soundex encoding of a word.
87167 **
87168 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
87169 ** soundex encoding of the string X. 
87170 */
87171 static void soundexFunc(
87172   sqlite3_context *context,
87173   int argc,
87174   sqlite3_value **argv
87175 ){
87176   char zResult[8];
87177   const u8 *zIn;
87178   int i, j;
87179   static const unsigned char iCode[] = {
87180     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87181     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87182     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87183     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87184     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
87185     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
87186     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
87187     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
87188   };
87189   assert( argc==1 );
87190   zIn = (u8*)sqlite3_value_text(argv[0]);
87191   if( zIn==0 ) zIn = (u8*)"";
87192   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
87193   if( zIn[i] ){
87194     u8 prevcode = iCode[zIn[i]&0x7f];
87195     zResult[0] = sqlite3Toupper(zIn[i]);
87196     for(j=1; j<4 && zIn[i]; i++){
87197       int code = iCode[zIn[i]&0x7f];
87198       if( code>0 ){
87199         if( code!=prevcode ){
87200           prevcode = code;
87201           zResult[j++] = code + '0';
87202         }
87203       }else{
87204         prevcode = 0;
87205       }
87206     }
87207     while( j<4 ){
87208       zResult[j++] = '0';
87209     }
87210     zResult[j] = 0;
87211     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
87212   }else{
87213     /* IMP: R-64894-50321 The string "?000" is returned if the argument
87214     ** is NULL or contains no ASCII alphabetic characters. */
87215     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
87216   }
87217 }
87218 #endif /* SQLITE_SOUNDEX */
87219
87220 #ifndef SQLITE_OMIT_LOAD_EXTENSION
87221 /*
87222 ** A function that loads a shared-library extension then returns NULL.
87223 */
87224 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
87225   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
87226   const char *zProc;
87227   sqlite3 *db = sqlite3_context_db_handle(context);
87228   char *zErrMsg = 0;
87229
87230   if( argc==2 ){
87231     zProc = (const char *)sqlite3_value_text(argv[1]);
87232   }else{
87233     zProc = 0;
87234   }
87235   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
87236     sqlite3_result_error(context, zErrMsg, -1);
87237     sqlite3_free(zErrMsg);
87238   }
87239 }
87240 #endif
87241
87242
87243 /*
87244 ** An instance of the following structure holds the context of a
87245 ** sum() or avg() aggregate computation.
87246 */
87247 typedef struct SumCtx SumCtx;
87248 struct SumCtx {
87249   double rSum;      /* Floating point sum */
87250   i64 iSum;         /* Integer sum */   
87251   i64 cnt;          /* Number of elements summed */
87252   u8 overflow;      /* True if integer overflow seen */
87253   u8 approx;        /* True if non-integer value was input to the sum */
87254 };
87255
87256 /*
87257 ** Routines used to compute the sum, average, and total.
87258 **
87259 ** The SUM() function follows the (broken) SQL standard which means
87260 ** that it returns NULL if it sums over no inputs.  TOTAL returns
87261 ** 0.0 in that case.  In addition, TOTAL always returns a float where
87262 ** SUM might return an integer if it never encounters a floating point
87263 ** value.  TOTAL never fails, but SUM might through an exception if
87264 ** it overflows an integer.
87265 */
87266 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
87267   SumCtx *p;
87268   int type;
87269   assert( argc==1 );
87270   UNUSED_PARAMETER(argc);
87271   p = sqlite3_aggregate_context(context, sizeof(*p));
87272   type = sqlite3_value_numeric_type(argv[0]);
87273   if( p && type!=SQLITE_NULL ){
87274     p->cnt++;
87275     if( type==SQLITE_INTEGER ){
87276       i64 v = sqlite3_value_int64(argv[0]);
87277       p->rSum += v;
87278       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
87279         p->overflow = 1;
87280       }
87281     }else{
87282       p->rSum += sqlite3_value_double(argv[0]);
87283       p->approx = 1;
87284     }
87285   }
87286 }
87287 static void sumFinalize(sqlite3_context *context){
87288   SumCtx *p;
87289   p = sqlite3_aggregate_context(context, 0);
87290   if( p && p->cnt>0 ){
87291     if( p->overflow ){
87292       sqlite3_result_error(context,"integer overflow",-1);
87293     }else if( p->approx ){
87294       sqlite3_result_double(context, p->rSum);
87295     }else{
87296       sqlite3_result_int64(context, p->iSum);
87297     }
87298   }
87299 }
87300 static void avgFinalize(sqlite3_context *context){
87301   SumCtx *p;
87302   p = sqlite3_aggregate_context(context, 0);
87303   if( p && p->cnt>0 ){
87304     sqlite3_result_double(context, p->rSum/(double)p->cnt);
87305   }
87306 }
87307 static void totalFinalize(sqlite3_context *context){
87308   SumCtx *p;
87309   p = sqlite3_aggregate_context(context, 0);
87310   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
87311   sqlite3_result_double(context, p ? p->rSum : (double)0);
87312 }
87313
87314 /*
87315 ** The following structure keeps track of state information for the
87316 ** count() aggregate function.
87317 */
87318 typedef struct CountCtx CountCtx;
87319 struct CountCtx {
87320   i64 n;
87321 };
87322
87323 /*
87324 ** Routines to implement the count() aggregate function.
87325 */
87326 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
87327   CountCtx *p;
87328   p = sqlite3_aggregate_context(context, sizeof(*p));
87329   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
87330     p->n++;
87331   }
87332
87333 #ifndef SQLITE_OMIT_DEPRECATED
87334   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
87335   ** sure it still operates correctly, verify that its count agrees with our 
87336   ** internal count when using count(*) and when the total count can be
87337   ** expressed as a 32-bit integer. */
87338   assert( argc==1 || p==0 || p->n>0x7fffffff
87339           || p->n==sqlite3_aggregate_count(context) );
87340 #endif
87341 }   
87342 static void countFinalize(sqlite3_context *context){
87343   CountCtx *p;
87344   p = sqlite3_aggregate_context(context, 0);
87345   sqlite3_result_int64(context, p ? p->n : 0);
87346 }
87347
87348 /*
87349 ** Routines to implement min() and max() aggregate functions.
87350 */
87351 static void minmaxStep(
87352   sqlite3_context *context, 
87353   int NotUsed, 
87354   sqlite3_value **argv
87355 ){
87356   Mem *pArg  = (Mem *)argv[0];
87357   Mem *pBest;
87358   UNUSED_PARAMETER(NotUsed);
87359
87360   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
87361   if( !pBest ) return;
87362
87363   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
87364     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
87365   }else if( pBest->flags ){
87366     int max;
87367     int cmp;
87368     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
87369     /* This step function is used for both the min() and max() aggregates,
87370     ** the only difference between the two being that the sense of the
87371     ** comparison is inverted. For the max() aggregate, the
87372     ** sqlite3_user_data() function returns (void *)-1. For min() it
87373     ** returns (void *)db, where db is the sqlite3* database pointer.
87374     ** Therefore the next statement sets variable 'max' to 1 for the max()
87375     ** aggregate, or 0 for min().
87376     */
87377     max = sqlite3_user_data(context)!=0;
87378     cmp = sqlite3MemCompare(pBest, pArg, pColl);
87379     if( (max && cmp<0) || (!max && cmp>0) ){
87380       sqlite3VdbeMemCopy(pBest, pArg);
87381     }else{
87382       sqlite3SkipAccumulatorLoad(context);
87383     }
87384   }else{
87385     sqlite3VdbeMemCopy(pBest, pArg);
87386   }
87387 }
87388 static void minMaxFinalize(sqlite3_context *context){
87389   sqlite3_value *pRes;
87390   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
87391   if( pRes ){
87392     if( pRes->flags ){
87393       sqlite3_result_value(context, pRes);
87394     }
87395     sqlite3VdbeMemRelease(pRes);
87396   }
87397 }
87398
87399 /*
87400 ** group_concat(EXPR, ?SEPARATOR?)
87401 */
87402 static void groupConcatStep(
87403   sqlite3_context *context,
87404   int argc,
87405   sqlite3_value **argv
87406 ){
87407   const char *zVal;
87408   StrAccum *pAccum;
87409   const char *zSep;
87410   int nVal, nSep;
87411   assert( argc==1 || argc==2 );
87412   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87413   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
87414
87415   if( pAccum ){
87416     sqlite3 *db = sqlite3_context_db_handle(context);
87417     int firstTerm = pAccum->useMalloc==0;
87418     pAccum->useMalloc = 2;
87419     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
87420     if( !firstTerm ){
87421       if( argc==2 ){
87422         zSep = (char*)sqlite3_value_text(argv[1]);
87423         nSep = sqlite3_value_bytes(argv[1]);
87424       }else{
87425         zSep = ",";
87426         nSep = 1;
87427       }
87428       sqlite3StrAccumAppend(pAccum, zSep, nSep);
87429     }
87430     zVal = (char*)sqlite3_value_text(argv[0]);
87431     nVal = sqlite3_value_bytes(argv[0]);
87432     sqlite3StrAccumAppend(pAccum, zVal, nVal);
87433   }
87434 }
87435 static void groupConcatFinalize(sqlite3_context *context){
87436   StrAccum *pAccum;
87437   pAccum = sqlite3_aggregate_context(context, 0);
87438   if( pAccum ){
87439     if( pAccum->tooBig ){
87440       sqlite3_result_error_toobig(context);
87441     }else if( pAccum->mallocFailed ){
87442       sqlite3_result_error_nomem(context);
87443     }else{    
87444       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
87445                           sqlite3_free);
87446     }
87447   }
87448 }
87449
87450 /*
87451 ** This routine does per-connection function registration.  Most
87452 ** of the built-in functions above are part of the global function set.
87453 ** This routine only deals with those that are not global.
87454 */
87455 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
87456   int rc = sqlite3_overload_function(db, "MATCH", 2);
87457   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
87458   if( rc==SQLITE_NOMEM ){
87459     db->mallocFailed = 1;
87460   }
87461 }
87462
87463 /*
87464 ** Set the LIKEOPT flag on the 2-argument function with the given name.
87465 */
87466 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
87467   FuncDef *pDef;
87468   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
87469                              2, SQLITE_UTF8, 0);
87470   if( ALWAYS(pDef) ){
87471     pDef->flags = flagVal;
87472   }
87473 }
87474
87475 /*
87476 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
87477 ** parameter determines whether or not the LIKE operator is case
87478 ** sensitive.  GLOB is always case sensitive.
87479 */
87480 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
87481   struct compareInfo *pInfo;
87482   if( caseSensitive ){
87483     pInfo = (struct compareInfo*)&likeInfoAlt;
87484   }else{
87485     pInfo = (struct compareInfo*)&likeInfoNorm;
87486   }
87487   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
87488   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
87489   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
87490       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
87491   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
87492   setLikeOptFlag(db, "like", 
87493       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
87494 }
87495
87496 /*
87497 ** pExpr points to an expression which implements a function.  If
87498 ** it is appropriate to apply the LIKE optimization to that function
87499 ** then set aWc[0] through aWc[2] to the wildcard characters and
87500 ** return TRUE.  If the function is not a LIKE-style function then
87501 ** return FALSE.
87502 */
87503 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
87504   FuncDef *pDef;
87505   if( pExpr->op!=TK_FUNCTION 
87506    || !pExpr->x.pList 
87507    || pExpr->x.pList->nExpr!=2
87508   ){
87509     return 0;
87510   }
87511   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
87512   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
87513                              sqlite3Strlen30(pExpr->u.zToken),
87514                              2, SQLITE_UTF8, 0);
87515   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
87516     return 0;
87517   }
87518
87519   /* The memcpy() statement assumes that the wildcard characters are
87520   ** the first three statements in the compareInfo structure.  The
87521   ** asserts() that follow verify that assumption
87522   */
87523   memcpy(aWc, pDef->pUserData, 3);
87524   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
87525   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
87526   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
87527   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
87528   return 1;
87529 }
87530
87531 /*
87532 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
87533 ** to the global function hash table.  This occurs at start-time (as
87534 ** a consequence of calling sqlite3_initialize()).
87535 **
87536 ** After this routine runs
87537 */
87538 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
87539   /*
87540   ** The following array holds FuncDef structures for all of the functions
87541   ** defined in this file.
87542   **
87543   ** The array cannot be constant since changes are made to the
87544   ** FuncDef.pHash elements at start-time.  The elements of this array
87545   ** are read-only after initialization is complete.
87546   */
87547   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
87548     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
87549     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
87550     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
87551     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
87552     FUNCTION(trim,               1, 3, 0, trimFunc         ),
87553     FUNCTION(trim,               2, 3, 0, trimFunc         ),
87554     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
87555     FUNCTION(min,                0, 0, 1, 0                ),
87556     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
87557     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
87558     FUNCTION(max,                0, 1, 1, 0                ),
87559     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
87560     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
87561     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
87562     FUNCTION(instr,              2, 0, 0, instrFunc        ),
87563     FUNCTION(substr,             2, 0, 0, substrFunc       ),
87564     FUNCTION(substr,             3, 0, 0, substrFunc       ),
87565     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
87566     FUNCTION(char,              -1, 0, 0, charFunc         ),
87567     FUNCTION(abs,                1, 0, 0, absFunc          ),
87568 #ifndef SQLITE_OMIT_FLOATING_POINT
87569     FUNCTION(round,              1, 0, 0, roundFunc        ),
87570     FUNCTION(round,              2, 0, 0, roundFunc        ),
87571 #endif
87572     FUNCTION(upper,              1, 0, 0, upperFunc        ),
87573     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
87574     FUNCTION(coalesce,           1, 0, 0, 0                ),
87575     FUNCTION(coalesce,           0, 0, 0, 0                ),
87576     FUNCTION2(coalesce,         -1, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
87577     FUNCTION(hex,                1, 0, 0, hexFunc          ),
87578     FUNCTION2(ifnull,            2, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
87579     FUNCTION(random,             0, 0, 0, randomFunc       ),
87580     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
87581     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
87582     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
87583     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
87584     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
87585 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87586     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
87587     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
87588 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
87589     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
87590     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
87591     FUNCTION(changes,            0, 0, 0, changes          ),
87592     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
87593     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
87594     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
87595   #ifdef SQLITE_SOUNDEX
87596     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
87597   #endif
87598   #ifndef SQLITE_OMIT_LOAD_EXTENSION
87599     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
87600     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
87601   #endif
87602     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
87603     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
87604     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
87605  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
87606     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
87607     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
87608     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
87609     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
87610   
87611     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87612   #ifdef SQLITE_CASE_SENSITIVE_LIKE
87613     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87614     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87615   #else
87616     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
87617     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
87618   #endif
87619   };
87620
87621   int i;
87622   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
87623   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
87624
87625   for(i=0; i<ArraySize(aBuiltinFunc); i++){
87626     sqlite3FuncDefInsert(pHash, &aFunc[i]);
87627   }
87628   sqlite3RegisterDateTimeFunctions();
87629 #ifndef SQLITE_OMIT_ALTERTABLE
87630   sqlite3AlterFunctions();
87631 #endif
87632 }
87633
87634 /************** End of func.c ************************************************/
87635 /************** Begin file fkey.c ********************************************/
87636 /*
87637 **
87638 ** The author disclaims copyright to this source code.  In place of
87639 ** a legal notice, here is a blessing:
87640 **
87641 **    May you do good and not evil.
87642 **    May you find forgiveness for yourself and forgive others.
87643 **    May you share freely, never taking more than you give.
87644 **
87645 *************************************************************************
87646 ** This file contains code used by the compiler to add foreign key
87647 ** support to compiled SQL statements.
87648 */
87649
87650 #ifndef SQLITE_OMIT_FOREIGN_KEY
87651 #ifndef SQLITE_OMIT_TRIGGER
87652
87653 /*
87654 ** Deferred and Immediate FKs
87655 ** --------------------------
87656 **
87657 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
87658 ** If an immediate foreign key constraint is violated,
87659 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
87660 ** statement transaction rolled back. If a 
87661 ** deferred foreign key constraint is violated, no action is taken 
87662 ** immediately. However if the application attempts to commit the 
87663 ** transaction before fixing the constraint violation, the attempt fails.
87664 **
87665 ** Deferred constraints are implemented using a simple counter associated
87666 ** with the database handle. The counter is set to zero each time a 
87667 ** database transaction is opened. Each time a statement is executed 
87668 ** that causes a foreign key violation, the counter is incremented. Each
87669 ** time a statement is executed that removes an existing violation from
87670 ** the database, the counter is decremented. When the transaction is
87671 ** committed, the commit fails if the current value of the counter is
87672 ** greater than zero. This scheme has two big drawbacks:
87673 **
87674 **   * When a commit fails due to a deferred foreign key constraint, 
87675 **     there is no way to tell which foreign constraint is not satisfied,
87676 **     or which row it is not satisfied for.
87677 **
87678 **   * If the database contains foreign key violations when the 
87679 **     transaction is opened, this may cause the mechanism to malfunction.
87680 **
87681 ** Despite these problems, this approach is adopted as it seems simpler
87682 ** than the alternatives.
87683 **
87684 ** INSERT operations:
87685 **
87686 **   I.1) For each FK for which the table is the child table, search
87687 **        the parent table for a match. If none is found increment the
87688 **        constraint counter.
87689 **
87690 **   I.2) For each FK for which the table is the parent table, 
87691 **        search the child table for rows that correspond to the new
87692 **        row in the parent table. Decrement the counter for each row
87693 **        found (as the constraint is now satisfied).
87694 **
87695 ** DELETE operations:
87696 **
87697 **   D.1) For each FK for which the table is the child table, 
87698 **        search the parent table for a row that corresponds to the 
87699 **        deleted row in the child table. If such a row is not found, 
87700 **        decrement the counter.
87701 **
87702 **   D.2) For each FK for which the table is the parent table, search 
87703 **        the child table for rows that correspond to the deleted row 
87704 **        in the parent table. For each found increment the counter.
87705 **
87706 ** UPDATE operations:
87707 **
87708 **   An UPDATE command requires that all 4 steps above are taken, but only
87709 **   for FK constraints for which the affected columns are actually 
87710 **   modified (values must be compared at runtime).
87711 **
87712 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
87713 ** This simplifies the implementation a bit.
87714 **
87715 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
87716 ** resolution is considered to delete rows before the new row is inserted.
87717 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
87718 ** is thrown, even if the FK constraint would be satisfied after the new 
87719 ** row is inserted.
87720 **
87721 ** Immediate constraints are usually handled similarly. The only difference 
87722 ** is that the counter used is stored as part of each individual statement
87723 ** object (struct Vdbe). If, after the statement has run, its immediate
87724 ** constraint counter is greater than zero,
87725 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
87726 ** and the statement transaction is rolled back. An exception is an INSERT
87727 ** statement that inserts a single row only (no triggers). In this case,
87728 ** instead of using a counter, an exception is thrown immediately if the
87729 ** INSERT violates a foreign key constraint. This is necessary as such
87730 ** an INSERT does not open a statement transaction.
87731 **
87732 ** TODO: How should dropping a table be handled? How should renaming a 
87733 ** table be handled?
87734 **
87735 **
87736 ** Query API Notes
87737 ** ---------------
87738 **
87739 ** Before coding an UPDATE or DELETE row operation, the code-generator
87740 ** for those two operations needs to know whether or not the operation
87741 ** requires any FK processing and, if so, which columns of the original
87742 ** row are required by the FK processing VDBE code (i.e. if FKs were
87743 ** implemented using triggers, which of the old.* columns would be 
87744 ** accessed). No information is required by the code-generator before
87745 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
87746 ** generation code to query for this information are:
87747 **
87748 **   sqlite3FkRequired() - Test to see if FK processing is required.
87749 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
87750 **
87751 **
87752 ** Externally accessible module functions
87753 ** --------------------------------------
87754 **
87755 **   sqlite3FkCheck()    - Check for foreign key violations.
87756 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
87757 **   sqlite3FkDelete()   - Delete an FKey structure.
87758 */
87759
87760 /*
87761 ** VDBE Calling Convention
87762 ** -----------------------
87763 **
87764 ** Example:
87765 **
87766 **   For the following INSERT statement:
87767 **
87768 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
87769 **     INSERT INTO t1 VALUES(1, 2, 3.1);
87770 **
87771 **   Register (x):        2    (type integer)
87772 **   Register (x+1):      1    (type integer)
87773 **   Register (x+2):      NULL (type NULL)
87774 **   Register (x+3):      3.1  (type real)
87775 */
87776
87777 /*
87778 ** A foreign key constraint requires that the key columns in the parent
87779 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
87780 ** Given that pParent is the parent table for foreign key constraint pFKey, 
87781 ** search the schema for a unique index on the parent key columns. 
87782 **
87783 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
87784 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
87785 ** is set to point to the unique index. 
87786 ** 
87787 ** If the parent key consists of a single column (the foreign key constraint
87788 ** is not a composite foreign key), output variable *paiCol is set to NULL.
87789 ** Otherwise, it is set to point to an allocated array of size N, where
87790 ** N is the number of columns in the parent key. The first element of the
87791 ** array is the index of the child table column that is mapped by the FK
87792 ** constraint to the parent table column stored in the left-most column
87793 ** of index *ppIdx. The second element of the array is the index of the
87794 ** child table column that corresponds to the second left-most column of
87795 ** *ppIdx, and so on.
87796 **
87797 ** If the required index cannot be found, either because:
87798 **
87799 **   1) The named parent key columns do not exist, or
87800 **
87801 **   2) The named parent key columns do exist, but are not subject to a
87802 **      UNIQUE or PRIMARY KEY constraint, or
87803 **
87804 **   3) No parent key columns were provided explicitly as part of the
87805 **      foreign key definition, and the parent table does not have a
87806 **      PRIMARY KEY, or
87807 **
87808 **   4) No parent key columns were provided explicitly as part of the
87809 **      foreign key definition, and the PRIMARY KEY of the parent table 
87810 **      consists of a a different number of columns to the child key in 
87811 **      the child table.
87812 **
87813 ** then non-zero is returned, and a "foreign key mismatch" error loaded
87814 ** into pParse. If an OOM error occurs, non-zero is returned and the
87815 ** pParse->db->mallocFailed flag is set.
87816 */
87817 SQLITE_PRIVATE int sqlite3FkLocateIndex(
87818   Parse *pParse,                  /* Parse context to store any error in */
87819   Table *pParent,                 /* Parent table of FK constraint pFKey */
87820   FKey *pFKey,                    /* Foreign key to find index for */
87821   Index **ppIdx,                  /* OUT: Unique index on parent table */
87822   int **paiCol                    /* OUT: Map of index columns in pFKey */
87823 ){
87824   Index *pIdx = 0;                    /* Value to return via *ppIdx */
87825   int *aiCol = 0;                     /* Value to return via *paiCol */
87826   int nCol = pFKey->nCol;             /* Number of columns in parent key */
87827   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
87828
87829   /* The caller is responsible for zeroing output parameters. */
87830   assert( ppIdx && *ppIdx==0 );
87831   assert( !paiCol || *paiCol==0 );
87832   assert( pParse );
87833
87834   /* If this is a non-composite (single column) foreign key, check if it 
87835   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
87836   ** and *paiCol set to zero and return early. 
87837   **
87838   ** Otherwise, for a composite foreign key (more than one column), allocate
87839   ** space for the aiCol array (returned via output parameter *paiCol).
87840   ** Non-composite foreign keys do not require the aiCol array.
87841   */
87842   if( nCol==1 ){
87843     /* The FK maps to the IPK if any of the following are true:
87844     **
87845     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
87846     **      mapped to the primary key of table pParent, or
87847     **   2) The FK is explicitly mapped to a column declared as INTEGER
87848     **      PRIMARY KEY.
87849     */
87850     if( pParent->iPKey>=0 ){
87851       if( !zKey ) return 0;
87852       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
87853     }
87854   }else if( paiCol ){
87855     assert( nCol>1 );
87856     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
87857     if( !aiCol ) return 1;
87858     *paiCol = aiCol;
87859   }
87860
87861   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
87862     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
87863       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
87864       ** of columns. If each indexed column corresponds to a foreign key
87865       ** column of pFKey, then this index is a winner.  */
87866
87867       if( zKey==0 ){
87868         /* If zKey is NULL, then this foreign key is implicitly mapped to 
87869         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
87870         ** identified by the test (Index.autoIndex==2).  */
87871         if( pIdx->autoIndex==2 ){
87872           if( aiCol ){
87873             int i;
87874             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
87875           }
87876           break;
87877         }
87878       }else{
87879         /* If zKey is non-NULL, then this foreign key was declared to
87880         ** map to an explicit list of columns in table pParent. Check if this
87881         ** index matches those columns. Also, check that the index uses
87882         ** the default collation sequences for each column. */
87883         int i, j;
87884         for(i=0; i<nCol; i++){
87885           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
87886           char *zDfltColl;                  /* Def. collation for column */
87887           char *zIdxCol;                    /* Name of indexed column */
87888
87889           /* If the index uses a collation sequence that is different from
87890           ** the default collation sequence for the column, this index is
87891           ** unusable. Bail out early in this case.  */
87892           zDfltColl = pParent->aCol[iCol].zColl;
87893           if( !zDfltColl ){
87894             zDfltColl = "BINARY";
87895           }
87896           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
87897
87898           zIdxCol = pParent->aCol[iCol].zName;
87899           for(j=0; j<nCol; j++){
87900             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
87901               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
87902               break;
87903             }
87904           }
87905           if( j==nCol ) break;
87906         }
87907         if( i==nCol ) break;      /* pIdx is usable */
87908       }
87909     }
87910   }
87911
87912   if( !pIdx ){
87913     if( !pParse->disableTriggers ){
87914       sqlite3ErrorMsg(pParse,
87915            "foreign key mismatch - \"%w\" referencing \"%w\"",
87916            pFKey->pFrom->zName, pFKey->zTo);
87917     }
87918     sqlite3DbFree(pParse->db, aiCol);
87919     return 1;
87920   }
87921
87922   *ppIdx = pIdx;
87923   return 0;
87924 }
87925
87926 /*
87927 ** This function is called when a row is inserted into or deleted from the 
87928 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
87929 ** on the child table of pFKey, this function is invoked twice for each row
87930 ** affected - once to "delete" the old row, and then again to "insert" the
87931 ** new row.
87932 **
87933 ** Each time it is called, this function generates VDBE code to locate the
87934 ** row in the parent table that corresponds to the row being inserted into 
87935 ** or deleted from the child table. If the parent row can be found, no 
87936 ** special action is taken. Otherwise, if the parent row can *not* be
87937 ** found in the parent table:
87938 **
87939 **   Operation | FK type   | Action taken
87940 **   --------------------------------------------------------------------------
87941 **   INSERT      immediate   Increment the "immediate constraint counter".
87942 **
87943 **   DELETE      immediate   Decrement the "immediate constraint counter".
87944 **
87945 **   INSERT      deferred    Increment the "deferred constraint counter".
87946 **
87947 **   DELETE      deferred    Decrement the "deferred constraint counter".
87948 **
87949 ** These operations are identified in the comment at the top of this file 
87950 ** (fkey.c) as "I.1" and "D.1".
87951 */
87952 static void fkLookupParent(
87953   Parse *pParse,        /* Parse context */
87954   int iDb,              /* Index of database housing pTab */
87955   Table *pTab,          /* Parent table of FK pFKey */
87956   Index *pIdx,          /* Unique index on parent key columns in pTab */
87957   FKey *pFKey,          /* Foreign key constraint */
87958   int *aiCol,           /* Map from parent key columns to child table columns */
87959   int regData,          /* Address of array containing child table row */
87960   int nIncr,            /* Increment constraint counter by this */
87961   int isIgnore          /* If true, pretend pTab contains all NULL values */
87962 ){
87963   int i;                                    /* Iterator variable */
87964   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
87965   int iCur = pParse->nTab - 1;              /* Cursor number to use */
87966   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
87967
87968   /* If nIncr is less than zero, then check at runtime if there are any
87969   ** outstanding constraints to resolve. If there are not, there is no need
87970   ** to check if deleting this row resolves any outstanding violations.
87971   **
87972   ** Check if any of the key columns in the child table row are NULL. If 
87973   ** any are, then the constraint is considered satisfied. No need to 
87974   ** search for a matching row in the parent table.  */
87975   if( nIncr<0 ){
87976     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
87977   }
87978   for(i=0; i<pFKey->nCol; i++){
87979     int iReg = aiCol[i] + regData + 1;
87980     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
87981   }
87982
87983   if( isIgnore==0 ){
87984     if( pIdx==0 ){
87985       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
87986       ** column of the parent table (table pTab).  */
87987       int iMustBeInt;               /* Address of MustBeInt instruction */
87988       int regTemp = sqlite3GetTempReg(pParse);
87989   
87990       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
87991       ** apply the affinity of the parent key). If this fails, then there
87992       ** is no matching parent key. Before using MustBeInt, make a copy of
87993       ** the value. Otherwise, the value inserted into the child key column
87994       ** will have INTEGER affinity applied to it, which may not be correct.  */
87995       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
87996       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
87997   
87998       /* If the parent table is the same as the child table, and we are about
87999       ** to increment the constraint-counter (i.e. this is an INSERT operation),
88000       ** then check if the row being inserted matches itself. If so, do not
88001       ** increment the constraint-counter.  */
88002       if( pTab==pFKey->pFrom && nIncr==1 ){
88003         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
88004       }
88005   
88006       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
88007       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
88008       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
88009       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
88010       sqlite3VdbeJumpHere(v, iMustBeInt);
88011       sqlite3ReleaseTempReg(pParse, regTemp);
88012     }else{
88013       int nCol = pFKey->nCol;
88014       int regTemp = sqlite3GetTempRange(pParse, nCol);
88015       int regRec = sqlite3GetTempReg(pParse);
88016       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
88017   
88018       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
88019       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
88020       for(i=0; i<nCol; i++){
88021         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
88022       }
88023   
88024       /* If the parent table is the same as the child table, and we are about
88025       ** to increment the constraint-counter (i.e. this is an INSERT operation),
88026       ** then check if the row being inserted matches itself. If so, do not
88027       ** increment the constraint-counter. 
88028       **
88029       ** If any of the parent-key values are NULL, then the row cannot match 
88030       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
88031       ** of the parent-key values are NULL (at this point it is known that
88032       ** none of the child key values are).
88033       */
88034       if( pTab==pFKey->pFrom && nIncr==1 ){
88035         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
88036         for(i=0; i<nCol; i++){
88037           int iChild = aiCol[i]+1+regData;
88038           int iParent = pIdx->aiColumn[i]+1+regData;
88039           assert( aiCol[i]!=pTab->iPKey );
88040           if( pIdx->aiColumn[i]==pTab->iPKey ){
88041             /* The parent key is a composite key that includes the IPK column */
88042             iParent = regData;
88043           }
88044           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
88045           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
88046         }
88047         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
88048       }
88049   
88050       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
88051       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
88052       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
88053   
88054       sqlite3ReleaseTempReg(pParse, regRec);
88055       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
88056     }
88057   }
88058
88059   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
88060     /* Special case: If this is an INSERT statement that will insert exactly
88061     ** one row into the table, raise a constraint immediately instead of
88062     ** incrementing a counter. This is necessary as the VM code is being
88063     ** generated for will not open a statement transaction.  */
88064     assert( nIncr==1 );
88065     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
88066         OE_Abort, "foreign key constraint failed", P4_STATIC
88067     );
88068   }else{
88069     if( nIncr>0 && pFKey->isDeferred==0 ){
88070       sqlite3ParseToplevel(pParse)->mayAbort = 1;
88071     }
88072     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
88073   }
88074
88075   sqlite3VdbeResolveLabel(v, iOk);
88076   sqlite3VdbeAddOp1(v, OP_Close, iCur);
88077 }
88078
88079 /*
88080 ** This function is called to generate code executed when a row is deleted
88081 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
88082 ** deferred, when a row is inserted into the same table. When generating
88083 ** code for an SQL UPDATE operation, this function may be called twice -
88084 ** once to "delete" the old row and once to "insert" the new row.
88085 **
88086 ** The code generated by this function scans through the rows in the child
88087 ** table that correspond to the parent table row being deleted or inserted.
88088 ** For each child row found, one of the following actions is taken:
88089 **
88090 **   Operation | FK type   | Action taken
88091 **   --------------------------------------------------------------------------
88092 **   DELETE      immediate   Increment the "immediate constraint counter".
88093 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
88094 **                           throw a "foreign key constraint failed" exception.
88095 **
88096 **   INSERT      immediate   Decrement the "immediate constraint counter".
88097 **
88098 **   DELETE      deferred    Increment the "deferred constraint counter".
88099 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
88100 **                           throw a "foreign key constraint failed" exception.
88101 **
88102 **   INSERT      deferred    Decrement the "deferred constraint counter".
88103 **
88104 ** These operations are identified in the comment at the top of this file 
88105 ** (fkey.c) as "I.2" and "D.2".
88106 */
88107 static void fkScanChildren(
88108   Parse *pParse,                  /* Parse context */
88109   SrcList *pSrc,                  /* SrcList containing the table to scan */
88110   Table *pTab,
88111   Index *pIdx,                    /* Foreign key index */
88112   FKey *pFKey,                    /* Foreign key relationship */
88113   int *aiCol,                     /* Map from pIdx cols to child table cols */
88114   int regData,                    /* Referenced table data starts here */
88115   int nIncr                       /* Amount to increment deferred counter by */
88116 ){
88117   sqlite3 *db = pParse->db;       /* Database handle */
88118   int i;                          /* Iterator variable */
88119   Expr *pWhere = 0;               /* WHERE clause to scan with */
88120   NameContext sNameContext;       /* Context used to resolve WHERE clause */
88121   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
88122   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
88123   Vdbe *v = sqlite3GetVdbe(pParse);
88124
88125   assert( !pIdx || pIdx->pTable==pTab );
88126
88127   if( nIncr<0 ){
88128     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
88129   }
88130
88131   /* Create an Expr object representing an SQL expression like:
88132   **
88133   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
88134   **
88135   ** The collation sequence used for the comparison should be that of
88136   ** the parent key columns. The affinity of the parent key column should
88137   ** be applied to each child key value before the comparison takes place.
88138   */
88139   for(i=0; i<pFKey->nCol; i++){
88140     Expr *pLeft;                  /* Value from parent table row */
88141     Expr *pRight;                 /* Column ref to child table */
88142     Expr *pEq;                    /* Expression (pLeft = pRight) */
88143     int iCol;                     /* Index of column in child table */ 
88144     const char *zCol;             /* Name of column in child table */
88145
88146     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
88147     if( pLeft ){
88148       /* Set the collation sequence and affinity of the LHS of each TK_EQ
88149       ** expression to the parent key column defaults.  */
88150       if( pIdx ){
88151         Column *pCol;
88152         const char *zColl;
88153         iCol = pIdx->aiColumn[i];
88154         pCol = &pTab->aCol[iCol];
88155         if( pTab->iPKey==iCol ) iCol = -1;
88156         pLeft->iTable = regData+iCol+1;
88157         pLeft->affinity = pCol->affinity;
88158         zColl = pCol->zColl;
88159         if( zColl==0 ) zColl = db->pDfltColl->zName;
88160         pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
88161       }else{
88162         pLeft->iTable = regData;
88163         pLeft->affinity = SQLITE_AFF_INTEGER;
88164       }
88165     }
88166     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
88167     assert( iCol>=0 );
88168     zCol = pFKey->pFrom->aCol[iCol].zName;
88169     pRight = sqlite3Expr(db, TK_ID, zCol);
88170     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
88171     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88172   }
88173
88174   /* If the child table is the same as the parent table, and this scan
88175   ** is taking place as part of a DELETE operation (operation D.2), omit the
88176   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
88177   ** clause, where $rowid is the rowid of the row being deleted.  */
88178   if( pTab==pFKey->pFrom && nIncr>0 ){
88179     Expr *pEq;                    /* Expression (pLeft = pRight) */
88180     Expr *pLeft;                  /* Value from parent table row */
88181     Expr *pRight;                 /* Column ref to child table */
88182     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
88183     pRight = sqlite3Expr(db, TK_COLUMN, 0);
88184     if( pLeft && pRight ){
88185       pLeft->iTable = regData;
88186       pLeft->affinity = SQLITE_AFF_INTEGER;
88187       pRight->iTable = pSrc->a[0].iCursor;
88188       pRight->iColumn = -1;
88189     }
88190     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
88191     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88192   }
88193
88194   /* Resolve the references in the WHERE clause. */
88195   memset(&sNameContext, 0, sizeof(NameContext));
88196   sNameContext.pSrcList = pSrc;
88197   sNameContext.pParse = pParse;
88198   sqlite3ResolveExprNames(&sNameContext, pWhere);
88199
88200   /* Create VDBE to loop through the entries in pSrc that match the WHERE
88201   ** clause. If the constraint is not deferred, throw an exception for
88202   ** each row found. Otherwise, for deferred constraints, increment the
88203   ** deferred constraint counter by nIncr for each row selected.  */
88204   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
88205   if( nIncr>0 && pFKey->isDeferred==0 ){
88206     sqlite3ParseToplevel(pParse)->mayAbort = 1;
88207   }
88208   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
88209   if( pWInfo ){
88210     sqlite3WhereEnd(pWInfo);
88211   }
88212
88213   /* Clean up the WHERE clause constructed above. */
88214   sqlite3ExprDelete(db, pWhere);
88215   if( iFkIfZero ){
88216     sqlite3VdbeJumpHere(v, iFkIfZero);
88217   }
88218 }
88219
88220 /*
88221 ** This function returns a pointer to the head of a linked list of FK
88222 ** constraints for which table pTab is the parent table. For example,
88223 ** given the following schema:
88224 **
88225 **   CREATE TABLE t1(a PRIMARY KEY);
88226 **   CREATE TABLE t2(b REFERENCES t1(a);
88227 **
88228 ** Calling this function with table "t1" as an argument returns a pointer
88229 ** to the FKey structure representing the foreign key constraint on table
88230 ** "t2". Calling this function with "t2" as the argument would return a
88231 ** NULL pointer (as there are no FK constraints for which t2 is the parent
88232 ** table).
88233 */
88234 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
88235   int nName = sqlite3Strlen30(pTab->zName);
88236   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
88237 }
88238
88239 /*
88240 ** The second argument is a Trigger structure allocated by the 
88241 ** fkActionTrigger() routine. This function deletes the Trigger structure
88242 ** and all of its sub-components.
88243 **
88244 ** The Trigger structure or any of its sub-components may be allocated from
88245 ** the lookaside buffer belonging to database handle dbMem.
88246 */
88247 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
88248   if( p ){
88249     TriggerStep *pStep = p->step_list;
88250     sqlite3ExprDelete(dbMem, pStep->pWhere);
88251     sqlite3ExprListDelete(dbMem, pStep->pExprList);
88252     sqlite3SelectDelete(dbMem, pStep->pSelect);
88253     sqlite3ExprDelete(dbMem, p->pWhen);
88254     sqlite3DbFree(dbMem, p);
88255   }
88256 }
88257
88258 /*
88259 ** This function is called to generate code that runs when table pTab is
88260 ** being dropped from the database. The SrcList passed as the second argument
88261 ** to this function contains a single entry guaranteed to resolve to
88262 ** table pTab.
88263 **
88264 ** Normally, no code is required. However, if either
88265 **
88266 **   (a) The table is the parent table of a FK constraint, or
88267 **   (b) The table is the child table of a deferred FK constraint and it is
88268 **       determined at runtime that there are outstanding deferred FK 
88269 **       constraint violations in the database,
88270 **
88271 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
88272 ** the table from the database. Triggers are disabled while running this
88273 ** DELETE, but foreign key actions are not.
88274 */
88275 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
88276   sqlite3 *db = pParse->db;
88277   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
88278     int iSkip = 0;
88279     Vdbe *v = sqlite3GetVdbe(pParse);
88280
88281     assert( v );                  /* VDBE has already been allocated */
88282     if( sqlite3FkReferences(pTab)==0 ){
88283       /* Search for a deferred foreign key constraint for which this table
88284       ** is the child table. If one cannot be found, return without 
88285       ** generating any VDBE code. If one can be found, then jump over
88286       ** the entire DELETE if there are no outstanding deferred constraints
88287       ** when this statement is run.  */
88288       FKey *p;
88289       for(p=pTab->pFKey; p; p=p->pNextFrom){
88290         if( p->isDeferred ) break;
88291       }
88292       if( !p ) return;
88293       iSkip = sqlite3VdbeMakeLabel(v);
88294       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
88295     }
88296
88297     pParse->disableTriggers = 1;
88298     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
88299     pParse->disableTriggers = 0;
88300
88301     /* If the DELETE has generated immediate foreign key constraint 
88302     ** violations, halt the VDBE and return an error at this point, before
88303     ** any modifications to the schema are made. This is because statement
88304     ** transactions are not able to rollback schema changes.  */
88305     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
88306     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
88307         OE_Abort, "foreign key constraint failed", P4_STATIC
88308     );
88309
88310     if( iSkip ){
88311       sqlite3VdbeResolveLabel(v, iSkip);
88312     }
88313   }
88314 }
88315
88316 /*
88317 ** This function is called when inserting, deleting or updating a row of
88318 ** table pTab to generate VDBE code to perform foreign key constraint 
88319 ** processing for the operation.
88320 **
88321 ** For a DELETE operation, parameter regOld is passed the index of the
88322 ** first register in an array of (pTab->nCol+1) registers containing the
88323 ** rowid of the row being deleted, followed by each of the column values
88324 ** of the row being deleted, from left to right. Parameter regNew is passed
88325 ** zero in this case.
88326 **
88327 ** For an INSERT operation, regOld is passed zero and regNew is passed the
88328 ** first register of an array of (pTab->nCol+1) registers containing the new
88329 ** row data.
88330 **
88331 ** For an UPDATE operation, this function is called twice. Once before
88332 ** the original record is deleted from the table using the calling convention
88333 ** described for DELETE. Then again after the original record is deleted
88334 ** but before the new record is inserted using the INSERT convention. 
88335 */
88336 SQLITE_PRIVATE void sqlite3FkCheck(
88337   Parse *pParse,                  /* Parse context */
88338   Table *pTab,                    /* Row is being deleted from this table */ 
88339   int regOld,                     /* Previous row data is stored here */
88340   int regNew                      /* New row data is stored here */
88341 ){
88342   sqlite3 *db = pParse->db;       /* Database handle */
88343   FKey *pFKey;                    /* Used to iterate through FKs */
88344   int iDb;                        /* Index of database containing pTab */
88345   const char *zDb;                /* Name of database containing pTab */
88346   int isIgnoreErrors = pParse->disableTriggers;
88347
88348   /* Exactly one of regOld and regNew should be non-zero. */
88349   assert( (regOld==0)!=(regNew==0) );
88350
88351   /* If foreign-keys are disabled, this function is a no-op. */
88352   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
88353
88354   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
88355   zDb = db->aDb[iDb].zName;
88356
88357   /* Loop through all the foreign key constraints for which pTab is the
88358   ** child table (the table that the foreign key definition is part of).  */
88359   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
88360     Table *pTo;                   /* Parent table of foreign key pFKey */
88361     Index *pIdx = 0;              /* Index on key columns in pTo */
88362     int *aiFree = 0;
88363     int *aiCol;
88364     int iCol;
88365     int i;
88366     int isIgnore = 0;
88367
88368     /* Find the parent table of this foreign key. Also find a unique index 
88369     ** on the parent key columns in the parent table. If either of these 
88370     ** schema items cannot be located, set an error in pParse and return 
88371     ** early.  */
88372     if( pParse->disableTriggers ){
88373       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
88374     }else{
88375       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
88376     }
88377     if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
88378       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
88379       if( !isIgnoreErrors || db->mallocFailed ) return;
88380       if( pTo==0 ){
88381         /* If isIgnoreErrors is true, then a table is being dropped. In this
88382         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
88383         ** before actually dropping it in order to check FK constraints.
88384         ** If the parent table of an FK constraint on the current table is
88385         ** missing, behave as if it is empty. i.e. decrement the relevant
88386         ** FK counter for each row of the current table with non-NULL keys.
88387         */
88388         Vdbe *v = sqlite3GetVdbe(pParse);
88389         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
88390         for(i=0; i<pFKey->nCol; i++){
88391           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
88392           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
88393         }
88394         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
88395       }
88396       continue;
88397     }
88398     assert( pFKey->nCol==1 || (aiFree && pIdx) );
88399
88400     if( aiFree ){
88401       aiCol = aiFree;
88402     }else{
88403       iCol = pFKey->aCol[0].iFrom;
88404       aiCol = &iCol;
88405     }
88406     for(i=0; i<pFKey->nCol; i++){
88407       if( aiCol[i]==pTab->iPKey ){
88408         aiCol[i] = -1;
88409       }
88410 #ifndef SQLITE_OMIT_AUTHORIZATION
88411       /* Request permission to read the parent key columns. If the 
88412       ** authorization callback returns SQLITE_IGNORE, behave as if any
88413       ** values read from the parent table are NULL. */
88414       if( db->xAuth ){
88415         int rcauth;
88416         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
88417         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
88418         isIgnore = (rcauth==SQLITE_IGNORE);
88419       }
88420 #endif
88421     }
88422
88423     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
88424     ** a cursor to use to search the unique index on the parent key columns 
88425     ** in the parent table.  */
88426     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
88427     pParse->nTab++;
88428
88429     if( regOld!=0 ){
88430       /* A row is being removed from the child table. Search for the parent.
88431       ** If the parent does not exist, removing the child row resolves an 
88432       ** outstanding foreign key constraint violation. */
88433       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
88434     }
88435     if( regNew!=0 ){
88436       /* A row is being added to the child table. If a parent row cannot
88437       ** be found, adding the child row has violated the FK constraint. */ 
88438       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
88439     }
88440
88441     sqlite3DbFree(db, aiFree);
88442   }
88443
88444   /* Loop through all the foreign key constraints that refer to this table */
88445   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88446     Index *pIdx = 0;              /* Foreign key index for pFKey */
88447     SrcList *pSrc;
88448     int *aiCol = 0;
88449
88450     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
88451       assert( regOld==0 && regNew!=0 );
88452       /* Inserting a single row into a parent table cannot cause an immediate
88453       ** foreign key violation. So do nothing in this case.  */
88454       continue;
88455     }
88456
88457     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
88458       if( !isIgnoreErrors || db->mallocFailed ) return;
88459       continue;
88460     }
88461     assert( aiCol || pFKey->nCol==1 );
88462
88463     /* Create a SrcList structure containing a single table (the table 
88464     ** the foreign key that refers to this table is attached to). This
88465     ** is required for the sqlite3WhereXXX() interface.  */
88466     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
88467     if( pSrc ){
88468       struct SrcList_item *pItem = pSrc->a;
88469       pItem->pTab = pFKey->pFrom;
88470       pItem->zName = pFKey->pFrom->zName;
88471       pItem->pTab->nRef++;
88472       pItem->iCursor = pParse->nTab++;
88473   
88474       if( regNew!=0 ){
88475         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
88476       }
88477       if( regOld!=0 ){
88478         /* If there is a RESTRICT action configured for the current operation
88479         ** on the parent table of this FK, then throw an exception 
88480         ** immediately if the FK constraint is violated, even if this is a
88481         ** deferred trigger. That's what RESTRICT means. To defer checking
88482         ** the constraint, the FK should specify NO ACTION (represented
88483         ** using OE_None). NO ACTION is the default.  */
88484         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
88485       }
88486       pItem->zName = 0;
88487       sqlite3SrcListDelete(db, pSrc);
88488     }
88489     sqlite3DbFree(db, aiCol);
88490   }
88491 }
88492
88493 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
88494
88495 /*
88496 ** This function is called before generating code to update or delete a 
88497 ** row contained in table pTab.
88498 */
88499 SQLITE_PRIVATE u32 sqlite3FkOldmask(
88500   Parse *pParse,                  /* Parse context */
88501   Table *pTab                     /* Table being modified */
88502 ){
88503   u32 mask = 0;
88504   if( pParse->db->flags&SQLITE_ForeignKeys ){
88505     FKey *p;
88506     int i;
88507     for(p=pTab->pFKey; p; p=p->pNextFrom){
88508       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
88509     }
88510     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
88511       Index *pIdx = 0;
88512       sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
88513       if( pIdx ){
88514         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
88515       }
88516     }
88517   }
88518   return mask;
88519 }
88520
88521 /*
88522 ** This function is called before generating code to update or delete a 
88523 ** row contained in table pTab. If the operation is a DELETE, then
88524 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
88525 ** to an array of size N, where N is the number of columns in table pTab.
88526 ** If the i'th column is not modified by the UPDATE, then the corresponding 
88527 ** entry in the aChange[] array is set to -1. If the column is modified,
88528 ** the value is 0 or greater. Parameter chngRowid is set to true if the
88529 ** UPDATE statement modifies the rowid fields of the table.
88530 **
88531 ** If any foreign key processing will be required, this function returns
88532 ** true. If there is no foreign key related processing, this function 
88533 ** returns false.
88534 */
88535 SQLITE_PRIVATE int sqlite3FkRequired(
88536   Parse *pParse,                  /* Parse context */
88537   Table *pTab,                    /* Table being modified */
88538   int *aChange,                   /* Non-NULL for UPDATE operations */
88539   int chngRowid                   /* True for UPDATE that affects rowid */
88540 ){
88541   if( pParse->db->flags&SQLITE_ForeignKeys ){
88542     if( !aChange ){
88543       /* A DELETE operation. Foreign key processing is required if the 
88544       ** table in question is either the child or parent table for any 
88545       ** foreign key constraint.  */
88546       return (sqlite3FkReferences(pTab) || pTab->pFKey);
88547     }else{
88548       /* This is an UPDATE. Foreign key processing is only required if the
88549       ** operation modifies one or more child or parent key columns. */
88550       int i;
88551       FKey *p;
88552
88553       /* Check if any child key columns are being modified. */
88554       for(p=pTab->pFKey; p; p=p->pNextFrom){
88555         for(i=0; i<p->nCol; i++){
88556           int iChildKey = p->aCol[i].iFrom;
88557           if( aChange[iChildKey]>=0 ) return 1;
88558           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
88559         }
88560       }
88561
88562       /* Check if any parent key columns are being modified. */
88563       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
88564         for(i=0; i<p->nCol; i++){
88565           char *zKey = p->aCol[i].zCol;
88566           int iKey;
88567           for(iKey=0; iKey<pTab->nCol; iKey++){
88568             Column *pCol = &pTab->aCol[iKey];
88569             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey)
88570                       : (pCol->colFlags & COLFLAG_PRIMKEY)!=0) ){
88571               if( aChange[iKey]>=0 ) return 1;
88572               if( iKey==pTab->iPKey && chngRowid ) return 1;
88573             }
88574           }
88575         }
88576       }
88577     }
88578   }
88579   return 0;
88580 }
88581
88582 /*
88583 ** This function is called when an UPDATE or DELETE operation is being 
88584 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
88585 ** If the current operation is an UPDATE, then the pChanges parameter is
88586 ** passed a pointer to the list of columns being modified. If it is a
88587 ** DELETE, pChanges is passed a NULL pointer.
88588 **
88589 ** It returns a pointer to a Trigger structure containing a trigger
88590 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
88591 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
88592 ** returned (these actions require no special handling by the triggers
88593 ** sub-system, code for them is created by fkScanChildren()).
88594 **
88595 ** For example, if pFKey is the foreign key and pTab is table "p" in 
88596 ** the following schema:
88597 **
88598 **   CREATE TABLE p(pk PRIMARY KEY);
88599 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
88600 **
88601 ** then the returned trigger structure is equivalent to:
88602 **
88603 **   CREATE TRIGGER ... DELETE ON p BEGIN
88604 **     DELETE FROM c WHERE ck = old.pk;
88605 **   END;
88606 **
88607 ** The returned pointer is cached as part of the foreign key object. It
88608 ** is eventually freed along with the rest of the foreign key object by 
88609 ** sqlite3FkDelete().
88610 */
88611 static Trigger *fkActionTrigger(
88612   Parse *pParse,                  /* Parse context */
88613   Table *pTab,                    /* Table being updated or deleted from */
88614   FKey *pFKey,                    /* Foreign key to get action for */
88615   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
88616 ){
88617   sqlite3 *db = pParse->db;       /* Database handle */
88618   int action;                     /* One of OE_None, OE_Cascade etc. */
88619   Trigger *pTrigger;              /* Trigger definition to return */
88620   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
88621
88622   action = pFKey->aAction[iAction];
88623   pTrigger = pFKey->apTrigger[iAction];
88624
88625   if( action!=OE_None && !pTrigger ){
88626     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
88627     char const *zFrom;            /* Name of child table */
88628     int nFrom;                    /* Length in bytes of zFrom */
88629     Index *pIdx = 0;              /* Parent key index for this FK */
88630     int *aiCol = 0;               /* child table cols -> parent key cols */
88631     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
88632     Expr *pWhere = 0;             /* WHERE clause of trigger step */
88633     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
88634     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
88635     int i;                        /* Iterator variable */
88636     Expr *pWhen = 0;              /* WHEN clause for the trigger */
88637
88638     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
88639     assert( aiCol || pFKey->nCol==1 );
88640
88641     for(i=0; i<pFKey->nCol; i++){
88642       Token tOld = { "old", 3 };  /* Literal "old" token */
88643       Token tNew = { "new", 3 };  /* Literal "new" token */
88644       Token tFromCol;             /* Name of column in child table */
88645       Token tToCol;               /* Name of column in parent table */
88646       int iFromCol;               /* Idx of column in child table */
88647       Expr *pEq;                  /* tFromCol = OLD.tToCol */
88648
88649       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
88650       assert( iFromCol>=0 );
88651       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
88652       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
88653
88654       tToCol.n = sqlite3Strlen30(tToCol.z);
88655       tFromCol.n = sqlite3Strlen30(tFromCol.z);
88656
88657       /* Create the expression "OLD.zToCol = zFromCol". It is important
88658       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
88659       ** that the affinity and collation sequence associated with the
88660       ** parent table are used for the comparison. */
88661       pEq = sqlite3PExpr(pParse, TK_EQ,
88662           sqlite3PExpr(pParse, TK_DOT, 
88663             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
88664             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88665           , 0),
88666           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
88667       , 0);
88668       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88669
88670       /* For ON UPDATE, construct the next term of the WHEN clause.
88671       ** The final WHEN clause will be like this:
88672       **
88673       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
88674       */
88675       if( pChanges ){
88676         pEq = sqlite3PExpr(pParse, TK_IS,
88677             sqlite3PExpr(pParse, TK_DOT, 
88678               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
88679               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88680               0),
88681             sqlite3PExpr(pParse, TK_DOT, 
88682               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
88683               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88684               0),
88685             0);
88686         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
88687       }
88688   
88689       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
88690         Expr *pNew;
88691         if( action==OE_Cascade ){
88692           pNew = sqlite3PExpr(pParse, TK_DOT, 
88693             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
88694             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88695           , 0);
88696         }else if( action==OE_SetDflt ){
88697           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
88698           if( pDflt ){
88699             pNew = sqlite3ExprDup(db, pDflt, 0);
88700           }else{
88701             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
88702           }
88703         }else{
88704           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
88705         }
88706         pList = sqlite3ExprListAppend(pParse, pList, pNew);
88707         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
88708       }
88709     }
88710     sqlite3DbFree(db, aiCol);
88711
88712     zFrom = pFKey->pFrom->zName;
88713     nFrom = sqlite3Strlen30(zFrom);
88714
88715     if( action==OE_Restrict ){
88716       Token tFrom;
88717       Expr *pRaise; 
88718
88719       tFrom.z = zFrom;
88720       tFrom.n = nFrom;
88721       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
88722       if( pRaise ){
88723         pRaise->affinity = OE_Abort;
88724       }
88725       pSelect = sqlite3SelectNew(pParse, 
88726           sqlite3ExprListAppend(pParse, 0, pRaise),
88727           sqlite3SrcListAppend(db, 0, &tFrom, 0),
88728           pWhere,
88729           0, 0, 0, 0, 0, 0
88730       );
88731       pWhere = 0;
88732     }
88733
88734     /* Disable lookaside memory allocation */
88735     enableLookaside = db->lookaside.bEnabled;
88736     db->lookaside.bEnabled = 0;
88737
88738     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
88739         sizeof(Trigger) +         /* struct Trigger */
88740         sizeof(TriggerStep) +     /* Single step in trigger program */
88741         nFrom + 1                 /* Space for pStep->target.z */
88742     );
88743     if( pTrigger ){
88744       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
88745       pStep->target.z = (char *)&pStep[1];
88746       pStep->target.n = nFrom;
88747       memcpy((char *)pStep->target.z, zFrom, nFrom);
88748   
88749       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
88750       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
88751       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
88752       if( pWhen ){
88753         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
88754         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
88755       }
88756     }
88757
88758     /* Re-enable the lookaside buffer, if it was disabled earlier. */
88759     db->lookaside.bEnabled = enableLookaside;
88760
88761     sqlite3ExprDelete(db, pWhere);
88762     sqlite3ExprDelete(db, pWhen);
88763     sqlite3ExprListDelete(db, pList);
88764     sqlite3SelectDelete(db, pSelect);
88765     if( db->mallocFailed==1 ){
88766       fkTriggerDelete(db, pTrigger);
88767       return 0;
88768     }
88769     assert( pStep!=0 );
88770
88771     switch( action ){
88772       case OE_Restrict:
88773         pStep->op = TK_SELECT; 
88774         break;
88775       case OE_Cascade: 
88776         if( !pChanges ){ 
88777           pStep->op = TK_DELETE; 
88778           break; 
88779         }
88780       default:
88781         pStep->op = TK_UPDATE;
88782     }
88783     pStep->pTrig = pTrigger;
88784     pTrigger->pSchema = pTab->pSchema;
88785     pTrigger->pTabSchema = pTab->pSchema;
88786     pFKey->apTrigger[iAction] = pTrigger;
88787     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
88788   }
88789
88790   return pTrigger;
88791 }
88792
88793 /*
88794 ** This function is called when deleting or updating a row to implement
88795 ** any required CASCADE, SET NULL or SET DEFAULT actions.
88796 */
88797 SQLITE_PRIVATE void sqlite3FkActions(
88798   Parse *pParse,                  /* Parse context */
88799   Table *pTab,                    /* Table being updated or deleted from */
88800   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
88801   int regOld                      /* Address of array containing old row */
88802 ){
88803   /* If foreign-key support is enabled, iterate through all FKs that 
88804   ** refer to table pTab. If there is an action associated with the FK 
88805   ** for this operation (either update or delete), invoke the associated 
88806   ** trigger sub-program.  */
88807   if( pParse->db->flags&SQLITE_ForeignKeys ){
88808     FKey *pFKey;                  /* Iterator variable */
88809     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88810       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
88811       if( pAction ){
88812         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
88813       }
88814     }
88815   }
88816 }
88817
88818 #endif /* ifndef SQLITE_OMIT_TRIGGER */
88819
88820 /*
88821 ** Free all memory associated with foreign key definitions attached to
88822 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
88823 ** hash table.
88824 */
88825 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
88826   FKey *pFKey;                    /* Iterator variable */
88827   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
88828
88829   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
88830   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
88831
88832     /* Remove the FK from the fkeyHash hash table. */
88833     if( !db || db->pnBytesFreed==0 ){
88834       if( pFKey->pPrevTo ){
88835         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
88836       }else{
88837         void *p = (void *)pFKey->pNextTo;
88838         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
88839         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
88840       }
88841       if( pFKey->pNextTo ){
88842         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
88843       }
88844     }
88845
88846     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
88847     ** classified as either immediate or deferred.
88848     */
88849     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
88850
88851     /* Delete any triggers created to implement actions for this FK. */
88852 #ifndef SQLITE_OMIT_TRIGGER
88853     fkTriggerDelete(db, pFKey->apTrigger[0]);
88854     fkTriggerDelete(db, pFKey->apTrigger[1]);
88855 #endif
88856
88857     pNext = pFKey->pNextFrom;
88858     sqlite3DbFree(db, pFKey);
88859   }
88860 }
88861 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
88862
88863 /************** End of fkey.c ************************************************/
88864 /************** Begin file insert.c ******************************************/
88865 /*
88866 ** 2001 September 15
88867 **
88868 ** The author disclaims copyright to this source code.  In place of
88869 ** a legal notice, here is a blessing:
88870 **
88871 **    May you do good and not evil.
88872 **    May you find forgiveness for yourself and forgive others.
88873 **    May you share freely, never taking more than you give.
88874 **
88875 *************************************************************************
88876 ** This file contains C code routines that are called by the parser
88877 ** to handle INSERT statements in SQLite.
88878 */
88879
88880 /*
88881 ** Generate code that will open a table for reading.
88882 */
88883 SQLITE_PRIVATE void sqlite3OpenTable(
88884   Parse *p,       /* Generate code into this VDBE */
88885   int iCur,       /* The cursor number of the table */
88886   int iDb,        /* The database index in sqlite3.aDb[] */
88887   Table *pTab,    /* The table to be opened */
88888   int opcode      /* OP_OpenRead or OP_OpenWrite */
88889 ){
88890   Vdbe *v;
88891   assert( !IsVirtual(pTab) );
88892   v = sqlite3GetVdbe(p);
88893   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
88894   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
88895   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
88896   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
88897   VdbeComment((v, "%s", pTab->zName));
88898 }
88899
88900 /*
88901 ** Return a pointer to the column affinity string associated with index
88902 ** pIdx. A column affinity string has one character for each column in 
88903 ** the table, according to the affinity of the column:
88904 **
88905 **  Character      Column affinity
88906 **  ------------------------------
88907 **  'a'            TEXT
88908 **  'b'            NONE
88909 **  'c'            NUMERIC
88910 **  'd'            INTEGER
88911 **  'e'            REAL
88912 **
88913 ** An extra 'd' is appended to the end of the string to cover the
88914 ** rowid that appears as the last column in every index.
88915 **
88916 ** Memory for the buffer containing the column index affinity string
88917 ** is managed along with the rest of the Index structure. It will be
88918 ** released when sqlite3DeleteIndex() is called.
88919 */
88920 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
88921   if( !pIdx->zColAff ){
88922     /* The first time a column affinity string for a particular index is
88923     ** required, it is allocated and populated here. It is then stored as
88924     ** a member of the Index structure for subsequent use.
88925     **
88926     ** The column affinity string will eventually be deleted by
88927     ** sqliteDeleteIndex() when the Index structure itself is cleaned
88928     ** up.
88929     */
88930     int n;
88931     Table *pTab = pIdx->pTable;
88932     sqlite3 *db = sqlite3VdbeDb(v);
88933     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
88934     if( !pIdx->zColAff ){
88935       db->mallocFailed = 1;
88936       return 0;
88937     }
88938     for(n=0; n<pIdx->nColumn; n++){
88939       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
88940     }
88941     pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
88942     pIdx->zColAff[n] = 0;
88943   }
88944  
88945   return pIdx->zColAff;
88946 }
88947
88948 /*
88949 ** Set P4 of the most recently inserted opcode to a column affinity
88950 ** string for table pTab. A column affinity string has one character
88951 ** for each column indexed by the index, according to the affinity of the
88952 ** column:
88953 **
88954 **  Character      Column affinity
88955 **  ------------------------------
88956 **  'a'            TEXT
88957 **  'b'            NONE
88958 **  'c'            NUMERIC
88959 **  'd'            INTEGER
88960 **  'e'            REAL
88961 */
88962 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
88963   /* The first time a column affinity string for a particular table
88964   ** is required, it is allocated and populated here. It is then 
88965   ** stored as a member of the Table structure for subsequent use.
88966   **
88967   ** The column affinity string will eventually be deleted by
88968   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
88969   */
88970   if( !pTab->zColAff ){
88971     char *zColAff;
88972     int i;
88973     sqlite3 *db = sqlite3VdbeDb(v);
88974
88975     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
88976     if( !zColAff ){
88977       db->mallocFailed = 1;
88978       return;
88979     }
88980
88981     for(i=0; i<pTab->nCol; i++){
88982       zColAff[i] = pTab->aCol[i].affinity;
88983     }
88984     zColAff[pTab->nCol] = '\0';
88985
88986     pTab->zColAff = zColAff;
88987   }
88988
88989   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
88990 }
88991
88992 /*
88993 ** Return non-zero if the table pTab in database iDb or any of its indices
88994 ** have been opened at any point in the VDBE program beginning at location
88995 ** iStartAddr throught the end of the program.  This is used to see if 
88996 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
88997 ** run without using temporary table for the results of the SELECT. 
88998 */
88999 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
89000   Vdbe *v = sqlite3GetVdbe(p);
89001   int i;
89002   int iEnd = sqlite3VdbeCurrentAddr(v);
89003 #ifndef SQLITE_OMIT_VIRTUALTABLE
89004   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
89005 #endif
89006
89007   for(i=iStartAddr; i<iEnd; i++){
89008     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
89009     assert( pOp!=0 );
89010     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
89011       Index *pIndex;
89012       int tnum = pOp->p2;
89013       if( tnum==pTab->tnum ){
89014         return 1;
89015       }
89016       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
89017         if( tnum==pIndex->tnum ){
89018           return 1;
89019         }
89020       }
89021     }
89022 #ifndef SQLITE_OMIT_VIRTUALTABLE
89023     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
89024       assert( pOp->p4.pVtab!=0 );
89025       assert( pOp->p4type==P4_VTAB );
89026       return 1;
89027     }
89028 #endif
89029   }
89030   return 0;
89031 }
89032
89033 #ifndef SQLITE_OMIT_AUTOINCREMENT
89034 /*
89035 ** Locate or create an AutoincInfo structure associated with table pTab
89036 ** which is in database iDb.  Return the register number for the register
89037 ** that holds the maximum rowid.
89038 **
89039 ** There is at most one AutoincInfo structure per table even if the
89040 ** same table is autoincremented multiple times due to inserts within
89041 ** triggers.  A new AutoincInfo structure is created if this is the
89042 ** first use of table pTab.  On 2nd and subsequent uses, the original
89043 ** AutoincInfo structure is used.
89044 **
89045 ** Three memory locations are allocated:
89046 **
89047 **   (1)  Register to hold the name of the pTab table.
89048 **   (2)  Register to hold the maximum ROWID of pTab.
89049 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
89050 **
89051 ** The 2nd register is the one that is returned.  That is all the
89052 ** insert routine needs to know about.
89053 */
89054 static int autoIncBegin(
89055   Parse *pParse,      /* Parsing context */
89056   int iDb,            /* Index of the database holding pTab */
89057   Table *pTab         /* The table we are writing to */
89058 ){
89059   int memId = 0;      /* Register holding maximum rowid */
89060   if( pTab->tabFlags & TF_Autoincrement ){
89061     Parse *pToplevel = sqlite3ParseToplevel(pParse);
89062     AutoincInfo *pInfo;
89063
89064     pInfo = pToplevel->pAinc;
89065     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
89066     if( pInfo==0 ){
89067       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
89068       if( pInfo==0 ) return 0;
89069       pInfo->pNext = pToplevel->pAinc;
89070       pToplevel->pAinc = pInfo;
89071       pInfo->pTab = pTab;
89072       pInfo->iDb = iDb;
89073       pToplevel->nMem++;                  /* Register to hold name of table */
89074       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
89075       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
89076     }
89077     memId = pInfo->regCtr;
89078   }
89079   return memId;
89080 }
89081
89082 /*
89083 ** This routine generates code that will initialize all of the
89084 ** register used by the autoincrement tracker.  
89085 */
89086 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
89087   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
89088   sqlite3 *db = pParse->db;  /* The database connection */
89089   Db *pDb;                   /* Database only autoinc table */
89090   int memId;                 /* Register holding max rowid */
89091   int addr;                  /* A VDBE address */
89092   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
89093
89094   /* This routine is never called during trigger-generation.  It is
89095   ** only called from the top-level */
89096   assert( pParse->pTriggerTab==0 );
89097   assert( pParse==sqlite3ParseToplevel(pParse) );
89098
89099   assert( v );   /* We failed long ago if this is not so */
89100   for(p = pParse->pAinc; p; p = p->pNext){
89101     pDb = &db->aDb[p->iDb];
89102     memId = p->regCtr;
89103     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
89104     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
89105     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
89106     addr = sqlite3VdbeCurrentAddr(v);
89107     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
89108     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
89109     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
89110     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
89111     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
89112     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
89113     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
89114     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
89115     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
89116     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
89117     sqlite3VdbeAddOp0(v, OP_Close);
89118   }
89119 }
89120
89121 /*
89122 ** Update the maximum rowid for an autoincrement calculation.
89123 **
89124 ** This routine should be called when the top of the stack holds a
89125 ** new rowid that is about to be inserted.  If that new rowid is
89126 ** larger than the maximum rowid in the memId memory cell, then the
89127 ** memory cell is updated.  The stack is unchanged.
89128 */
89129 static void autoIncStep(Parse *pParse, int memId, int regRowid){
89130   if( memId>0 ){
89131     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
89132   }
89133 }
89134
89135 /*
89136 ** This routine generates the code needed to write autoincrement
89137 ** maximum rowid values back into the sqlite_sequence register.
89138 ** Every statement that might do an INSERT into an autoincrement
89139 ** table (either directly or through triggers) needs to call this
89140 ** routine just before the "exit" code.
89141 */
89142 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
89143   AutoincInfo *p;
89144   Vdbe *v = pParse->pVdbe;
89145   sqlite3 *db = pParse->db;
89146
89147   assert( v );
89148   for(p = pParse->pAinc; p; p = p->pNext){
89149     Db *pDb = &db->aDb[p->iDb];
89150     int j1, j2, j3, j4, j5;
89151     int iRec;
89152     int memId = p->regCtr;
89153
89154     iRec = sqlite3GetTempReg(pParse);
89155     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
89156     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
89157     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
89158     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
89159     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
89160     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
89161     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
89162     sqlite3VdbeJumpHere(v, j2);
89163     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
89164     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
89165     sqlite3VdbeJumpHere(v, j4);
89166     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
89167     sqlite3VdbeJumpHere(v, j1);
89168     sqlite3VdbeJumpHere(v, j5);
89169     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
89170     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
89171     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
89172     sqlite3VdbeAddOp0(v, OP_Close);
89173     sqlite3ReleaseTempReg(pParse, iRec);
89174   }
89175 }
89176 #else
89177 /*
89178 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
89179 ** above are all no-ops
89180 */
89181 # define autoIncBegin(A,B,C) (0)
89182 # define autoIncStep(A,B,C)
89183 #endif /* SQLITE_OMIT_AUTOINCREMENT */
89184
89185
89186 /*
89187 ** Generate code for a co-routine that will evaluate a subquery one
89188 ** row at a time.
89189 **
89190 ** The pSelect parameter is the subquery that the co-routine will evaluation.
89191 ** Information about the location of co-routine and the registers it will use
89192 ** is returned by filling in the pDest object.
89193 **
89194 ** Registers are allocated as follows:
89195 **
89196 **   pDest->iSDParm      The register holding the next entry-point of the
89197 **                       co-routine.  Run the co-routine to its next breakpoint
89198 **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
89199 **
89200 **   pDest->iSDParm+1    The register holding the "completed" flag for the
89201 **                       co-routine. This register is 0 if the previous Yield
89202 **                       generated a new result row, or 1 if the subquery
89203 **                       has completed.  If the Yield is called again
89204 **                       after this register becomes 1, then the VDBE will
89205 **                       halt with an SQLITE_INTERNAL error.
89206 **
89207 **   pDest->iSdst        First result register.
89208 **
89209 **   pDest->nSdst        Number of result registers.
89210 **
89211 ** This routine handles all of the register allocation and fills in the
89212 ** pDest structure appropriately.
89213 **
89214 ** Here is a schematic of the generated code assuming that X is the 
89215 ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
89216 ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
89217 ** registers that hold the result set, reg[pDest->iSdst] through
89218 ** reg[pDest->iSdst+pDest->nSdst-1]:
89219 **
89220 **         X <- A
89221 **         EOF <- 0
89222 **         goto B
89223 **      A: setup for the SELECT
89224 **         loop rows in the SELECT
89225 **           load results into registers R..S
89226 **           yield X
89227 **         end loop
89228 **         cleanup after the SELECT
89229 **         EOF <- 1
89230 **         yield X
89231 **         halt-error
89232 **      B:
89233 **
89234 ** To use this subroutine, the caller generates code as follows:
89235 **
89236 **         [ Co-routine generated by this subroutine, shown above ]
89237 **      S: yield X
89238 **         if EOF goto E
89239 **         if skip this row, goto C
89240 **         if terminate loop, goto E
89241 **         deal with this row
89242 **      C: goto S
89243 **      E:
89244 */
89245 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
89246   int regYield;       /* Register holding co-routine entry-point */
89247   int regEof;         /* Register holding co-routine completion flag */
89248   int addrTop;        /* Top of the co-routine */
89249   int j1;             /* Jump instruction */
89250   int rc;             /* Result code */
89251   Vdbe *v;            /* VDBE under construction */
89252
89253   regYield = ++pParse->nMem;
89254   regEof = ++pParse->nMem;
89255   v = sqlite3GetVdbe(pParse);
89256   addrTop = sqlite3VdbeCurrentAddr(v);
89257   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
89258   VdbeComment((v, "Co-routine entry point"));
89259   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
89260   VdbeComment((v, "Co-routine completion flag"));
89261   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
89262   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
89263   rc = sqlite3Select(pParse, pSelect, pDest);
89264   assert( pParse->nErr==0 || rc );
89265   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
89266   if( rc ) return rc;
89267   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
89268   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
89269   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
89270   VdbeComment((v, "End of coroutine"));
89271   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
89272   return rc;
89273 }
89274
89275
89276
89277 /* Forward declaration */
89278 static int xferOptimization(
89279   Parse *pParse,        /* Parser context */
89280   Table *pDest,         /* The table we are inserting into */
89281   Select *pSelect,      /* A SELECT statement to use as the data source */
89282   int onError,          /* How to handle constraint errors */
89283   int iDbDest           /* The database of pDest */
89284 );
89285
89286 /*
89287 ** This routine is call to handle SQL of the following forms:
89288 **
89289 **    insert into TABLE (IDLIST) values(EXPRLIST)
89290 **    insert into TABLE (IDLIST) select
89291 **
89292 ** The IDLIST following the table name is always optional.  If omitted,
89293 ** then a list of all columns for the table is substituted.  The IDLIST
89294 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
89295 **
89296 ** The pList parameter holds EXPRLIST in the first form of the INSERT
89297 ** statement above, and pSelect is NULL.  For the second form, pList is
89298 ** NULL and pSelect is a pointer to the select statement used to generate
89299 ** data for the insert.
89300 **
89301 ** The code generated follows one of four templates.  For a simple
89302 ** select with data coming from a VALUES clause, the code executes
89303 ** once straight down through.  Pseudo-code follows (we call this
89304 ** the "1st template"):
89305 **
89306 **         open write cursor to <table> and its indices
89307 **         puts VALUES clause expressions onto the stack
89308 **         write the resulting record into <table>
89309 **         cleanup
89310 **
89311 ** The three remaining templates assume the statement is of the form
89312 **
89313 **   INSERT INTO <table> SELECT ...
89314 **
89315 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
89316 ** in other words if the SELECT pulls all columns from a single table
89317 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
89318 ** if <table2> and <table1> are distinct tables but have identical
89319 ** schemas, including all the same indices, then a special optimization
89320 ** is invoked that copies raw records from <table2> over to <table1>.
89321 ** See the xferOptimization() function for the implementation of this
89322 ** template.  This is the 2nd template.
89323 **
89324 **         open a write cursor to <table>
89325 **         open read cursor on <table2>
89326 **         transfer all records in <table2> over to <table>
89327 **         close cursors
89328 **         foreach index on <table>
89329 **           open a write cursor on the <table> index
89330 **           open a read cursor on the corresponding <table2> index
89331 **           transfer all records from the read to the write cursors
89332 **           close cursors
89333 **         end foreach
89334 **
89335 ** The 3rd template is for when the second template does not apply
89336 ** and the SELECT clause does not read from <table> at any time.
89337 ** The generated code follows this template:
89338 **
89339 **         EOF <- 0
89340 **         X <- A
89341 **         goto B
89342 **      A: setup for the SELECT
89343 **         loop over the rows in the SELECT
89344 **           load values into registers R..R+n
89345 **           yield X
89346 **         end loop
89347 **         cleanup after the SELECT
89348 **         EOF <- 1
89349 **         yield X
89350 **         goto A
89351 **      B: open write cursor to <table> and its indices
89352 **      C: yield X
89353 **         if EOF goto D
89354 **         insert the select result into <table> from R..R+n
89355 **         goto C
89356 **      D: cleanup
89357 **
89358 ** The 4th template is used if the insert statement takes its
89359 ** values from a SELECT but the data is being inserted into a table
89360 ** that is also read as part of the SELECT.  In the third form,
89361 ** we have to use a intermediate table to store the results of
89362 ** the select.  The template is like this:
89363 **
89364 **         EOF <- 0
89365 **         X <- A
89366 **         goto B
89367 **      A: setup for the SELECT
89368 **         loop over the tables in the SELECT
89369 **           load value into register R..R+n
89370 **           yield X
89371 **         end loop
89372 **         cleanup after the SELECT
89373 **         EOF <- 1
89374 **         yield X
89375 **         halt-error
89376 **      B: open temp table
89377 **      L: yield X
89378 **         if EOF goto M
89379 **         insert row from R..R+n into temp table
89380 **         goto L
89381 **      M: open write cursor to <table> and its indices
89382 **         rewind temp table
89383 **      C: loop over rows of intermediate table
89384 **           transfer values form intermediate table into <table>
89385 **         end loop
89386 **      D: cleanup
89387 */
89388 SQLITE_PRIVATE void sqlite3Insert(
89389   Parse *pParse,        /* Parser context */
89390   SrcList *pTabList,    /* Name of table into which we are inserting */
89391   ExprList *pList,      /* List of values to be inserted */
89392   Select *pSelect,      /* A SELECT statement to use as the data source */
89393   IdList *pColumn,      /* Column names corresponding to IDLIST. */
89394   int onError           /* How to handle constraint errors */
89395 ){
89396   sqlite3 *db;          /* The main database structure */
89397   Table *pTab;          /* The table to insert into.  aka TABLE */
89398   char *zTab;           /* Name of the table into which we are inserting */
89399   const char *zDb;      /* Name of the database holding this table */
89400   int i, j, idx;        /* Loop counters */
89401   Vdbe *v;              /* Generate code into this virtual machine */
89402   Index *pIdx;          /* For looping over indices of the table */
89403   int nColumn;          /* Number of columns in the data */
89404   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
89405   int baseCur = 0;      /* VDBE Cursor number for pTab */
89406   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
89407   int endOfLoop;        /* Label for the end of the insertion loop */
89408   int useTempTable = 0; /* Store SELECT results in intermediate table */
89409   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
89410   int addrInsTop = 0;   /* Jump to label "D" */
89411   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
89412   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
89413   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
89414   int iDb;              /* Index of database holding TABLE */
89415   Db *pDb;              /* The database containing table being inserted into */
89416   int appendFlag = 0;   /* True if the insert is likely to be an append */
89417
89418   /* Register allocations */
89419   int regFromSelect = 0;/* Base register for data coming from SELECT */
89420   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
89421   int regRowCount = 0;  /* Memory cell used for the row counter */
89422   int regIns;           /* Block of regs holding rowid+data being inserted */
89423   int regRowid;         /* registers holding insert rowid */
89424   int regData;          /* register holding first column to insert */
89425   int regEof = 0;       /* Register recording end of SELECT data */
89426   int *aRegIdx = 0;     /* One register allocated to each index */
89427
89428 #ifndef SQLITE_OMIT_TRIGGER
89429   int isView;                 /* True if attempting to insert into a view */
89430   Trigger *pTrigger;          /* List of triggers on pTab, if required */
89431   int tmask;                  /* Mask of trigger times */
89432 #endif
89433
89434   db = pParse->db;
89435   memset(&dest, 0, sizeof(dest));
89436   if( pParse->nErr || db->mallocFailed ){
89437     goto insert_cleanup;
89438   }
89439
89440   /* Locate the table into which we will be inserting new information.
89441   */
89442   assert( pTabList->nSrc==1 );
89443   zTab = pTabList->a[0].zName;
89444   if( NEVER(zTab==0) ) goto insert_cleanup;
89445   pTab = sqlite3SrcListLookup(pParse, pTabList);
89446   if( pTab==0 ){
89447     goto insert_cleanup;
89448   }
89449   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89450   assert( iDb<db->nDb );
89451   pDb = &db->aDb[iDb];
89452   zDb = pDb->zName;
89453   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
89454     goto insert_cleanup;
89455   }
89456
89457   /* Figure out if we have any triggers and if the table being
89458   ** inserted into is a view
89459   */
89460 #ifndef SQLITE_OMIT_TRIGGER
89461   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
89462   isView = pTab->pSelect!=0;
89463 #else
89464 # define pTrigger 0
89465 # define tmask 0
89466 # define isView 0
89467 #endif
89468 #ifdef SQLITE_OMIT_VIEW
89469 # undef isView
89470 # define isView 0
89471 #endif
89472   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
89473
89474   /* If pTab is really a view, make sure it has been initialized.
89475   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
89476   ** module table).
89477   */
89478   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
89479     goto insert_cleanup;
89480   }
89481
89482   /* Ensure that:
89483   *  (a) the table is not read-only, 
89484   *  (b) that if it is a view then ON INSERT triggers exist
89485   */
89486   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
89487     goto insert_cleanup;
89488   }
89489
89490   /* Allocate a VDBE
89491   */
89492   v = sqlite3GetVdbe(pParse);
89493   if( v==0 ) goto insert_cleanup;
89494   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
89495   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
89496
89497 #ifndef SQLITE_OMIT_XFER_OPT
89498   /* If the statement is of the form
89499   **
89500   **       INSERT INTO <table1> SELECT * FROM <table2>;
89501   **
89502   ** Then special optimizations can be applied that make the transfer
89503   ** very fast and which reduce fragmentation of indices.
89504   **
89505   ** This is the 2nd template.
89506   */
89507   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
89508     assert( !pTrigger );
89509     assert( pList==0 );
89510     goto insert_end;
89511   }
89512 #endif /* SQLITE_OMIT_XFER_OPT */
89513
89514   /* If this is an AUTOINCREMENT table, look up the sequence number in the
89515   ** sqlite_sequence table and store it in memory cell regAutoinc.
89516   */
89517   regAutoinc = autoIncBegin(pParse, iDb, pTab);
89518
89519   /* Figure out how many columns of data are supplied.  If the data
89520   ** is coming from a SELECT statement, then generate a co-routine that
89521   ** produces a single row of the SELECT on each invocation.  The
89522   ** co-routine is the common header to the 3rd and 4th templates.
89523   */
89524   if( pSelect ){
89525     /* Data is coming from a SELECT.  Generate a co-routine to run that
89526     ** SELECT. */
89527     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
89528     if( rc ) goto insert_cleanup;
89529
89530     regEof = dest.iSDParm + 1;
89531     regFromSelect = dest.iSdst;
89532     assert( pSelect->pEList );
89533     nColumn = pSelect->pEList->nExpr;
89534     assert( dest.nSdst==nColumn );
89535
89536     /* Set useTempTable to TRUE if the result of the SELECT statement
89537     ** should be written into a temporary table (template 4).  Set to
89538     ** FALSE if each* row of the SELECT can be written directly into
89539     ** the destination table (template 3).
89540     **
89541     ** A temp table must be used if the table being updated is also one
89542     ** of the tables being read by the SELECT statement.  Also use a 
89543     ** temp table in the case of row triggers.
89544     */
89545     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
89546       useTempTable = 1;
89547     }
89548
89549     if( useTempTable ){
89550       /* Invoke the coroutine to extract information from the SELECT
89551       ** and add it to a transient table srcTab.  The code generated
89552       ** here is from the 4th template:
89553       **
89554       **      B: open temp table
89555       **      L: yield X
89556       **         if EOF goto M
89557       **         insert row from R..R+n into temp table
89558       **         goto L
89559       **      M: ...
89560       */
89561       int regRec;          /* Register to hold packed record */
89562       int regTempRowid;    /* Register to hold temp table ROWID */
89563       int addrTop;         /* Label "L" */
89564       int addrIf;          /* Address of jump to M */
89565
89566       srcTab = pParse->nTab++;
89567       regRec = sqlite3GetTempReg(pParse);
89568       regTempRowid = sqlite3GetTempReg(pParse);
89569       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
89570       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
89571       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
89572       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
89573       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
89574       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
89575       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
89576       sqlite3VdbeJumpHere(v, addrIf);
89577       sqlite3ReleaseTempReg(pParse, regRec);
89578       sqlite3ReleaseTempReg(pParse, regTempRowid);
89579     }
89580   }else{
89581     /* This is the case if the data for the INSERT is coming from a VALUES
89582     ** clause
89583     */
89584     NameContext sNC;
89585     memset(&sNC, 0, sizeof(sNC));
89586     sNC.pParse = pParse;
89587     srcTab = -1;
89588     assert( useTempTable==0 );
89589     nColumn = pList ? pList->nExpr : 0;
89590     for(i=0; i<nColumn; i++){
89591       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
89592         goto insert_cleanup;
89593       }
89594     }
89595   }
89596
89597   /* Make sure the number of columns in the source data matches the number
89598   ** of columns to be inserted into the table.
89599   */
89600   if( IsVirtual(pTab) ){
89601     for(i=0; i<pTab->nCol; i++){
89602       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
89603     }
89604   }
89605   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
89606     sqlite3ErrorMsg(pParse, 
89607        "table %S has %d columns but %d values were supplied",
89608        pTabList, 0, pTab->nCol-nHidden, nColumn);
89609     goto insert_cleanup;
89610   }
89611   if( pColumn!=0 && nColumn!=pColumn->nId ){
89612     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
89613     goto insert_cleanup;
89614   }
89615
89616   /* If the INSERT statement included an IDLIST term, then make sure
89617   ** all elements of the IDLIST really are columns of the table and 
89618   ** remember the column indices.
89619   **
89620   ** If the table has an INTEGER PRIMARY KEY column and that column
89621   ** is named in the IDLIST, then record in the keyColumn variable
89622   ** the index into IDLIST of the primary key column.  keyColumn is
89623   ** the index of the primary key as it appears in IDLIST, not as
89624   ** is appears in the original table.  (The index of the primary
89625   ** key in the original table is pTab->iPKey.)
89626   */
89627   if( pColumn ){
89628     for(i=0; i<pColumn->nId; i++){
89629       pColumn->a[i].idx = -1;
89630     }
89631     for(i=0; i<pColumn->nId; i++){
89632       for(j=0; j<pTab->nCol; j++){
89633         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
89634           pColumn->a[i].idx = j;
89635           if( j==pTab->iPKey ){
89636             keyColumn = i;
89637           }
89638           break;
89639         }
89640       }
89641       if( j>=pTab->nCol ){
89642         if( sqlite3IsRowid(pColumn->a[i].zName) ){
89643           keyColumn = i;
89644         }else{
89645           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
89646               pTabList, 0, pColumn->a[i].zName);
89647           pParse->checkSchema = 1;
89648           goto insert_cleanup;
89649         }
89650       }
89651     }
89652   }
89653
89654   /* If there is no IDLIST term but the table has an integer primary
89655   ** key, the set the keyColumn variable to the primary key column index
89656   ** in the original table definition.
89657   */
89658   if( pColumn==0 && nColumn>0 ){
89659     keyColumn = pTab->iPKey;
89660   }
89661     
89662   /* Initialize the count of rows to be inserted
89663   */
89664   if( db->flags & SQLITE_CountRows ){
89665     regRowCount = ++pParse->nMem;
89666     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
89667   }
89668
89669   /* If this is not a view, open the table and and all indices */
89670   if( !isView ){
89671     int nIdx;
89672
89673     baseCur = pParse->nTab;
89674     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
89675     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
89676     if( aRegIdx==0 ){
89677       goto insert_cleanup;
89678     }
89679     for(i=0; i<nIdx; i++){
89680       aRegIdx[i] = ++pParse->nMem;
89681     }
89682   }
89683
89684   /* This is the top of the main insertion loop */
89685   if( useTempTable ){
89686     /* This block codes the top of loop only.  The complete loop is the
89687     ** following pseudocode (template 4):
89688     **
89689     **         rewind temp table
89690     **      C: loop over rows of intermediate table
89691     **           transfer values form intermediate table into <table>
89692     **         end loop
89693     **      D: ...
89694     */
89695     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
89696     addrCont = sqlite3VdbeCurrentAddr(v);
89697   }else if( pSelect ){
89698     /* This block codes the top of loop only.  The complete loop is the
89699     ** following pseudocode (template 3):
89700     **
89701     **      C: yield X
89702     **         if EOF goto D
89703     **         insert the select result into <table> from R..R+n
89704     **         goto C
89705     **      D: ...
89706     */
89707     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
89708     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
89709   }
89710
89711   /* Allocate registers for holding the rowid of the new row,
89712   ** the content of the new row, and the assemblied row record.
89713   */
89714   regRowid = regIns = pParse->nMem+1;
89715   pParse->nMem += pTab->nCol + 1;
89716   if( IsVirtual(pTab) ){
89717     regRowid++;
89718     pParse->nMem++;
89719   }
89720   regData = regRowid+1;
89721
89722   /* Run the BEFORE and INSTEAD OF triggers, if there are any
89723   */
89724   endOfLoop = sqlite3VdbeMakeLabel(v);
89725   if( tmask & TRIGGER_BEFORE ){
89726     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
89727
89728     /* build the NEW.* reference row.  Note that if there is an INTEGER
89729     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
89730     ** translated into a unique ID for the row.  But on a BEFORE trigger,
89731     ** we do not know what the unique ID will be (because the insert has
89732     ** not happened yet) so we substitute a rowid of -1
89733     */
89734     if( keyColumn<0 ){
89735       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
89736     }else{
89737       int j1;
89738       if( useTempTable ){
89739         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
89740       }else{
89741         assert( pSelect==0 );  /* Otherwise useTempTable is true */
89742         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
89743       }
89744       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
89745       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
89746       sqlite3VdbeJumpHere(v, j1);
89747       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
89748     }
89749
89750     /* Cannot have triggers on a virtual table. If it were possible,
89751     ** this block would have to account for hidden column.
89752     */
89753     assert( !IsVirtual(pTab) );
89754
89755     /* Create the new column data
89756     */
89757     for(i=0; i<pTab->nCol; i++){
89758       if( pColumn==0 ){
89759         j = i;
89760       }else{
89761         for(j=0; j<pColumn->nId; j++){
89762           if( pColumn->a[j].idx==i ) break;
89763         }
89764       }
89765       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
89766         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
89767       }else if( useTempTable ){
89768         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
89769       }else{
89770         assert( pSelect==0 ); /* Otherwise useTempTable is true */
89771         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
89772       }
89773     }
89774
89775     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
89776     ** do not attempt any conversions before assembling the record.
89777     ** If this is a real table, attempt conversions as required by the
89778     ** table column affinities.
89779     */
89780     if( !isView ){
89781       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
89782       sqlite3TableAffinityStr(v, pTab);
89783     }
89784
89785     /* Fire BEFORE or INSTEAD OF triggers */
89786     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
89787         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
89788
89789     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
89790   }
89791
89792   /* Push the record number for the new entry onto the stack.  The
89793   ** record number is a randomly generate integer created by NewRowid
89794   ** except when the table has an INTEGER PRIMARY KEY column, in which
89795   ** case the record number is the same as that column. 
89796   */
89797   if( !isView ){
89798     if( IsVirtual(pTab) ){
89799       /* The row that the VUpdate opcode will delete: none */
89800       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
89801     }
89802     if( keyColumn>=0 ){
89803       if( useTempTable ){
89804         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
89805       }else if( pSelect ){
89806         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
89807       }else{
89808         VdbeOp *pOp;
89809         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
89810         pOp = sqlite3VdbeGetOp(v, -1);
89811         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
89812           appendFlag = 1;
89813           pOp->opcode = OP_NewRowid;
89814           pOp->p1 = baseCur;
89815           pOp->p2 = regRowid;
89816           pOp->p3 = regAutoinc;
89817         }
89818       }
89819       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
89820       ** to generate a unique primary key value.
89821       */
89822       if( !appendFlag ){
89823         int j1;
89824         if( !IsVirtual(pTab) ){
89825           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
89826           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89827           sqlite3VdbeJumpHere(v, j1);
89828         }else{
89829           j1 = sqlite3VdbeCurrentAddr(v);
89830           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
89831         }
89832         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
89833       }
89834     }else if( IsVirtual(pTab) ){
89835       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
89836     }else{
89837       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89838       appendFlag = 1;
89839     }
89840     autoIncStep(pParse, regAutoinc, regRowid);
89841
89842     /* Push onto the stack, data for all columns of the new entry, beginning
89843     ** with the first column.
89844     */
89845     nHidden = 0;
89846     for(i=0; i<pTab->nCol; i++){
89847       int iRegStore = regRowid+1+i;
89848       if( i==pTab->iPKey ){
89849         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
89850         ** Whenever this column is read, the record number will be substituted
89851         ** in its place.  So will fill this column with a NULL to avoid
89852         ** taking up data space with information that will never be used. */
89853         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
89854         continue;
89855       }
89856       if( pColumn==0 ){
89857         if( IsHiddenColumn(&pTab->aCol[i]) ){
89858           assert( IsVirtual(pTab) );
89859           j = -1;
89860           nHidden++;
89861         }else{
89862           j = i - nHidden;
89863         }
89864       }else{
89865         for(j=0; j<pColumn->nId; j++){
89866           if( pColumn->a[j].idx==i ) break;
89867         }
89868       }
89869       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
89870         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
89871       }else if( useTempTable ){
89872         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
89873       }else if( pSelect ){
89874         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
89875       }else{
89876         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
89877       }
89878     }
89879
89880     /* Generate code to check constraints and generate index keys and
89881     ** do the insertion.
89882     */
89883 #ifndef SQLITE_OMIT_VIRTUALTABLE
89884     if( IsVirtual(pTab) ){
89885       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
89886       sqlite3VtabMakeWritable(pParse, pTab);
89887       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
89888       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
89889       sqlite3MayAbort(pParse);
89890     }else
89891 #endif
89892     {
89893       int isReplace;    /* Set to true if constraints may cause a replace */
89894       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
89895           keyColumn>=0, 0, onError, endOfLoop, &isReplace
89896       );
89897       sqlite3FkCheck(pParse, pTab, 0, regIns);
89898       sqlite3CompleteInsertion(
89899           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
89900       );
89901     }
89902   }
89903
89904   /* Update the count of rows that are inserted
89905   */
89906   if( (db->flags & SQLITE_CountRows)!=0 ){
89907     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
89908   }
89909
89910   if( pTrigger ){
89911     /* Code AFTER triggers */
89912     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
89913         pTab, regData-2-pTab->nCol, onError, endOfLoop);
89914   }
89915
89916   /* The bottom of the main insertion loop, if the data source
89917   ** is a SELECT statement.
89918   */
89919   sqlite3VdbeResolveLabel(v, endOfLoop);
89920   if( useTempTable ){
89921     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
89922     sqlite3VdbeJumpHere(v, addrInsTop);
89923     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
89924   }else if( pSelect ){
89925     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
89926     sqlite3VdbeJumpHere(v, addrInsTop);
89927   }
89928
89929   if( !IsVirtual(pTab) && !isView ){
89930     /* Close all tables opened */
89931     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
89932     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
89933       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
89934     }
89935   }
89936
89937 insert_end:
89938   /* Update the sqlite_sequence table by storing the content of the
89939   ** maximum rowid counter values recorded while inserting into
89940   ** autoincrement tables.
89941   */
89942   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
89943     sqlite3AutoincrementEnd(pParse);
89944   }
89945
89946   /*
89947   ** Return the number of rows inserted. If this routine is 
89948   ** generating code because of a call to sqlite3NestedParse(), do not
89949   ** invoke the callback function.
89950   */
89951   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
89952     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
89953     sqlite3VdbeSetNumCols(v, 1);
89954     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
89955   }
89956
89957 insert_cleanup:
89958   sqlite3SrcListDelete(db, pTabList);
89959   sqlite3ExprListDelete(db, pList);
89960   sqlite3SelectDelete(db, pSelect);
89961   sqlite3IdListDelete(db, pColumn);
89962   sqlite3DbFree(db, aRegIdx);
89963 }
89964
89965 /* Make sure "isView" and other macros defined above are undefined. Otherwise
89966 ** thely may interfere with compilation of other functions in this file
89967 ** (or in another file, if this file becomes part of the amalgamation).  */
89968 #ifdef isView
89969  #undef isView
89970 #endif
89971 #ifdef pTrigger
89972  #undef pTrigger
89973 #endif
89974 #ifdef tmask
89975  #undef tmask
89976 #endif
89977
89978
89979 /*
89980 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
89981 **
89982 ** The input is a range of consecutive registers as follows:
89983 **
89984 **    1.  The rowid of the row after the update.
89985 **
89986 **    2.  The data in the first column of the entry after the update.
89987 **
89988 **    i.  Data from middle columns...
89989 **
89990 **    N.  The data in the last column of the entry after the update.
89991 **
89992 ** The regRowid parameter is the index of the register containing (1).
89993 **
89994 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
89995 ** the address of a register containing the rowid before the update takes
89996 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
89997 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
89998 ** indicates that the rowid was explicitly specified as part of the
89999 ** INSERT statement. If rowidChng is false, it means that  the rowid is
90000 ** computed automatically in an insert or that the rowid value is not 
90001 ** modified by an update.
90002 **
90003 ** The code generated by this routine store new index entries into
90004 ** registers identified by aRegIdx[].  No index entry is created for
90005 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
90006 ** the same as the order of indices on the linked list of indices
90007 ** attached to the table.
90008 **
90009 ** This routine also generates code to check constraints.  NOT NULL,
90010 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
90011 ** then the appropriate action is performed.  There are five possible
90012 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
90013 **
90014 **  Constraint type  Action       What Happens
90015 **  ---------------  ----------   ----------------------------------------
90016 **  any              ROLLBACK     The current transaction is rolled back and
90017 **                                sqlite3_exec() returns immediately with a
90018 **                                return code of SQLITE_CONSTRAINT.
90019 **
90020 **  any              ABORT        Back out changes from the current command
90021 **                                only (do not do a complete rollback) then
90022 **                                cause sqlite3_exec() to return immediately
90023 **                                with SQLITE_CONSTRAINT.
90024 **
90025 **  any              FAIL         Sqlite3_exec() returns immediately with a
90026 **                                return code of SQLITE_CONSTRAINT.  The
90027 **                                transaction is not rolled back and any
90028 **                                prior changes are retained.
90029 **
90030 **  any              IGNORE       The record number and data is popped from
90031 **                                the stack and there is an immediate jump
90032 **                                to label ignoreDest.
90033 **
90034 **  NOT NULL         REPLACE      The NULL value is replace by the default
90035 **                                value for that column.  If the default value
90036 **                                is NULL, the action is the same as ABORT.
90037 **
90038 **  UNIQUE           REPLACE      The other row that conflicts with the row
90039 **                                being inserted is removed.
90040 **
90041 **  CHECK            REPLACE      Illegal.  The results in an exception.
90042 **
90043 ** Which action to take is determined by the overrideError parameter.
90044 ** Or if overrideError==OE_Default, then the pParse->onError parameter
90045 ** is used.  Or if pParse->onError==OE_Default then the onError value
90046 ** for the constraint is used.
90047 **
90048 ** The calling routine must open a read/write cursor for pTab with
90049 ** cursor number "baseCur".  All indices of pTab must also have open
90050 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
90051 ** Except, if there is no possibility of a REPLACE action then
90052 ** cursors do not need to be open for indices where aRegIdx[i]==0.
90053 */
90054 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
90055   Parse *pParse,      /* The parser context */
90056   Table *pTab,        /* the table into which we are inserting */
90057   int baseCur,        /* Index of a read/write cursor pointing at pTab */
90058   int regRowid,       /* Index of the range of input registers */
90059   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
90060   int rowidChng,      /* True if the rowid might collide with existing entry */
90061   int isUpdate,       /* True for UPDATE, False for INSERT */
90062   int overrideError,  /* Override onError to this if not OE_Default */
90063   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
90064   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
90065 ){
90066   int i;              /* loop counter */
90067   Vdbe *v;            /* VDBE under constrution */
90068   int nCol;           /* Number of columns */
90069   int onError;        /* Conflict resolution strategy */
90070   int j1;             /* Addresss of jump instruction */
90071   int j2 = 0, j3;     /* Addresses of jump instructions */
90072   int regData;        /* Register containing first data column */
90073   int iCur;           /* Table cursor number */
90074   Index *pIdx;         /* Pointer to one of the indices */
90075   sqlite3 *db;         /* Database connection */
90076   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
90077   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
90078
90079   db = pParse->db;
90080   v = sqlite3GetVdbe(pParse);
90081   assert( v!=0 );
90082   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
90083   nCol = pTab->nCol;
90084   regData = regRowid + 1;
90085
90086   /* Test all NOT NULL constraints.
90087   */
90088   for(i=0; i<nCol; i++){
90089     if( i==pTab->iPKey ){
90090       continue;
90091     }
90092     onError = pTab->aCol[i].notNull;
90093     if( onError==OE_None ) continue;
90094     if( overrideError!=OE_Default ){
90095       onError = overrideError;
90096     }else if( onError==OE_Default ){
90097       onError = OE_Abort;
90098     }
90099     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
90100       onError = OE_Abort;
90101     }
90102     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
90103         || onError==OE_Ignore || onError==OE_Replace );
90104     switch( onError ){
90105       case OE_Abort:
90106         sqlite3MayAbort(pParse);
90107       case OE_Rollback:
90108       case OE_Fail: {
90109         char *zMsg;
90110         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
90111                           SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
90112         zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
90113                               pTab->zName, pTab->aCol[i].zName);
90114         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
90115         break;
90116       }
90117       case OE_Ignore: {
90118         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
90119         break;
90120       }
90121       default: {
90122         assert( onError==OE_Replace );
90123         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
90124         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
90125         sqlite3VdbeJumpHere(v, j1);
90126         break;
90127       }
90128     }
90129   }
90130
90131   /* Test all CHECK constraints
90132   */
90133 #ifndef SQLITE_OMIT_CHECK
90134   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
90135     ExprList *pCheck = pTab->pCheck;
90136     pParse->ckBase = regData;
90137     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
90138     for(i=0; i<pCheck->nExpr; i++){
90139       int allOk = sqlite3VdbeMakeLabel(v);
90140       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
90141       if( onError==OE_Ignore ){
90142         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90143       }else{
90144         char *zConsName = pCheck->a[i].zName;
90145         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
90146         if( zConsName ){
90147           zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
90148         }else{
90149           zConsName = 0;
90150         }
90151         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
90152                               onError, zConsName, P4_DYNAMIC);
90153       }
90154       sqlite3VdbeResolveLabel(v, allOk);
90155     }
90156   }
90157 #endif /* !defined(SQLITE_OMIT_CHECK) */
90158
90159   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
90160   ** of the new record does not previously exist.  Except, if this
90161   ** is an UPDATE and the primary key is not changing, that is OK.
90162   */
90163   if( rowidChng ){
90164     onError = pTab->keyConf;
90165     if( overrideError!=OE_Default ){
90166       onError = overrideError;
90167     }else if( onError==OE_Default ){
90168       onError = OE_Abort;
90169     }
90170     
90171     if( isUpdate ){
90172       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
90173     }
90174     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
90175     switch( onError ){
90176       default: {
90177         onError = OE_Abort;
90178         /* Fall thru into the next case */
90179       }
90180       case OE_Rollback:
90181       case OE_Abort:
90182       case OE_Fail: {
90183         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
90184            onError, "PRIMARY KEY must be unique", P4_STATIC);
90185         break;
90186       }
90187       case OE_Replace: {
90188         /* If there are DELETE triggers on this table and the
90189         ** recursive-triggers flag is set, call GenerateRowDelete() to
90190         ** remove the conflicting row from the table. This will fire
90191         ** the triggers and remove both the table and index b-tree entries.
90192         **
90193         ** Otherwise, if there are no triggers or the recursive-triggers
90194         ** flag is not set, but the table has one or more indexes, call 
90195         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
90196         ** only. The table b-tree entry will be replaced by the new entry 
90197         ** when it is inserted.  
90198         **
90199         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
90200         ** also invoke MultiWrite() to indicate that this VDBE may require
90201         ** statement rollback (if the statement is aborted after the delete
90202         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
90203         ** but being more selective here allows statements like:
90204         **
90205         **   REPLACE INTO t(rowid) VALUES($newrowid)
90206         **
90207         ** to run without a statement journal if there are no indexes on the
90208         ** table.
90209         */
90210         Trigger *pTrigger = 0;
90211         if( db->flags&SQLITE_RecTriggers ){
90212           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
90213         }
90214         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
90215           sqlite3MultiWrite(pParse);
90216           sqlite3GenerateRowDelete(
90217               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
90218           );
90219         }else if( pTab->pIndex ){
90220           sqlite3MultiWrite(pParse);
90221           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
90222         }
90223         seenReplace = 1;
90224         break;
90225       }
90226       case OE_Ignore: {
90227         assert( seenReplace==0 );
90228         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90229         break;
90230       }
90231     }
90232     sqlite3VdbeJumpHere(v, j3);
90233     if( isUpdate ){
90234       sqlite3VdbeJumpHere(v, j2);
90235     }
90236   }
90237
90238   /* Test all UNIQUE constraints by creating entries for each UNIQUE
90239   ** index and making sure that duplicate entries do not already exist.
90240   ** Add the new records to the indices as we go.
90241   */
90242   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
90243     int regIdx;
90244     int regR;
90245
90246     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
90247
90248     /* Create a key for accessing the index entry */
90249     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
90250     for(i=0; i<pIdx->nColumn; i++){
90251       int idx = pIdx->aiColumn[i];
90252       if( idx==pTab->iPKey ){
90253         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
90254       }else{
90255         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
90256       }
90257     }
90258     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
90259     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
90260     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
90261     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
90262
90263     /* Find out what action to take in case there is an indexing conflict */
90264     onError = pIdx->onError;
90265     if( onError==OE_None ){ 
90266       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
90267       continue;  /* pIdx is not a UNIQUE index */
90268     }
90269     if( overrideError!=OE_Default ){
90270       onError = overrideError;
90271     }else if( onError==OE_Default ){
90272       onError = OE_Abort;
90273     }
90274     if( seenReplace ){
90275       if( onError==OE_Ignore ) onError = OE_Replace;
90276       else if( onError==OE_Fail ) onError = OE_Abort;
90277     }
90278     
90279     /* Check to see if the new index entry will be unique */
90280     regR = sqlite3GetTempReg(pParse);
90281     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
90282     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
90283                            regR, SQLITE_INT_TO_PTR(regIdx),
90284                            P4_INT32);
90285     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
90286
90287     /* Generate code that executes if the new index entry is not unique */
90288     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
90289         || onError==OE_Ignore || onError==OE_Replace );
90290     switch( onError ){
90291       case OE_Rollback:
90292       case OE_Abort:
90293       case OE_Fail: {
90294         int j;
90295         StrAccum errMsg;
90296         const char *zSep;
90297         char *zErr;
90298
90299         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
90300         errMsg.db = db;
90301         zSep = pIdx->nColumn>1 ? "columns " : "column ";
90302         for(j=0; j<pIdx->nColumn; j++){
90303           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
90304           sqlite3StrAccumAppend(&errMsg, zSep, -1);
90305           zSep = ", ";
90306           sqlite3StrAccumAppend(&errMsg, zCol, -1);
90307         }
90308         sqlite3StrAccumAppend(&errMsg,
90309             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
90310         zErr = sqlite3StrAccumFinish(&errMsg);
90311         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
90312                               onError, zErr, 0);
90313         sqlite3DbFree(errMsg.db, zErr);
90314         break;
90315       }
90316       case OE_Ignore: {
90317         assert( seenReplace==0 );
90318         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90319         break;
90320       }
90321       default: {
90322         Trigger *pTrigger = 0;
90323         assert( onError==OE_Replace );
90324         sqlite3MultiWrite(pParse);
90325         if( db->flags&SQLITE_RecTriggers ){
90326           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
90327         }
90328         sqlite3GenerateRowDelete(
90329             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
90330         );
90331         seenReplace = 1;
90332         break;
90333       }
90334     }
90335     sqlite3VdbeJumpHere(v, j3);
90336     sqlite3ReleaseTempReg(pParse, regR);
90337   }
90338   
90339   if( pbMayReplace ){
90340     *pbMayReplace = seenReplace;
90341   }
90342 }
90343
90344 /*
90345 ** This routine generates code to finish the INSERT or UPDATE operation
90346 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
90347 ** A consecutive range of registers starting at regRowid contains the
90348 ** rowid and the content to be inserted.
90349 **
90350 ** The arguments to this routine should be the same as the first six
90351 ** arguments to sqlite3GenerateConstraintChecks.
90352 */
90353 SQLITE_PRIVATE void sqlite3CompleteInsertion(
90354   Parse *pParse,      /* The parser context */
90355   Table *pTab,        /* the table into which we are inserting */
90356   int baseCur,        /* Index of a read/write cursor pointing at pTab */
90357   int regRowid,       /* Range of content */
90358   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
90359   int isUpdate,       /* True for UPDATE, False for INSERT */
90360   int appendBias,     /* True if this is likely to be an append */
90361   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
90362 ){
90363   int i;
90364   Vdbe *v;
90365   int nIdx;
90366   Index *pIdx;
90367   u8 pik_flags;
90368   int regData;
90369   int regRec;
90370
90371   v = sqlite3GetVdbe(pParse);
90372   assert( v!=0 );
90373   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
90374   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
90375   for(i=nIdx-1; i>=0; i--){
90376     if( aRegIdx[i]==0 ) continue;
90377     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
90378     if( useSeekResult ){
90379       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
90380     }
90381   }
90382   regData = regRowid + 1;
90383   regRec = sqlite3GetTempReg(pParse);
90384   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
90385   sqlite3TableAffinityStr(v, pTab);
90386   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
90387   if( pParse->nested ){
90388     pik_flags = 0;
90389   }else{
90390     pik_flags = OPFLAG_NCHANGE;
90391     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
90392   }
90393   if( appendBias ){
90394     pik_flags |= OPFLAG_APPEND;
90395   }
90396   if( useSeekResult ){
90397     pik_flags |= OPFLAG_USESEEKRESULT;
90398   }
90399   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
90400   if( !pParse->nested ){
90401     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
90402   }
90403   sqlite3VdbeChangeP5(v, pik_flags);
90404 }
90405
90406 /*
90407 ** Generate code that will open cursors for a table and for all
90408 ** indices of that table.  The "baseCur" parameter is the cursor number used
90409 ** for the table.  Indices are opened on subsequent cursors.
90410 **
90411 ** Return the number of indices on the table.
90412 */
90413 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
90414   Parse *pParse,   /* Parsing context */
90415   Table *pTab,     /* Table to be opened */
90416   int baseCur,     /* Cursor number assigned to the table */
90417   int op           /* OP_OpenRead or OP_OpenWrite */
90418 ){
90419   int i;
90420   int iDb;
90421   Index *pIdx;
90422   Vdbe *v;
90423
90424   if( IsVirtual(pTab) ) return 0;
90425   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
90426   v = sqlite3GetVdbe(pParse);
90427   assert( v!=0 );
90428   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
90429   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
90430     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
90431     assert( pIdx->pSchema==pTab->pSchema );
90432     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
90433                       (char*)pKey, P4_KEYINFO_HANDOFF);
90434     VdbeComment((v, "%s", pIdx->zName));
90435   }
90436   if( pParse->nTab<baseCur+i ){
90437     pParse->nTab = baseCur+i;
90438   }
90439   return i-1;
90440 }
90441
90442
90443 #ifdef SQLITE_TEST
90444 /*
90445 ** The following global variable is incremented whenever the
90446 ** transfer optimization is used.  This is used for testing
90447 ** purposes only - to make sure the transfer optimization really
90448 ** is happening when it is suppose to.
90449 */
90450 SQLITE_API int sqlite3_xferopt_count;
90451 #endif /* SQLITE_TEST */
90452
90453
90454 #ifndef SQLITE_OMIT_XFER_OPT
90455 /*
90456 ** Check to collation names to see if they are compatible.
90457 */
90458 static int xferCompatibleCollation(const char *z1, const char *z2){
90459   if( z1==0 ){
90460     return z2==0;
90461   }
90462   if( z2==0 ){
90463     return 0;
90464   }
90465   return sqlite3StrICmp(z1, z2)==0;
90466 }
90467
90468
90469 /*
90470 ** Check to see if index pSrc is compatible as a source of data
90471 ** for index pDest in an insert transfer optimization.  The rules
90472 ** for a compatible index:
90473 **
90474 **    *   The index is over the same set of columns
90475 **    *   The same DESC and ASC markings occurs on all columns
90476 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
90477 **    *   The same collating sequence on each column
90478 */
90479 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
90480   int i;
90481   assert( pDest && pSrc );
90482   assert( pDest->pTable!=pSrc->pTable );
90483   if( pDest->nColumn!=pSrc->nColumn ){
90484     return 0;   /* Different number of columns */
90485   }
90486   if( pDest->onError!=pSrc->onError ){
90487     return 0;   /* Different conflict resolution strategies */
90488   }
90489   for(i=0; i<pSrc->nColumn; i++){
90490     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
90491       return 0;   /* Different columns indexed */
90492     }
90493     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
90494       return 0;   /* Different sort orders */
90495     }
90496     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
90497       return 0;   /* Different collating sequences */
90498     }
90499   }
90500
90501   /* If no test above fails then the indices must be compatible */
90502   return 1;
90503 }
90504
90505 /*
90506 ** Attempt the transfer optimization on INSERTs of the form
90507 **
90508 **     INSERT INTO tab1 SELECT * FROM tab2;
90509 **
90510 ** The xfer optimization transfers raw records from tab2 over to tab1.  
90511 ** Columns are not decoded and reassemblied, which greatly improves
90512 ** performance.  Raw index records are transferred in the same way.
90513 **
90514 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
90515 ** There are lots of rules for determining compatibility - see comments
90516 ** embedded in the code for details.
90517 **
90518 ** This routine returns TRUE if the optimization is guaranteed to be used.
90519 ** Sometimes the xfer optimization will only work if the destination table
90520 ** is empty - a factor that can only be determined at run-time.  In that
90521 ** case, this routine generates code for the xfer optimization but also
90522 ** does a test to see if the destination table is empty and jumps over the
90523 ** xfer optimization code if the test fails.  In that case, this routine
90524 ** returns FALSE so that the caller will know to go ahead and generate
90525 ** an unoptimized transfer.  This routine also returns FALSE if there
90526 ** is no chance that the xfer optimization can be applied.
90527 **
90528 ** This optimization is particularly useful at making VACUUM run faster.
90529 */
90530 static int xferOptimization(
90531   Parse *pParse,        /* Parser context */
90532   Table *pDest,         /* The table we are inserting into */
90533   Select *pSelect,      /* A SELECT statement to use as the data source */
90534   int onError,          /* How to handle constraint errors */
90535   int iDbDest           /* The database of pDest */
90536 ){
90537   ExprList *pEList;                /* The result set of the SELECT */
90538   Table *pSrc;                     /* The table in the FROM clause of SELECT */
90539   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
90540   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
90541   int i;                           /* Loop counter */
90542   int iDbSrc;                      /* The database of pSrc */
90543   int iSrc, iDest;                 /* Cursors from source and destination */
90544   int addr1, addr2;                /* Loop addresses */
90545   int emptyDestTest;               /* Address of test for empty pDest */
90546   int emptySrcTest;                /* Address of test for empty pSrc */
90547   Vdbe *v;                         /* The VDBE we are building */
90548   KeyInfo *pKey;                   /* Key information for an index */
90549   int regAutoinc;                  /* Memory register used by AUTOINC */
90550   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
90551   int regData, regRowid;           /* Registers holding data and rowid */
90552
90553   if( pSelect==0 ){
90554     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
90555   }
90556   if( sqlite3TriggerList(pParse, pDest) ){
90557     return 0;   /* tab1 must not have triggers */
90558   }
90559 #ifndef SQLITE_OMIT_VIRTUALTABLE
90560   if( pDest->tabFlags & TF_Virtual ){
90561     return 0;   /* tab1 must not be a virtual table */
90562   }
90563 #endif
90564   if( onError==OE_Default ){
90565     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
90566     if( onError==OE_Default ) onError = OE_Abort;
90567   }
90568   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
90569   if( pSelect->pSrc->nSrc!=1 ){
90570     return 0;   /* FROM clause must have exactly one term */
90571   }
90572   if( pSelect->pSrc->a[0].pSelect ){
90573     return 0;   /* FROM clause cannot contain a subquery */
90574   }
90575   if( pSelect->pWhere ){
90576     return 0;   /* SELECT may not have a WHERE clause */
90577   }
90578   if( pSelect->pOrderBy ){
90579     return 0;   /* SELECT may not have an ORDER BY clause */
90580   }
90581   /* Do not need to test for a HAVING clause.  If HAVING is present but
90582   ** there is no ORDER BY, we will get an error. */
90583   if( pSelect->pGroupBy ){
90584     return 0;   /* SELECT may not have a GROUP BY clause */
90585   }
90586   if( pSelect->pLimit ){
90587     return 0;   /* SELECT may not have a LIMIT clause */
90588   }
90589   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
90590   if( pSelect->pPrior ){
90591     return 0;   /* SELECT may not be a compound query */
90592   }
90593   if( pSelect->selFlags & SF_Distinct ){
90594     return 0;   /* SELECT may not be DISTINCT */
90595   }
90596   pEList = pSelect->pEList;
90597   assert( pEList!=0 );
90598   if( pEList->nExpr!=1 ){
90599     return 0;   /* The result set must have exactly one column */
90600   }
90601   assert( pEList->a[0].pExpr );
90602   if( pEList->a[0].pExpr->op!=TK_ALL ){
90603     return 0;   /* The result set must be the special operator "*" */
90604   }
90605
90606   /* At this point we have established that the statement is of the
90607   ** correct syntactic form to participate in this optimization.  Now
90608   ** we have to check the semantics.
90609   */
90610   pItem = pSelect->pSrc->a;
90611   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
90612   if( pSrc==0 ){
90613     return 0;   /* FROM clause does not contain a real table */
90614   }
90615   if( pSrc==pDest ){
90616     return 0;   /* tab1 and tab2 may not be the same table */
90617   }
90618 #ifndef SQLITE_OMIT_VIRTUALTABLE
90619   if( pSrc->tabFlags & TF_Virtual ){
90620     return 0;   /* tab2 must not be a virtual table */
90621   }
90622 #endif
90623   if( pSrc->pSelect ){
90624     return 0;   /* tab2 may not be a view */
90625   }
90626   if( pDest->nCol!=pSrc->nCol ){
90627     return 0;   /* Number of columns must be the same in tab1 and tab2 */
90628   }
90629   if( pDest->iPKey!=pSrc->iPKey ){
90630     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
90631   }
90632   for(i=0; i<pDest->nCol; i++){
90633     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
90634       return 0;    /* Affinity must be the same on all columns */
90635     }
90636     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
90637       return 0;    /* Collating sequence must be the same on all columns */
90638     }
90639     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
90640       return 0;    /* tab2 must be NOT NULL if tab1 is */
90641     }
90642   }
90643   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90644     if( pDestIdx->onError!=OE_None ){
90645       destHasUniqueIdx = 1;
90646     }
90647     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
90648       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90649     }
90650     if( pSrcIdx==0 ){
90651       return 0;    /* pDestIdx has no corresponding index in pSrc */
90652     }
90653   }
90654 #ifndef SQLITE_OMIT_CHECK
90655   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck, pDest->pCheck) ){
90656     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
90657   }
90658 #endif
90659 #ifndef SQLITE_OMIT_FOREIGN_KEY
90660   /* Disallow the transfer optimization if the destination table constains
90661   ** any foreign key constraints.  This is more restrictive than necessary.
90662   ** But the main beneficiary of the transfer optimization is the VACUUM 
90663   ** command, and the VACUUM command disables foreign key constraints.  So
90664   ** the extra complication to make this rule less restrictive is probably
90665   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
90666   */
90667   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
90668     return 0;
90669   }
90670 #endif
90671   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
90672     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
90673   }
90674
90675   /* If we get this far, it means that the xfer optimization is at
90676   ** least a possibility, though it might only work if the destination
90677   ** table (tab1) is initially empty.
90678   */
90679 #ifdef SQLITE_TEST
90680   sqlite3_xferopt_count++;
90681 #endif
90682   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
90683   v = sqlite3GetVdbe(pParse);
90684   sqlite3CodeVerifySchema(pParse, iDbSrc);
90685   iSrc = pParse->nTab++;
90686   iDest = pParse->nTab++;
90687   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
90688   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
90689   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
90690    || destHasUniqueIdx                              /* (2) */
90691    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
90692   ){
90693     /* In some circumstances, we are able to run the xfer optimization
90694     ** only if the destination table is initially empty.  This code makes
90695     ** that determination.  Conditions under which the destination must
90696     ** be empty:
90697     **
90698     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
90699     **     (If the destination is not initially empty, the rowid fields
90700     **     of index entries might need to change.)
90701     **
90702     ** (2) The destination has a unique index.  (The xfer optimization 
90703     **     is unable to test uniqueness.)
90704     **
90705     ** (3) onError is something other than OE_Abort and OE_Rollback.
90706     */
90707     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
90708     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
90709     sqlite3VdbeJumpHere(v, addr1);
90710   }else{
90711     emptyDestTest = 0;
90712   }
90713   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
90714   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90715   regData = sqlite3GetTempReg(pParse);
90716   regRowid = sqlite3GetTempReg(pParse);
90717   if( pDest->iPKey>=0 ){
90718     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90719     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
90720     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
90721         onError, "PRIMARY KEY must be unique", P4_STATIC);
90722     sqlite3VdbeJumpHere(v, addr2);
90723     autoIncStep(pParse, regAutoinc, regRowid);
90724   }else if( pDest->pIndex==0 ){
90725     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
90726   }else{
90727     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90728     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
90729   }
90730   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
90731   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
90732   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
90733   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
90734   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
90735   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90736     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
90737       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90738     }
90739     assert( pSrcIdx );
90740     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
90741     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90742     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
90743     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
90744                       (char*)pKey, P4_KEYINFO_HANDOFF);
90745     VdbeComment((v, "%s", pSrcIdx->zName));
90746     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
90747     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
90748                       (char*)pKey, P4_KEYINFO_HANDOFF);
90749     VdbeComment((v, "%s", pDestIdx->zName));
90750     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90751     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
90752     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
90753     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
90754     sqlite3VdbeJumpHere(v, addr1);
90755   }
90756   sqlite3VdbeJumpHere(v, emptySrcTest);
90757   sqlite3ReleaseTempReg(pParse, regRowid);
90758   sqlite3ReleaseTempReg(pParse, regData);
90759   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
90760   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90761   if( emptyDestTest ){
90762     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
90763     sqlite3VdbeJumpHere(v, emptyDestTest);
90764     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90765     return 0;
90766   }else{
90767     return 1;
90768   }
90769 }
90770 #endif /* SQLITE_OMIT_XFER_OPT */
90771
90772 /************** End of insert.c **********************************************/
90773 /************** Begin file legacy.c ******************************************/
90774 /*
90775 ** 2001 September 15
90776 **
90777 ** The author disclaims copyright to this source code.  In place of
90778 ** a legal notice, here is a blessing:
90779 **
90780 **    May you do good and not evil.
90781 **    May you find forgiveness for yourself and forgive others.
90782 **    May you share freely, never taking more than you give.
90783 **
90784 *************************************************************************
90785 ** Main file for the SQLite library.  The routines in this file
90786 ** implement the programmer interface to the library.  Routines in
90787 ** other files are for internal use by SQLite and should not be
90788 ** accessed by users of the library.
90789 */
90790
90791
90792 /*
90793 ** Execute SQL code.  Return one of the SQLITE_ success/failure
90794 ** codes.  Also write an error message into memory obtained from
90795 ** malloc() and make *pzErrMsg point to that message.
90796 **
90797 ** If the SQL is a query, then for each row in the query result
90798 ** the xCallback() function is called.  pArg becomes the first
90799 ** argument to xCallback().  If xCallback=NULL then no callback
90800 ** is invoked, even for queries.
90801 */
90802 SQLITE_API int sqlite3_exec(
90803   sqlite3 *db,                /* The database on which the SQL executes */
90804   const char *zSql,           /* The SQL to be executed */
90805   sqlite3_callback xCallback, /* Invoke this callback routine */
90806   void *pArg,                 /* First argument to xCallback() */
90807   char **pzErrMsg             /* Write error messages here */
90808 ){
90809   int rc = SQLITE_OK;         /* Return code */
90810   const char *zLeftover;      /* Tail of unprocessed SQL */
90811   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
90812   char **azCols = 0;          /* Names of result columns */
90813   int nRetry = 0;             /* Number of retry attempts */
90814   int callbackIsInit;         /* True if callback data is initialized */
90815
90816   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
90817   if( zSql==0 ) zSql = "";
90818
90819   sqlite3_mutex_enter(db->mutex);
90820   sqlite3Error(db, SQLITE_OK, 0);
90821   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
90822     int nCol;
90823     char **azVals = 0;
90824
90825     pStmt = 0;
90826     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
90827     assert( rc==SQLITE_OK || pStmt==0 );
90828     if( rc!=SQLITE_OK ){
90829       continue;
90830     }
90831     if( !pStmt ){
90832       /* this happens for a comment or white-space */
90833       zSql = zLeftover;
90834       continue;
90835     }
90836
90837     callbackIsInit = 0;
90838     nCol = sqlite3_column_count(pStmt);
90839
90840     while( 1 ){
90841       int i;
90842       rc = sqlite3_step(pStmt);
90843
90844       /* Invoke the callback function if required */
90845       if( xCallback && (SQLITE_ROW==rc || 
90846           (SQLITE_DONE==rc && !callbackIsInit
90847                            && db->flags&SQLITE_NullCallback)) ){
90848         if( !callbackIsInit ){
90849           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
90850           if( azCols==0 ){
90851             goto exec_out;
90852           }
90853           for(i=0; i<nCol; i++){
90854             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
90855             /* sqlite3VdbeSetColName() installs column names as UTF8
90856             ** strings so there is no way for sqlite3_column_name() to fail. */
90857             assert( azCols[i]!=0 );
90858           }
90859           callbackIsInit = 1;
90860         }
90861         if( rc==SQLITE_ROW ){
90862           azVals = &azCols[nCol];
90863           for(i=0; i<nCol; i++){
90864             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
90865             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
90866               db->mallocFailed = 1;
90867               goto exec_out;
90868             }
90869           }
90870         }
90871         if( xCallback(pArg, nCol, azVals, azCols) ){
90872           rc = SQLITE_ABORT;
90873           sqlite3VdbeFinalize((Vdbe *)pStmt);
90874           pStmt = 0;
90875           sqlite3Error(db, SQLITE_ABORT, 0);
90876           goto exec_out;
90877         }
90878       }
90879
90880       if( rc!=SQLITE_ROW ){
90881         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
90882         pStmt = 0;
90883         if( rc!=SQLITE_SCHEMA ){
90884           nRetry = 0;
90885           zSql = zLeftover;
90886           while( sqlite3Isspace(zSql[0]) ) zSql++;
90887         }
90888         break;
90889       }
90890     }
90891
90892     sqlite3DbFree(db, azCols);
90893     azCols = 0;
90894   }
90895
90896 exec_out:
90897   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
90898   sqlite3DbFree(db, azCols);
90899
90900   rc = sqlite3ApiExit(db, rc);
90901   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
90902     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
90903     *pzErrMsg = sqlite3Malloc(nErrMsg);
90904     if( *pzErrMsg ){
90905       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
90906     }else{
90907       rc = SQLITE_NOMEM;
90908       sqlite3Error(db, SQLITE_NOMEM, 0);
90909     }
90910   }else if( pzErrMsg ){
90911     *pzErrMsg = 0;
90912   }
90913
90914   assert( (rc&db->errMask)==rc );
90915   sqlite3_mutex_leave(db->mutex);
90916   return rc;
90917 }
90918
90919 /************** End of legacy.c **********************************************/
90920 /************** Begin file loadext.c *****************************************/
90921 /*
90922 ** 2006 June 7
90923 **
90924 ** The author disclaims copyright to this source code.  In place of
90925 ** a legal notice, here is a blessing:
90926 **
90927 **    May you do good and not evil.
90928 **    May you find forgiveness for yourself and forgive others.
90929 **    May you share freely, never taking more than you give.
90930 **
90931 *************************************************************************
90932 ** This file contains code used to dynamically load extensions into
90933 ** the SQLite library.
90934 */
90935
90936 #ifndef SQLITE_CORE
90937   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
90938 #endif
90939 /************** Include sqlite3ext.h in the middle of loadext.c **************/
90940 /************** Begin file sqlite3ext.h **************************************/
90941 /*
90942 ** 2006 June 7
90943 **
90944 ** The author disclaims copyright to this source code.  In place of
90945 ** a legal notice, here is a blessing:
90946 **
90947 **    May you do good and not evil.
90948 **    May you find forgiveness for yourself and forgive others.
90949 **    May you share freely, never taking more than you give.
90950 **
90951 *************************************************************************
90952 ** This header file defines the SQLite interface for use by
90953 ** shared libraries that want to be imported as extensions into
90954 ** an SQLite instance.  Shared libraries that intend to be loaded
90955 ** as extensions by SQLite should #include this file instead of 
90956 ** sqlite3.h.
90957 */
90958 #ifndef _SQLITE3EXT_H_
90959 #define _SQLITE3EXT_H_
90960
90961 typedef struct sqlite3_api_routines sqlite3_api_routines;
90962
90963 /*
90964 ** The following structure holds pointers to all of the SQLite API
90965 ** routines.
90966 **
90967 ** WARNING:  In order to maintain backwards compatibility, add new
90968 ** interfaces to the end of this structure only.  If you insert new
90969 ** interfaces in the middle of this structure, then older different
90970 ** versions of SQLite will not be able to load each others' shared
90971 ** libraries!
90972 */
90973 struct sqlite3_api_routines {
90974   void * (*aggregate_context)(sqlite3_context*,int nBytes);
90975   int  (*aggregate_count)(sqlite3_context*);
90976   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
90977   int  (*bind_double)(sqlite3_stmt*,int,double);
90978   int  (*bind_int)(sqlite3_stmt*,int,int);
90979   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
90980   int  (*bind_null)(sqlite3_stmt*,int);
90981   int  (*bind_parameter_count)(sqlite3_stmt*);
90982   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
90983   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
90984   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
90985   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
90986   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
90987   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
90988   int  (*busy_timeout)(sqlite3*,int ms);
90989   int  (*changes)(sqlite3*);
90990   int  (*close)(sqlite3*);
90991   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
90992                            int eTextRep,const char*));
90993   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
90994                              int eTextRep,const void*));
90995   const void * (*column_blob)(sqlite3_stmt*,int iCol);
90996   int  (*column_bytes)(sqlite3_stmt*,int iCol);
90997   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
90998   int  (*column_count)(sqlite3_stmt*pStmt);
90999   const char * (*column_database_name)(sqlite3_stmt*,int);
91000   const void * (*column_database_name16)(sqlite3_stmt*,int);
91001   const char * (*column_decltype)(sqlite3_stmt*,int i);
91002   const void * (*column_decltype16)(sqlite3_stmt*,int);
91003   double  (*column_double)(sqlite3_stmt*,int iCol);
91004   int  (*column_int)(sqlite3_stmt*,int iCol);
91005   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
91006   const char * (*column_name)(sqlite3_stmt*,int);
91007   const void * (*column_name16)(sqlite3_stmt*,int);
91008   const char * (*column_origin_name)(sqlite3_stmt*,int);
91009   const void * (*column_origin_name16)(sqlite3_stmt*,int);
91010   const char * (*column_table_name)(sqlite3_stmt*,int);
91011   const void * (*column_table_name16)(sqlite3_stmt*,int);
91012   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
91013   const void * (*column_text16)(sqlite3_stmt*,int iCol);
91014   int  (*column_type)(sqlite3_stmt*,int iCol);
91015   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
91016   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
91017   int  (*complete)(const char*sql);
91018   int  (*complete16)(const void*sql);
91019   int  (*create_collation)(sqlite3*,const char*,int,void*,
91020                            int(*)(void*,int,const void*,int,const void*));
91021   int  (*create_collation16)(sqlite3*,const void*,int,void*,
91022                              int(*)(void*,int,const void*,int,const void*));
91023   int  (*create_function)(sqlite3*,const char*,int,int,void*,
91024                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
91025                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
91026                           void (*xFinal)(sqlite3_context*));
91027   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
91028                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
91029                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
91030                             void (*xFinal)(sqlite3_context*));
91031   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
91032   int  (*data_count)(sqlite3_stmt*pStmt);
91033   sqlite3 * (*db_handle)(sqlite3_stmt*);
91034   int (*declare_vtab)(sqlite3*,const char*);
91035   int  (*enable_shared_cache)(int);
91036   int  (*errcode)(sqlite3*db);
91037   const char * (*errmsg)(sqlite3*);
91038   const void * (*errmsg16)(sqlite3*);
91039   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
91040   int  (*expired)(sqlite3_stmt*);
91041   int  (*finalize)(sqlite3_stmt*pStmt);
91042   void  (*free)(void*);
91043   void  (*free_table)(char**result);
91044   int  (*get_autocommit)(sqlite3*);
91045   void * (*get_auxdata)(sqlite3_context*,int);
91046   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
91047   int  (*global_recover)(void);
91048   void  (*interruptx)(sqlite3*);
91049   sqlite_int64  (*last_insert_rowid)(sqlite3*);
91050   const char * (*libversion)(void);
91051   int  (*libversion_number)(void);
91052   void *(*malloc)(int);
91053   char * (*mprintf)(const char*,...);
91054   int  (*open)(const char*,sqlite3**);
91055   int  (*open16)(const void*,sqlite3**);
91056   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
91057   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
91058   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
91059   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
91060   void *(*realloc)(void*,int);
91061   int  (*reset)(sqlite3_stmt*pStmt);
91062   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
91063   void  (*result_double)(sqlite3_context*,double);
91064   void  (*result_error)(sqlite3_context*,const char*,int);
91065   void  (*result_error16)(sqlite3_context*,const void*,int);
91066   void  (*result_int)(sqlite3_context*,int);
91067   void  (*result_int64)(sqlite3_context*,sqlite_int64);
91068   void  (*result_null)(sqlite3_context*);
91069   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
91070   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
91071   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
91072   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
91073   void  (*result_value)(sqlite3_context*,sqlite3_value*);
91074   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
91075   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
91076                          const char*,const char*),void*);
91077   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
91078   char * (*snprintf)(int,char*,const char*,...);
91079   int  (*step)(sqlite3_stmt*);
91080   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
91081                                 char const**,char const**,int*,int*,int*);
91082   void  (*thread_cleanup)(void);
91083   int  (*total_changes)(sqlite3*);
91084   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
91085   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
91086   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
91087                                          sqlite_int64),void*);
91088   void * (*user_data)(sqlite3_context*);
91089   const void * (*value_blob)(sqlite3_value*);
91090   int  (*value_bytes)(sqlite3_value*);
91091   int  (*value_bytes16)(sqlite3_value*);
91092   double  (*value_double)(sqlite3_value*);
91093   int  (*value_int)(sqlite3_value*);
91094   sqlite_int64  (*value_int64)(sqlite3_value*);
91095   int  (*value_numeric_type)(sqlite3_value*);
91096   const unsigned char * (*value_text)(sqlite3_value*);
91097   const void * (*value_text16)(sqlite3_value*);
91098   const void * (*value_text16be)(sqlite3_value*);
91099   const void * (*value_text16le)(sqlite3_value*);
91100   int  (*value_type)(sqlite3_value*);
91101   char *(*vmprintf)(const char*,va_list);
91102   /* Added ??? */
91103   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
91104   /* Added by 3.3.13 */
91105   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
91106   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
91107   int (*clear_bindings)(sqlite3_stmt*);
91108   /* Added by 3.4.1 */
91109   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
91110                           void (*xDestroy)(void *));
91111   /* Added by 3.5.0 */
91112   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
91113   int (*blob_bytes)(sqlite3_blob*);
91114   int (*blob_close)(sqlite3_blob*);
91115   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
91116                    int,sqlite3_blob**);
91117   int (*blob_read)(sqlite3_blob*,void*,int,int);
91118   int (*blob_write)(sqlite3_blob*,const void*,int,int);
91119   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
91120                              int(*)(void*,int,const void*,int,const void*),
91121                              void(*)(void*));
91122   int (*file_control)(sqlite3*,const char*,int,void*);
91123   sqlite3_int64 (*memory_highwater)(int);
91124   sqlite3_int64 (*memory_used)(void);
91125   sqlite3_mutex *(*mutex_alloc)(int);
91126   void (*mutex_enter)(sqlite3_mutex*);
91127   void (*mutex_free)(sqlite3_mutex*);
91128   void (*mutex_leave)(sqlite3_mutex*);
91129   int (*mutex_try)(sqlite3_mutex*);
91130   int (*open_v2)(const char*,sqlite3**,int,const char*);
91131   int (*release_memory)(int);
91132   void (*result_error_nomem)(sqlite3_context*);
91133   void (*result_error_toobig)(sqlite3_context*);
91134   int (*sleep)(int);
91135   void (*soft_heap_limit)(int);
91136   sqlite3_vfs *(*vfs_find)(const char*);
91137   int (*vfs_register)(sqlite3_vfs*,int);
91138   int (*vfs_unregister)(sqlite3_vfs*);
91139   int (*xthreadsafe)(void);
91140   void (*result_zeroblob)(sqlite3_context*,int);
91141   void (*result_error_code)(sqlite3_context*,int);
91142   int (*test_control)(int, ...);
91143   void (*randomness)(int,void*);
91144   sqlite3 *(*context_db_handle)(sqlite3_context*);
91145   int (*extended_result_codes)(sqlite3*,int);
91146   int (*limit)(sqlite3*,int,int);
91147   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
91148   const char *(*sql)(sqlite3_stmt*);
91149   int (*status)(int,int*,int*,int);
91150   int (*backup_finish)(sqlite3_backup*);
91151   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
91152   int (*backup_pagecount)(sqlite3_backup*);
91153   int (*backup_remaining)(sqlite3_backup*);
91154   int (*backup_step)(sqlite3_backup*,int);
91155   const char *(*compileoption_get)(int);
91156   int (*compileoption_used)(const char*);
91157   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
91158                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
91159                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
91160                             void (*xFinal)(sqlite3_context*),
91161                             void(*xDestroy)(void*));
91162   int (*db_config)(sqlite3*,int,...);
91163   sqlite3_mutex *(*db_mutex)(sqlite3*);
91164   int (*db_status)(sqlite3*,int,int*,int*,int);
91165   int (*extended_errcode)(sqlite3*);
91166   void (*log)(int,const char*,...);
91167   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
91168   const char *(*sourceid)(void);
91169   int (*stmt_status)(sqlite3_stmt*,int,int);
91170   int (*strnicmp)(const char*,const char*,int);
91171   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
91172   int (*wal_autocheckpoint)(sqlite3*,int);
91173   int (*wal_checkpoint)(sqlite3*,const char*);
91174   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
91175   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
91176   int (*vtab_config)(sqlite3*,int op,...);
91177   int (*vtab_on_conflict)(sqlite3*);
91178   /* Version 3.7.16 and later */
91179   int (*close_v2)(sqlite3*);
91180   const char *(*db_filename)(sqlite3*,const char*);
91181   int (*db_readonly)(sqlite3*,const char*);
91182   int (*db_release_memory)(sqlite3*);
91183   const char *(*errstr)(int);
91184   int (*stmt_busy)(sqlite3_stmt*);
91185   int (*stmt_readonly)(sqlite3_stmt*);
91186   int (*stricmp)(const char*,const char*);
91187   int (*uri_boolean)(const char*,const char*,int);
91188   sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
91189   const char *(*uri_parameter)(const char*,const char*);
91190   char *(*vsnprintf)(int,char*,const char*,va_list);
91191   int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
91192 };
91193
91194 /*
91195 ** The following macros redefine the API routines so that they are
91196 ** redirected throught the global sqlite3_api structure.
91197 **
91198 ** This header file is also used by the loadext.c source file
91199 ** (part of the main SQLite library - not an extension) so that
91200 ** it can get access to the sqlite3_api_routines structure
91201 ** definition.  But the main library does not want to redefine
91202 ** the API.  So the redefinition macros are only valid if the
91203 ** SQLITE_CORE macros is undefined.
91204 */
91205 #ifndef SQLITE_CORE
91206 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
91207 #ifndef SQLITE_OMIT_DEPRECATED
91208 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
91209 #endif
91210 #define sqlite3_bind_blob              sqlite3_api->bind_blob
91211 #define sqlite3_bind_double            sqlite3_api->bind_double
91212 #define sqlite3_bind_int               sqlite3_api->bind_int
91213 #define sqlite3_bind_int64             sqlite3_api->bind_int64
91214 #define sqlite3_bind_null              sqlite3_api->bind_null
91215 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
91216 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
91217 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
91218 #define sqlite3_bind_text              sqlite3_api->bind_text
91219 #define sqlite3_bind_text16            sqlite3_api->bind_text16
91220 #define sqlite3_bind_value             sqlite3_api->bind_value
91221 #define sqlite3_busy_handler           sqlite3_api->busy_handler
91222 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
91223 #define sqlite3_changes                sqlite3_api->changes
91224 #define sqlite3_close                  sqlite3_api->close
91225 #define sqlite3_collation_needed       sqlite3_api->collation_needed
91226 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
91227 #define sqlite3_column_blob            sqlite3_api->column_blob
91228 #define sqlite3_column_bytes           sqlite3_api->column_bytes
91229 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
91230 #define sqlite3_column_count           sqlite3_api->column_count
91231 #define sqlite3_column_database_name   sqlite3_api->column_database_name
91232 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
91233 #define sqlite3_column_decltype        sqlite3_api->column_decltype
91234 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
91235 #define sqlite3_column_double          sqlite3_api->column_double
91236 #define sqlite3_column_int             sqlite3_api->column_int
91237 #define sqlite3_column_int64           sqlite3_api->column_int64
91238 #define sqlite3_column_name            sqlite3_api->column_name
91239 #define sqlite3_column_name16          sqlite3_api->column_name16
91240 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
91241 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
91242 #define sqlite3_column_table_name      sqlite3_api->column_table_name
91243 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
91244 #define sqlite3_column_text            sqlite3_api->column_text
91245 #define sqlite3_column_text16          sqlite3_api->column_text16
91246 #define sqlite3_column_type            sqlite3_api->column_type
91247 #define sqlite3_column_value           sqlite3_api->column_value
91248 #define sqlite3_commit_hook            sqlite3_api->commit_hook
91249 #define sqlite3_complete               sqlite3_api->complete
91250 #define sqlite3_complete16             sqlite3_api->complete16
91251 #define sqlite3_create_collation       sqlite3_api->create_collation
91252 #define sqlite3_create_collation16     sqlite3_api->create_collation16
91253 #define sqlite3_create_function        sqlite3_api->create_function
91254 #define sqlite3_create_function16      sqlite3_api->create_function16
91255 #define sqlite3_create_module          sqlite3_api->create_module
91256 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
91257 #define sqlite3_data_count             sqlite3_api->data_count
91258 #define sqlite3_db_handle              sqlite3_api->db_handle
91259 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
91260 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
91261 #define sqlite3_errcode                sqlite3_api->errcode
91262 #define sqlite3_errmsg                 sqlite3_api->errmsg
91263 #define sqlite3_errmsg16               sqlite3_api->errmsg16
91264 #define sqlite3_exec                   sqlite3_api->exec
91265 #ifndef SQLITE_OMIT_DEPRECATED
91266 #define sqlite3_expired                sqlite3_api->expired
91267 #endif
91268 #define sqlite3_finalize               sqlite3_api->finalize
91269 #define sqlite3_free                   sqlite3_api->free
91270 #define sqlite3_free_table             sqlite3_api->free_table
91271 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
91272 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
91273 #define sqlite3_get_table              sqlite3_api->get_table
91274 #ifndef SQLITE_OMIT_DEPRECATED
91275 #define sqlite3_global_recover         sqlite3_api->global_recover
91276 #endif
91277 #define sqlite3_interrupt              sqlite3_api->interruptx
91278 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
91279 #define sqlite3_libversion             sqlite3_api->libversion
91280 #define sqlite3_libversion_number      sqlite3_api->libversion_number
91281 #define sqlite3_malloc                 sqlite3_api->malloc
91282 #define sqlite3_mprintf                sqlite3_api->mprintf
91283 #define sqlite3_open                   sqlite3_api->open
91284 #define sqlite3_open16                 sqlite3_api->open16
91285 #define sqlite3_prepare                sqlite3_api->prepare
91286 #define sqlite3_prepare16              sqlite3_api->prepare16
91287 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
91288 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
91289 #define sqlite3_profile                sqlite3_api->profile
91290 #define sqlite3_progress_handler       sqlite3_api->progress_handler
91291 #define sqlite3_realloc                sqlite3_api->realloc
91292 #define sqlite3_reset                  sqlite3_api->reset
91293 #define sqlite3_result_blob            sqlite3_api->result_blob
91294 #define sqlite3_result_double          sqlite3_api->result_double
91295 #define sqlite3_result_error           sqlite3_api->result_error
91296 #define sqlite3_result_error16         sqlite3_api->result_error16
91297 #define sqlite3_result_int             sqlite3_api->result_int
91298 #define sqlite3_result_int64           sqlite3_api->result_int64
91299 #define sqlite3_result_null            sqlite3_api->result_null
91300 #define sqlite3_result_text            sqlite3_api->result_text
91301 #define sqlite3_result_text16          sqlite3_api->result_text16
91302 #define sqlite3_result_text16be        sqlite3_api->result_text16be
91303 #define sqlite3_result_text16le        sqlite3_api->result_text16le
91304 #define sqlite3_result_value           sqlite3_api->result_value
91305 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
91306 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
91307 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
91308 #define sqlite3_snprintf               sqlite3_api->snprintf
91309 #define sqlite3_step                   sqlite3_api->step
91310 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
91311 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
91312 #define sqlite3_total_changes          sqlite3_api->total_changes
91313 #define sqlite3_trace                  sqlite3_api->trace
91314 #ifndef SQLITE_OMIT_DEPRECATED
91315 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
91316 #endif
91317 #define sqlite3_update_hook            sqlite3_api->update_hook
91318 #define sqlite3_user_data              sqlite3_api->user_data
91319 #define sqlite3_value_blob             sqlite3_api->value_blob
91320 #define sqlite3_value_bytes            sqlite3_api->value_bytes
91321 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
91322 #define sqlite3_value_double           sqlite3_api->value_double
91323 #define sqlite3_value_int              sqlite3_api->value_int
91324 #define sqlite3_value_int64            sqlite3_api->value_int64
91325 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
91326 #define sqlite3_value_text             sqlite3_api->value_text
91327 #define sqlite3_value_text16           sqlite3_api->value_text16
91328 #define sqlite3_value_text16be         sqlite3_api->value_text16be
91329 #define sqlite3_value_text16le         sqlite3_api->value_text16le
91330 #define sqlite3_value_type             sqlite3_api->value_type
91331 #define sqlite3_vmprintf               sqlite3_api->vmprintf
91332 #define sqlite3_overload_function      sqlite3_api->overload_function
91333 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
91334 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
91335 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
91336 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
91337 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
91338 #define sqlite3_blob_close             sqlite3_api->blob_close
91339 #define sqlite3_blob_open              sqlite3_api->blob_open
91340 #define sqlite3_blob_read              sqlite3_api->blob_read
91341 #define sqlite3_blob_write             sqlite3_api->blob_write
91342 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
91343 #define sqlite3_file_control           sqlite3_api->file_control
91344 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
91345 #define sqlite3_memory_used            sqlite3_api->memory_used
91346 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
91347 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
91348 #define sqlite3_mutex_free             sqlite3_api->mutex_free
91349 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
91350 #define sqlite3_mutex_try              sqlite3_api->mutex_try
91351 #define sqlite3_open_v2                sqlite3_api->open_v2
91352 #define sqlite3_release_memory         sqlite3_api->release_memory
91353 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
91354 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
91355 #define sqlite3_sleep                  sqlite3_api->sleep
91356 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
91357 #define sqlite3_vfs_find               sqlite3_api->vfs_find
91358 #define sqlite3_vfs_register           sqlite3_api->vfs_register
91359 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
91360 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
91361 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
91362 #define sqlite3_result_error_code      sqlite3_api->result_error_code
91363 #define sqlite3_test_control           sqlite3_api->test_control
91364 #define sqlite3_randomness             sqlite3_api->randomness
91365 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
91366 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
91367 #define sqlite3_limit                  sqlite3_api->limit
91368 #define sqlite3_next_stmt              sqlite3_api->next_stmt
91369 #define sqlite3_sql                    sqlite3_api->sql
91370 #define sqlite3_status                 sqlite3_api->status
91371 #define sqlite3_backup_finish          sqlite3_api->backup_finish
91372 #define sqlite3_backup_init            sqlite3_api->backup_init
91373 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
91374 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
91375 #define sqlite3_backup_step            sqlite3_api->backup_step
91376 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
91377 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
91378 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
91379 #define sqlite3_db_config              sqlite3_api->db_config
91380 #define sqlite3_db_mutex               sqlite3_api->db_mutex
91381 #define sqlite3_db_status              sqlite3_api->db_status
91382 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
91383 #define sqlite3_log                    sqlite3_api->log
91384 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
91385 #define sqlite3_sourceid               sqlite3_api->sourceid
91386 #define sqlite3_stmt_status            sqlite3_api->stmt_status
91387 #define sqlite3_strnicmp               sqlite3_api->strnicmp
91388 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
91389 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
91390 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
91391 #define sqlite3_wal_hook               sqlite3_api->wal_hook
91392 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
91393 #define sqlite3_vtab_config            sqlite3_api->vtab_config
91394 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
91395 /* Version 3.7.16 and later */
91396 #define sqlite3_close_v2               sqlite3_api->close_v2
91397 #define sqlite3_db_filename            sqlite3_api->db_filename
91398 #define sqlite3_db_readonly            sqlite3_api->db_readonly
91399 #define sqlite3_db_release_memory      sqlite3_api->db_release_memory
91400 #define sqlite3_errstr                 sqlite3_api->errstr
91401 #define sqlite3_stmt_busy              sqlite3_api->stmt_busy
91402 #define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
91403 #define sqlite3_stricmp                sqlite3_api->stricmp
91404 #define sqlite3_uri_boolean            sqlite3_api->uri_boolean
91405 #define sqlite3_uri_int64              sqlite3_api->uri_int64
91406 #define sqlite3_uri_parameter          sqlite3_api->uri_parameter
91407 #define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
91408 #define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
91409 #endif /* SQLITE_CORE */
91410
91411 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
91412 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
91413
91414 #endif /* _SQLITE3EXT_H_ */
91415
91416 /************** End of sqlite3ext.h ******************************************/
91417 /************** Continuing where we left off in loadext.c ********************/
91418 /* #include <string.h> */
91419
91420 #ifndef SQLITE_OMIT_LOAD_EXTENSION
91421
91422 /*
91423 ** Some API routines are omitted when various features are
91424 ** excluded from a build of SQLite.  Substitute a NULL pointer
91425 ** for any missing APIs.
91426 */
91427 #ifndef SQLITE_ENABLE_COLUMN_METADATA
91428 # define sqlite3_column_database_name   0
91429 # define sqlite3_column_database_name16 0
91430 # define sqlite3_column_table_name      0
91431 # define sqlite3_column_table_name16    0
91432 # define sqlite3_column_origin_name     0
91433 # define sqlite3_column_origin_name16   0
91434 # define sqlite3_table_column_metadata  0
91435 #endif
91436
91437 #ifdef SQLITE_OMIT_AUTHORIZATION
91438 # define sqlite3_set_authorizer         0
91439 #endif
91440
91441 #ifdef SQLITE_OMIT_UTF16
91442 # define sqlite3_bind_text16            0
91443 # define sqlite3_collation_needed16     0
91444 # define sqlite3_column_decltype16      0
91445 # define sqlite3_column_name16          0
91446 # define sqlite3_column_text16          0
91447 # define sqlite3_complete16             0
91448 # define sqlite3_create_collation16     0
91449 # define sqlite3_create_function16      0
91450 # define sqlite3_errmsg16               0
91451 # define sqlite3_open16                 0
91452 # define sqlite3_prepare16              0
91453 # define sqlite3_prepare16_v2           0
91454 # define sqlite3_result_error16         0
91455 # define sqlite3_result_text16          0
91456 # define sqlite3_result_text16be        0
91457 # define sqlite3_result_text16le        0
91458 # define sqlite3_value_text16           0
91459 # define sqlite3_value_text16be         0
91460 # define sqlite3_value_text16le         0
91461 # define sqlite3_column_database_name16 0
91462 # define sqlite3_column_table_name16    0
91463 # define sqlite3_column_origin_name16   0
91464 #endif
91465
91466 #ifdef SQLITE_OMIT_COMPLETE
91467 # define sqlite3_complete 0
91468 # define sqlite3_complete16 0
91469 #endif
91470
91471 #ifdef SQLITE_OMIT_DECLTYPE
91472 # define sqlite3_column_decltype16      0
91473 # define sqlite3_column_decltype        0
91474 #endif
91475
91476 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
91477 # define sqlite3_progress_handler 0
91478 #endif
91479
91480 #ifdef SQLITE_OMIT_VIRTUALTABLE
91481 # define sqlite3_create_module 0
91482 # define sqlite3_create_module_v2 0
91483 # define sqlite3_declare_vtab 0
91484 # define sqlite3_vtab_config 0
91485 # define sqlite3_vtab_on_conflict 0
91486 #endif
91487
91488 #ifdef SQLITE_OMIT_SHARED_CACHE
91489 # define sqlite3_enable_shared_cache 0
91490 #endif
91491
91492 #ifdef SQLITE_OMIT_TRACE
91493 # define sqlite3_profile       0
91494 # define sqlite3_trace         0
91495 #endif
91496
91497 #ifdef SQLITE_OMIT_GET_TABLE
91498 # define sqlite3_free_table    0
91499 # define sqlite3_get_table     0
91500 #endif
91501
91502 #ifdef SQLITE_OMIT_INCRBLOB
91503 #define sqlite3_bind_zeroblob  0
91504 #define sqlite3_blob_bytes     0
91505 #define sqlite3_blob_close     0
91506 #define sqlite3_blob_open      0
91507 #define sqlite3_blob_read      0
91508 #define sqlite3_blob_write     0
91509 #define sqlite3_blob_reopen    0
91510 #endif
91511
91512 /*
91513 ** The following structure contains pointers to all SQLite API routines.
91514 ** A pointer to this structure is passed into extensions when they are
91515 ** loaded so that the extension can make calls back into the SQLite
91516 ** library.
91517 **
91518 ** When adding new APIs, add them to the bottom of this structure
91519 ** in order to preserve backwards compatibility.
91520 **
91521 ** Extensions that use newer APIs should first call the
91522 ** sqlite3_libversion_number() to make sure that the API they
91523 ** intend to use is supported by the library.  Extensions should
91524 ** also check to make sure that the pointer to the function is
91525 ** not NULL before calling it.
91526 */
91527 static const sqlite3_api_routines sqlite3Apis = {
91528   sqlite3_aggregate_context,
91529 #ifndef SQLITE_OMIT_DEPRECATED
91530   sqlite3_aggregate_count,
91531 #else
91532   0,
91533 #endif
91534   sqlite3_bind_blob,
91535   sqlite3_bind_double,
91536   sqlite3_bind_int,
91537   sqlite3_bind_int64,
91538   sqlite3_bind_null,
91539   sqlite3_bind_parameter_count,
91540   sqlite3_bind_parameter_index,
91541   sqlite3_bind_parameter_name,
91542   sqlite3_bind_text,
91543   sqlite3_bind_text16,
91544   sqlite3_bind_value,
91545   sqlite3_busy_handler,
91546   sqlite3_busy_timeout,
91547   sqlite3_changes,
91548   sqlite3_close,
91549   sqlite3_collation_needed,
91550   sqlite3_collation_needed16,
91551   sqlite3_column_blob,
91552   sqlite3_column_bytes,
91553   sqlite3_column_bytes16,
91554   sqlite3_column_count,
91555   sqlite3_column_database_name,
91556   sqlite3_column_database_name16,
91557   sqlite3_column_decltype,
91558   sqlite3_column_decltype16,
91559   sqlite3_column_double,
91560   sqlite3_column_int,
91561   sqlite3_column_int64,
91562   sqlite3_column_name,
91563   sqlite3_column_name16,
91564   sqlite3_column_origin_name,
91565   sqlite3_column_origin_name16,
91566   sqlite3_column_table_name,
91567   sqlite3_column_table_name16,
91568   sqlite3_column_text,
91569   sqlite3_column_text16,
91570   sqlite3_column_type,
91571   sqlite3_column_value,
91572   sqlite3_commit_hook,
91573   sqlite3_complete,
91574   sqlite3_complete16,
91575   sqlite3_create_collation,
91576   sqlite3_create_collation16,
91577   sqlite3_create_function,
91578   sqlite3_create_function16,
91579   sqlite3_create_module,
91580   sqlite3_data_count,
91581   sqlite3_db_handle,
91582   sqlite3_declare_vtab,
91583   sqlite3_enable_shared_cache,
91584   sqlite3_errcode,
91585   sqlite3_errmsg,
91586   sqlite3_errmsg16,
91587   sqlite3_exec,
91588 #ifndef SQLITE_OMIT_DEPRECATED
91589   sqlite3_expired,
91590 #else
91591   0,
91592 #endif
91593   sqlite3_finalize,
91594   sqlite3_free,
91595   sqlite3_free_table,
91596   sqlite3_get_autocommit,
91597   sqlite3_get_auxdata,
91598   sqlite3_get_table,
91599   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
91600   sqlite3_interrupt,
91601   sqlite3_last_insert_rowid,
91602   sqlite3_libversion,
91603   sqlite3_libversion_number,
91604   sqlite3_malloc,
91605   sqlite3_mprintf,
91606   sqlite3_open,
91607   sqlite3_open16,
91608   sqlite3_prepare,
91609   sqlite3_prepare16,
91610   sqlite3_profile,
91611   sqlite3_progress_handler,
91612   sqlite3_realloc,
91613   sqlite3_reset,
91614   sqlite3_result_blob,
91615   sqlite3_result_double,
91616   sqlite3_result_error,
91617   sqlite3_result_error16,
91618   sqlite3_result_int,
91619   sqlite3_result_int64,
91620   sqlite3_result_null,
91621   sqlite3_result_text,
91622   sqlite3_result_text16,
91623   sqlite3_result_text16be,
91624   sqlite3_result_text16le,
91625   sqlite3_result_value,
91626   sqlite3_rollback_hook,
91627   sqlite3_set_authorizer,
91628   sqlite3_set_auxdata,
91629   sqlite3_snprintf,
91630   sqlite3_step,
91631   sqlite3_table_column_metadata,
91632 #ifndef SQLITE_OMIT_DEPRECATED
91633   sqlite3_thread_cleanup,
91634 #else
91635   0,
91636 #endif
91637   sqlite3_total_changes,
91638   sqlite3_trace,
91639 #ifndef SQLITE_OMIT_DEPRECATED
91640   sqlite3_transfer_bindings,
91641 #else
91642   0,
91643 #endif
91644   sqlite3_update_hook,
91645   sqlite3_user_data,
91646   sqlite3_value_blob,
91647   sqlite3_value_bytes,
91648   sqlite3_value_bytes16,
91649   sqlite3_value_double,
91650   sqlite3_value_int,
91651   sqlite3_value_int64,
91652   sqlite3_value_numeric_type,
91653   sqlite3_value_text,
91654   sqlite3_value_text16,
91655   sqlite3_value_text16be,
91656   sqlite3_value_text16le,
91657   sqlite3_value_type,
91658   sqlite3_vmprintf,
91659   /*
91660   ** The original API set ends here.  All extensions can call any
91661   ** of the APIs above provided that the pointer is not NULL.  But
91662   ** before calling APIs that follow, extension should check the
91663   ** sqlite3_libversion_number() to make sure they are dealing with
91664   ** a library that is new enough to support that API.
91665   *************************************************************************
91666   */
91667   sqlite3_overload_function,
91668
91669   /*
91670   ** Added after 3.3.13
91671   */
91672   sqlite3_prepare_v2,
91673   sqlite3_prepare16_v2,
91674   sqlite3_clear_bindings,
91675
91676   /*
91677   ** Added for 3.4.1
91678   */
91679   sqlite3_create_module_v2,
91680
91681   /*
91682   ** Added for 3.5.0
91683   */
91684   sqlite3_bind_zeroblob,
91685   sqlite3_blob_bytes,
91686   sqlite3_blob_close,
91687   sqlite3_blob_open,
91688   sqlite3_blob_read,
91689   sqlite3_blob_write,
91690   sqlite3_create_collation_v2,
91691   sqlite3_file_control,
91692   sqlite3_memory_highwater,
91693   sqlite3_memory_used,
91694 #ifdef SQLITE_MUTEX_OMIT
91695   0, 
91696   0, 
91697   0,
91698   0,
91699   0,
91700 #else
91701   sqlite3_mutex_alloc,
91702   sqlite3_mutex_enter,
91703   sqlite3_mutex_free,
91704   sqlite3_mutex_leave,
91705   sqlite3_mutex_try,
91706 #endif
91707   sqlite3_open_v2,
91708   sqlite3_release_memory,
91709   sqlite3_result_error_nomem,
91710   sqlite3_result_error_toobig,
91711   sqlite3_sleep,
91712   sqlite3_soft_heap_limit,
91713   sqlite3_vfs_find,
91714   sqlite3_vfs_register,
91715   sqlite3_vfs_unregister,
91716
91717   /*
91718   ** Added for 3.5.8
91719   */
91720   sqlite3_threadsafe,
91721   sqlite3_result_zeroblob,
91722   sqlite3_result_error_code,
91723   sqlite3_test_control,
91724   sqlite3_randomness,
91725   sqlite3_context_db_handle,
91726
91727   /*
91728   ** Added for 3.6.0
91729   */
91730   sqlite3_extended_result_codes,
91731   sqlite3_limit,
91732   sqlite3_next_stmt,
91733   sqlite3_sql,
91734   sqlite3_status,
91735
91736   /*
91737   ** Added for 3.7.4
91738   */
91739   sqlite3_backup_finish,
91740   sqlite3_backup_init,
91741   sqlite3_backup_pagecount,
91742   sqlite3_backup_remaining,
91743   sqlite3_backup_step,
91744 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
91745   sqlite3_compileoption_get,
91746   sqlite3_compileoption_used,
91747 #else
91748   0,
91749   0,
91750 #endif
91751   sqlite3_create_function_v2,
91752   sqlite3_db_config,
91753   sqlite3_db_mutex,
91754   sqlite3_db_status,
91755   sqlite3_extended_errcode,
91756   sqlite3_log,
91757   sqlite3_soft_heap_limit64,
91758   sqlite3_sourceid,
91759   sqlite3_stmt_status,
91760   sqlite3_strnicmp,
91761 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
91762   sqlite3_unlock_notify,
91763 #else
91764   0,
91765 #endif
91766 #ifndef SQLITE_OMIT_WAL
91767   sqlite3_wal_autocheckpoint,
91768   sqlite3_wal_checkpoint,
91769   sqlite3_wal_hook,
91770 #else
91771   0,
91772   0,
91773   0,
91774 #endif
91775   sqlite3_blob_reopen,
91776   sqlite3_vtab_config,
91777   sqlite3_vtab_on_conflict,
91778   sqlite3_close_v2,
91779   sqlite3_db_filename,
91780   sqlite3_db_readonly,
91781   sqlite3_db_release_memory,
91782   sqlite3_errstr,
91783   sqlite3_stmt_busy,
91784   sqlite3_stmt_readonly,
91785   sqlite3_stricmp,
91786   sqlite3_uri_boolean,
91787   sqlite3_uri_int64,
91788   sqlite3_uri_parameter,
91789   sqlite3_vsnprintf,
91790   sqlite3_wal_checkpoint_v2
91791 };
91792
91793 /*
91794 ** Attempt to load an SQLite extension library contained in the file
91795 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
91796 ** default entry point name (sqlite3_extension_init) is used.  Use
91797 ** of the default name is recommended.
91798 **
91799 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
91800 **
91801 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
91802 ** error message text.  The calling function should free this memory
91803 ** by calling sqlite3DbFree(db, ).
91804 */
91805 static int sqlite3LoadExtension(
91806   sqlite3 *db,          /* Load the extension into this database connection */
91807   const char *zFile,    /* Name of the shared library containing extension */
91808   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
91809   char **pzErrMsg       /* Put error message here if not 0 */
91810 ){
91811   sqlite3_vfs *pVfs = db->pVfs;
91812   void *handle;
91813   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
91814   char *zErrmsg = 0;
91815   void **aHandle;
91816   int nMsg = 300 + sqlite3Strlen30(zFile);
91817
91818   if( pzErrMsg ) *pzErrMsg = 0;
91819
91820   /* Ticket #1863.  To avoid a creating security problems for older
91821   ** applications that relink against newer versions of SQLite, the
91822   ** ability to run load_extension is turned off by default.  One
91823   ** must call sqlite3_enable_load_extension() to turn on extension
91824   ** loading.  Otherwise you get the following error.
91825   */
91826   if( (db->flags & SQLITE_LoadExtension)==0 ){
91827     if( pzErrMsg ){
91828       *pzErrMsg = sqlite3_mprintf("not authorized");
91829     }
91830     return SQLITE_ERROR;
91831   }
91832
91833   if( zProc==0 ){
91834     zProc = "sqlite3_extension_init";
91835   }
91836
91837   handle = sqlite3OsDlOpen(pVfs, zFile);
91838   if( handle==0 ){
91839     if( pzErrMsg ){
91840       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
91841       if( zErrmsg ){
91842         sqlite3_snprintf(nMsg, zErrmsg, 
91843             "unable to open shared library [%s]", zFile);
91844         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
91845       }
91846     }
91847     return SQLITE_ERROR;
91848   }
91849   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
91850                    sqlite3OsDlSym(pVfs, handle, zProc);
91851   if( xInit==0 ){
91852     if( pzErrMsg ){
91853       nMsg += sqlite3Strlen30(zProc);
91854       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
91855       if( zErrmsg ){
91856         sqlite3_snprintf(nMsg, zErrmsg,
91857             "no entry point [%s] in shared library [%s]", zProc,zFile);
91858         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
91859       }
91860       sqlite3OsDlClose(pVfs, handle);
91861     }
91862     return SQLITE_ERROR;
91863   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
91864     if( pzErrMsg ){
91865       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
91866     }
91867     sqlite3_free(zErrmsg);
91868     sqlite3OsDlClose(pVfs, handle);
91869     return SQLITE_ERROR;
91870   }
91871
91872   /* Append the new shared library handle to the db->aExtension array. */
91873   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
91874   if( aHandle==0 ){
91875     return SQLITE_NOMEM;
91876   }
91877   if( db->nExtension>0 ){
91878     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
91879   }
91880   sqlite3DbFree(db, db->aExtension);
91881   db->aExtension = aHandle;
91882
91883   db->aExtension[db->nExtension++] = handle;
91884   return SQLITE_OK;
91885 }
91886 SQLITE_API int sqlite3_load_extension(
91887   sqlite3 *db,          /* Load the extension into this database connection */
91888   const char *zFile,    /* Name of the shared library containing extension */
91889   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
91890   char **pzErrMsg       /* Put error message here if not 0 */
91891 ){
91892   int rc;
91893   sqlite3_mutex_enter(db->mutex);
91894   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
91895   rc = sqlite3ApiExit(db, rc);
91896   sqlite3_mutex_leave(db->mutex);
91897   return rc;
91898 }
91899
91900 /*
91901 ** Call this routine when the database connection is closing in order
91902 ** to clean up loaded extensions
91903 */
91904 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
91905   int i;
91906   assert( sqlite3_mutex_held(db->mutex) );
91907   for(i=0; i<db->nExtension; i++){
91908     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
91909   }
91910   sqlite3DbFree(db, db->aExtension);
91911 }
91912
91913 /*
91914 ** Enable or disable extension loading.  Extension loading is disabled by
91915 ** default so as not to open security holes in older applications.
91916 */
91917 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
91918   sqlite3_mutex_enter(db->mutex);
91919   if( onoff ){
91920     db->flags |= SQLITE_LoadExtension;
91921   }else{
91922     db->flags &= ~SQLITE_LoadExtension;
91923   }
91924   sqlite3_mutex_leave(db->mutex);
91925   return SQLITE_OK;
91926 }
91927
91928 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
91929
91930 /*
91931 ** The auto-extension code added regardless of whether or not extension
91932 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
91933 ** code if regular extension loading is not available.  This is that
91934 ** dummy pointer.
91935 */
91936 #ifdef SQLITE_OMIT_LOAD_EXTENSION
91937 static const sqlite3_api_routines sqlite3Apis = { 0 };
91938 #endif
91939
91940
91941 /*
91942 ** The following object holds the list of automatically loaded
91943 ** extensions.
91944 **
91945 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
91946 ** mutex must be held while accessing this list.
91947 */
91948 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
91949 static SQLITE_WSD struct sqlite3AutoExtList {
91950   int nExt;              /* Number of entries in aExt[] */          
91951   void (**aExt)(void);   /* Pointers to the extension init functions */
91952 } sqlite3Autoext = { 0, 0 };
91953
91954 /* The "wsdAutoext" macro will resolve to the autoextension
91955 ** state vector.  If writable static data is unsupported on the target,
91956 ** we have to locate the state vector at run-time.  In the more common
91957 ** case where writable static data is supported, wsdStat can refer directly
91958 ** to the "sqlite3Autoext" state vector declared above.
91959 */
91960 #ifdef SQLITE_OMIT_WSD
91961 # define wsdAutoextInit \
91962   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
91963 # define wsdAutoext x[0]
91964 #else
91965 # define wsdAutoextInit
91966 # define wsdAutoext sqlite3Autoext
91967 #endif
91968
91969
91970 /*
91971 ** Register a statically linked extension that is automatically
91972 ** loaded by every new database connection.
91973 */
91974 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
91975   int rc = SQLITE_OK;
91976 #ifndef SQLITE_OMIT_AUTOINIT
91977   rc = sqlite3_initialize();
91978   if( rc ){
91979     return rc;
91980   }else
91981 #endif
91982   {
91983     int i;
91984 #if SQLITE_THREADSAFE
91985     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
91986 #endif
91987     wsdAutoextInit;
91988     sqlite3_mutex_enter(mutex);
91989     for(i=0; i<wsdAutoext.nExt; i++){
91990       if( wsdAutoext.aExt[i]==xInit ) break;
91991     }
91992     if( i==wsdAutoext.nExt ){
91993       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
91994       void (**aNew)(void);
91995       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
91996       if( aNew==0 ){
91997         rc = SQLITE_NOMEM;
91998       }else{
91999         wsdAutoext.aExt = aNew;
92000         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
92001         wsdAutoext.nExt++;
92002       }
92003     }
92004     sqlite3_mutex_leave(mutex);
92005     assert( (rc&0xff)==rc );
92006     return rc;
92007   }
92008 }
92009
92010 /*
92011 ** Reset the automatic extension loading mechanism.
92012 */
92013 SQLITE_API void sqlite3_reset_auto_extension(void){
92014 #ifndef SQLITE_OMIT_AUTOINIT
92015   if( sqlite3_initialize()==SQLITE_OK )
92016 #endif
92017   {
92018 #if SQLITE_THREADSAFE
92019     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
92020 #endif
92021     wsdAutoextInit;
92022     sqlite3_mutex_enter(mutex);
92023     sqlite3_free(wsdAutoext.aExt);
92024     wsdAutoext.aExt = 0;
92025     wsdAutoext.nExt = 0;
92026     sqlite3_mutex_leave(mutex);
92027   }
92028 }
92029
92030 /*
92031 ** Load all automatic extensions.
92032 **
92033 ** If anything goes wrong, set an error in the database connection.
92034 */
92035 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
92036   int i;
92037   int go = 1;
92038   int rc;
92039   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
92040
92041   wsdAutoextInit;
92042   if( wsdAutoext.nExt==0 ){
92043     /* Common case: early out without every having to acquire a mutex */
92044     return;
92045   }
92046   for(i=0; go; i++){
92047     char *zErrmsg;
92048 #if SQLITE_THREADSAFE
92049     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
92050 #endif
92051     sqlite3_mutex_enter(mutex);
92052     if( i>=wsdAutoext.nExt ){
92053       xInit = 0;
92054       go = 0;
92055     }else{
92056       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
92057               wsdAutoext.aExt[i];
92058     }
92059     sqlite3_mutex_leave(mutex);
92060     zErrmsg = 0;
92061     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
92062       sqlite3Error(db, rc,
92063             "automatic extension loading failed: %s", zErrmsg);
92064       go = 0;
92065     }
92066     sqlite3_free(zErrmsg);
92067   }
92068 }
92069
92070 /************** End of loadext.c *********************************************/
92071 /************** Begin file pragma.c ******************************************/
92072 /*
92073 ** 2003 April 6
92074 **
92075 ** The author disclaims copyright to this source code.  In place of
92076 ** a legal notice, here is a blessing:
92077 **
92078 **    May you do good and not evil.
92079 **    May you find forgiveness for yourself and forgive others.
92080 **    May you share freely, never taking more than you give.
92081 **
92082 *************************************************************************
92083 ** This file contains code used to implement the PRAGMA command.
92084 */
92085
92086 /*
92087 ** Interpret the given string as a safety level.  Return 0 for OFF,
92088 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
92089 ** unrecognized string argument.  The FULL option is disallowed
92090 ** if the omitFull parameter it 1.
92091 **
92092 ** Note that the values returned are one less that the values that
92093 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
92094 ** to support legacy SQL code.  The safety level used to be boolean
92095 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
92096 */
92097 static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
92098                              /* 123456789 123456789 */
92099   static const char zText[] = "onoffalseyestruefull";
92100   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
92101   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
92102   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
92103   int i, n;
92104   if( sqlite3Isdigit(*z) ){
92105     return (u8)sqlite3Atoi(z);
92106   }
92107   n = sqlite3Strlen30(z);
92108   for(i=0; i<ArraySize(iLength)-omitFull; i++){
92109     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
92110       return iValue[i];
92111     }
92112   }
92113   return dflt;
92114 }
92115
92116 /*
92117 ** Interpret the given string as a boolean value.
92118 */
92119 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
92120   return getSafetyLevel(z,1,dflt)!=0;
92121 }
92122
92123 /* The sqlite3GetBoolean() function is used by other modules but the
92124 ** remainder of this file is specific to PRAGMA processing.  So omit
92125 ** the rest of the file if PRAGMAs are omitted from the build.
92126 */
92127 #if !defined(SQLITE_OMIT_PRAGMA)
92128
92129 /*
92130 ** Interpret the given string as a locking mode value.
92131 */
92132 static int getLockingMode(const char *z){
92133   if( z ){
92134     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
92135     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
92136   }
92137   return PAGER_LOCKINGMODE_QUERY;
92138 }
92139
92140 #ifndef SQLITE_OMIT_AUTOVACUUM
92141 /*
92142 ** Interpret the given string as an auto-vacuum mode value.
92143 **
92144 ** The following strings, "none", "full" and "incremental" are 
92145 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
92146 */
92147 static int getAutoVacuum(const char *z){
92148   int i;
92149   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
92150   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
92151   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
92152   i = sqlite3Atoi(z);
92153   return (u8)((i>=0&&i<=2)?i:0);
92154 }
92155 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
92156
92157 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
92158 /*
92159 ** Interpret the given string as a temp db location. Return 1 for file
92160 ** backed temporary databases, 2 for the Red-Black tree in memory database
92161 ** and 0 to use the compile-time default.
92162 */
92163 static int getTempStore(const char *z){
92164   if( z[0]>='0' && z[0]<='2' ){
92165     return z[0] - '0';
92166   }else if( sqlite3StrICmp(z, "file")==0 ){
92167     return 1;
92168   }else if( sqlite3StrICmp(z, "memory")==0 ){
92169     return 2;
92170   }else{
92171     return 0;
92172   }
92173 }
92174 #endif /* SQLITE_PAGER_PRAGMAS */
92175
92176 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
92177 /*
92178 ** Invalidate temp storage, either when the temp storage is changed
92179 ** from default, or when 'file' and the temp_store_directory has changed
92180 */
92181 static int invalidateTempStorage(Parse *pParse){
92182   sqlite3 *db = pParse->db;
92183   if( db->aDb[1].pBt!=0 ){
92184     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
92185       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
92186         "from within a transaction");
92187       return SQLITE_ERROR;
92188     }
92189     sqlite3BtreeClose(db->aDb[1].pBt);
92190     db->aDb[1].pBt = 0;
92191     sqlite3ResetAllSchemasOfConnection(db);
92192   }
92193   return SQLITE_OK;
92194 }
92195 #endif /* SQLITE_PAGER_PRAGMAS */
92196
92197 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
92198 /*
92199 ** If the TEMP database is open, close it and mark the database schema
92200 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
92201 ** or DEFAULT_TEMP_STORE pragmas.
92202 */
92203 static int changeTempStorage(Parse *pParse, const char *zStorageType){
92204   int ts = getTempStore(zStorageType);
92205   sqlite3 *db = pParse->db;
92206   if( db->temp_store==ts ) return SQLITE_OK;
92207   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
92208     return SQLITE_ERROR;
92209   }
92210   db->temp_store = (u8)ts;
92211   return SQLITE_OK;
92212 }
92213 #endif /* SQLITE_PAGER_PRAGMAS */
92214
92215 /*
92216 ** Generate code to return a single integer value.
92217 */
92218 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
92219   Vdbe *v = sqlite3GetVdbe(pParse);
92220   int mem = ++pParse->nMem;
92221   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
92222   if( pI64 ){
92223     memcpy(pI64, &value, sizeof(value));
92224   }
92225   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
92226   sqlite3VdbeSetNumCols(v, 1);
92227   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
92228   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
92229 }
92230
92231 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
92232 /*
92233 ** Check to see if zRight and zLeft refer to a pragma that queries
92234 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
92235 ** Also, implement the pragma.
92236 */
92237 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
92238   static const struct sPragmaType {
92239     const char *zName;  /* Name of the pragma */
92240     int mask;           /* Mask for the db->flags value */
92241   } aPragma[] = {
92242     { "full_column_names",        SQLITE_FullColNames  },
92243     { "short_column_names",       SQLITE_ShortColNames },
92244     { "count_changes",            SQLITE_CountRows     },
92245     { "empty_result_callbacks",   SQLITE_NullCallback  },
92246     { "legacy_file_format",       SQLITE_LegacyFileFmt },
92247     { "fullfsync",                SQLITE_FullFSync     },
92248     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
92249     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
92250 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
92251     { "automatic_index",          SQLITE_AutoIndex     },
92252 #endif
92253 #ifdef SQLITE_DEBUG
92254     { "sql_trace",                SQLITE_SqlTrace      },
92255     { "vdbe_listing",             SQLITE_VdbeListing   },
92256     { "vdbe_trace",               SQLITE_VdbeTrace     },
92257     { "vdbe_addoptrace",          SQLITE_VdbeAddopTrace},
92258     { "vdbe_debug",    SQLITE_SqlTrace | SQLITE_VdbeListing
92259                                | SQLITE_VdbeTrace      },
92260 #endif
92261 #ifndef SQLITE_OMIT_CHECK
92262     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
92263 #endif
92264     /* The following is VERY experimental */
92265     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
92266
92267     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
92268     ** flag if there are any active statements. */
92269     { "read_uncommitted",         SQLITE_ReadUncommitted },
92270     { "recursive_triggers",       SQLITE_RecTriggers },
92271
92272     /* This flag may only be set if both foreign-key and trigger support
92273     ** are present in the build.  */
92274 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
92275     { "foreign_keys",             SQLITE_ForeignKeys },
92276 #endif
92277   };
92278   int i;
92279   const struct sPragmaType *p;
92280   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
92281     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
92282       sqlite3 *db = pParse->db;
92283       Vdbe *v;
92284       v = sqlite3GetVdbe(pParse);
92285       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
92286       if( ALWAYS(v) ){
92287         if( zRight==0 ){
92288           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
92289         }else{
92290           int mask = p->mask;          /* Mask of bits to set or clear. */
92291           if( db->autoCommit==0 ){
92292             /* Foreign key support may not be enabled or disabled while not
92293             ** in auto-commit mode.  */
92294             mask &= ~(SQLITE_ForeignKeys);
92295           }
92296
92297           if( sqlite3GetBoolean(zRight, 0) ){
92298             db->flags |= mask;
92299           }else{
92300             db->flags &= ~mask;
92301           }
92302
92303           /* Many of the flag-pragmas modify the code generated by the SQL 
92304           ** compiler (eg. count_changes). So add an opcode to expire all
92305           ** compiled SQL statements after modifying a pragma value.
92306           */
92307           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
92308         }
92309       }
92310
92311       return 1;
92312     }
92313   }
92314   return 0;
92315 }
92316 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
92317
92318 /*
92319 ** Return a human-readable name for a constraint resolution action.
92320 */
92321 #ifndef SQLITE_OMIT_FOREIGN_KEY
92322 static const char *actionName(u8 action){
92323   const char *zName;
92324   switch( action ){
92325     case OE_SetNull:  zName = "SET NULL";        break;
92326     case OE_SetDflt:  zName = "SET DEFAULT";     break;
92327     case OE_Cascade:  zName = "CASCADE";         break;
92328     case OE_Restrict: zName = "RESTRICT";        break;
92329     default:          zName = "NO ACTION";  
92330                       assert( action==OE_None ); break;
92331   }
92332   return zName;
92333 }
92334 #endif
92335
92336
92337 /*
92338 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
92339 ** defined in pager.h. This function returns the associated lowercase
92340 ** journal-mode name.
92341 */
92342 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
92343   static char * const azModeName[] = {
92344     "delete", "persist", "off", "truncate", "memory"
92345 #ifndef SQLITE_OMIT_WAL
92346      , "wal"
92347 #endif
92348   };
92349   assert( PAGER_JOURNALMODE_DELETE==0 );
92350   assert( PAGER_JOURNALMODE_PERSIST==1 );
92351   assert( PAGER_JOURNALMODE_OFF==2 );
92352   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
92353   assert( PAGER_JOURNALMODE_MEMORY==4 );
92354   assert( PAGER_JOURNALMODE_WAL==5 );
92355   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
92356
92357   if( eMode==ArraySize(azModeName) ) return 0;
92358   return azModeName[eMode];
92359 }
92360
92361 /*
92362 ** Process a pragma statement.  
92363 **
92364 ** Pragmas are of this form:
92365 **
92366 **      PRAGMA [database.]id [= value]
92367 **
92368 ** The identifier might also be a string.  The value is a string, and
92369 ** identifier, or a number.  If minusFlag is true, then the value is
92370 ** a number that was preceded by a minus sign.
92371 **
92372 ** If the left side is "database.id" then pId1 is the database name
92373 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
92374 ** id and pId2 is any empty string.
92375 */
92376 SQLITE_PRIVATE void sqlite3Pragma(
92377   Parse *pParse, 
92378   Token *pId1,        /* First part of [database.]id field */
92379   Token *pId2,        /* Second part of [database.]id field, or NULL */
92380   Token *pValue,      /* Token for <value>, or NULL */
92381   int minusFlag       /* True if a '-' sign preceded <value> */
92382 ){
92383   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
92384   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
92385   const char *zDb = 0;   /* The database name */
92386   Token *pId;            /* Pointer to <id> token */
92387   int iDb;               /* Database index for <database> */
92388   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
92389   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
92390   sqlite3 *db = pParse->db;    /* The database connection */
92391   Db *pDb;                     /* The specific database being pragmaed */
92392   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);  /* Prepared statement */
92393
92394   if( v==0 ) return;
92395   sqlite3VdbeRunOnlyOnce(v);
92396   pParse->nMem = 2;
92397
92398   /* Interpret the [database.] part of the pragma statement. iDb is the
92399   ** index of the database this pragma is being applied to in db.aDb[]. */
92400   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
92401   if( iDb<0 ) return;
92402   pDb = &db->aDb[iDb];
92403
92404   /* If the temp database has been explicitly named as part of the 
92405   ** pragma, make sure it is open. 
92406   */
92407   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
92408     return;
92409   }
92410
92411   zLeft = sqlite3NameFromToken(db, pId);
92412   if( !zLeft ) return;
92413   if( minusFlag ){
92414     zRight = sqlite3MPrintf(db, "-%T", pValue);
92415   }else{
92416     zRight = sqlite3NameFromToken(db, pValue);
92417   }
92418
92419   assert( pId2 );
92420   zDb = pId2->n>0 ? pDb->zName : 0;
92421   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
92422     goto pragma_out;
92423   }
92424
92425   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
92426   ** connection.  If it returns SQLITE_OK, then assume that the VFS
92427   ** handled the pragma and generate a no-op prepared statement.
92428   */
92429   aFcntl[0] = 0;
92430   aFcntl[1] = zLeft;
92431   aFcntl[2] = zRight;
92432   aFcntl[3] = 0;
92433   db->busyHandler.nBusy = 0;
92434   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
92435   if( rc==SQLITE_OK ){
92436     if( aFcntl[0] ){
92437       int mem = ++pParse->nMem;
92438       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
92439       sqlite3VdbeSetNumCols(v, 1);
92440       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
92441       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
92442       sqlite3_free(aFcntl[0]);
92443     }
92444   }else if( rc!=SQLITE_NOTFOUND ){
92445     if( aFcntl[0] ){
92446       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
92447       sqlite3_free(aFcntl[0]);
92448     }
92449     pParse->nErr++;
92450     pParse->rc = rc;
92451   }else
92452                             
92453  
92454 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
92455   /*
92456   **  PRAGMA [database.]default_cache_size
92457   **  PRAGMA [database.]default_cache_size=N
92458   **
92459   ** The first form reports the current persistent setting for the
92460   ** page cache size.  The value returned is the maximum number of
92461   ** pages in the page cache.  The second form sets both the current
92462   ** page cache size value and the persistent page cache size value
92463   ** stored in the database file.
92464   **
92465   ** Older versions of SQLite would set the default cache size to a
92466   ** negative number to indicate synchronous=OFF.  These days, synchronous
92467   ** is always on by default regardless of the sign of the default cache
92468   ** size.  But continue to take the absolute value of the default cache
92469   ** size of historical compatibility.
92470   */
92471   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
92472     static const VdbeOpList getCacheSize[] = {
92473       { OP_Transaction, 0, 0,        0},                         /* 0 */
92474       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
92475       { OP_IfPos,       1, 7,        0},
92476       { OP_Integer,     0, 2,        0},
92477       { OP_Subtract,    1, 2,        1},
92478       { OP_IfPos,       1, 7,        0},
92479       { OP_Integer,     0, 1,        0},                         /* 6 */
92480       { OP_ResultRow,   1, 1,        0},
92481     };
92482     int addr;
92483     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92484     sqlite3VdbeUsesBtree(v, iDb);
92485     if( !zRight ){
92486       sqlite3VdbeSetNumCols(v, 1);
92487       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
92488       pParse->nMem += 2;
92489       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
92490       sqlite3VdbeChangeP1(v, addr, iDb);
92491       sqlite3VdbeChangeP1(v, addr+1, iDb);
92492       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
92493     }else{
92494       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
92495       sqlite3BeginWriteOperation(pParse, 0, iDb);
92496       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
92497       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
92498       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92499       pDb->pSchema->cache_size = size;
92500       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92501     }
92502   }else
92503 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
92504
92505 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
92506   /*
92507   **  PRAGMA [database.]page_size
92508   **  PRAGMA [database.]page_size=N
92509   **
92510   ** The first form reports the current setting for the
92511   ** database page size in bytes.  The second form sets the
92512   ** database page size value.  The value can only be set if
92513   ** the database has not yet been created.
92514   */
92515   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
92516     Btree *pBt = pDb->pBt;
92517     assert( pBt!=0 );
92518     if( !zRight ){
92519       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
92520       returnSingleInt(pParse, "page_size", size);
92521     }else{
92522       /* Malloc may fail when setting the page-size, as there is an internal
92523       ** buffer that the pager module resizes using sqlite3_realloc().
92524       */
92525       db->nextPagesize = sqlite3Atoi(zRight);
92526       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
92527         db->mallocFailed = 1;
92528       }
92529     }
92530   }else
92531
92532   /*
92533   **  PRAGMA [database.]secure_delete
92534   **  PRAGMA [database.]secure_delete=ON/OFF
92535   **
92536   ** The first form reports the current setting for the
92537   ** secure_delete flag.  The second form changes the secure_delete
92538   ** flag setting and reports thenew value.
92539   */
92540   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
92541     Btree *pBt = pDb->pBt;
92542     int b = -1;
92543     assert( pBt!=0 );
92544     if( zRight ){
92545       b = sqlite3GetBoolean(zRight, 0);
92546     }
92547     if( pId2->n==0 && b>=0 ){
92548       int ii;
92549       for(ii=0; ii<db->nDb; ii++){
92550         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
92551       }
92552     }
92553     b = sqlite3BtreeSecureDelete(pBt, b);
92554     returnSingleInt(pParse, "secure_delete", b);
92555   }else
92556
92557   /*
92558   **  PRAGMA [database.]max_page_count
92559   **  PRAGMA [database.]max_page_count=N
92560   **
92561   ** The first form reports the current setting for the
92562   ** maximum number of pages in the database file.  The 
92563   ** second form attempts to change this setting.  Both
92564   ** forms return the current setting.
92565   **
92566   ** The absolute value of N is used.  This is undocumented and might
92567   ** change.  The only purpose is to provide an easy way to test
92568   ** the sqlite3AbsInt32() function.
92569   **
92570   **  PRAGMA [database.]page_count
92571   **
92572   ** Return the number of pages in the specified database.
92573   */
92574   if( sqlite3StrICmp(zLeft,"page_count")==0
92575    || sqlite3StrICmp(zLeft,"max_page_count")==0
92576   ){
92577     int iReg;
92578     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92579     sqlite3CodeVerifySchema(pParse, iDb);
92580     iReg = ++pParse->nMem;
92581     if( sqlite3Tolower(zLeft[0])=='p' ){
92582       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
92583     }else{
92584       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
92585                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
92586     }
92587     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
92588     sqlite3VdbeSetNumCols(v, 1);
92589     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
92590   }else
92591
92592   /*
92593   **  PRAGMA [database.]locking_mode
92594   **  PRAGMA [database.]locking_mode = (normal|exclusive)
92595   */
92596   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
92597     const char *zRet = "normal";
92598     int eMode = getLockingMode(zRight);
92599
92600     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
92601       /* Simple "PRAGMA locking_mode;" statement. This is a query for
92602       ** the current default locking mode (which may be different to
92603       ** the locking-mode of the main database).
92604       */
92605       eMode = db->dfltLockMode;
92606     }else{
92607       Pager *pPager;
92608       if( pId2->n==0 ){
92609         /* This indicates that no database name was specified as part
92610         ** of the PRAGMA command. In this case the locking-mode must be
92611         ** set on all attached databases, as well as the main db file.
92612         **
92613         ** Also, the sqlite3.dfltLockMode variable is set so that
92614         ** any subsequently attached databases also use the specified
92615         ** locking mode.
92616         */
92617         int ii;
92618         assert(pDb==&db->aDb[0]);
92619         for(ii=2; ii<db->nDb; ii++){
92620           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
92621           sqlite3PagerLockingMode(pPager, eMode);
92622         }
92623         db->dfltLockMode = (u8)eMode;
92624       }
92625       pPager = sqlite3BtreePager(pDb->pBt);
92626       eMode = sqlite3PagerLockingMode(pPager, eMode);
92627     }
92628
92629     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
92630     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
92631       zRet = "exclusive";
92632     }
92633     sqlite3VdbeSetNumCols(v, 1);
92634     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
92635     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
92636     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92637   }else
92638
92639   /*
92640   **  PRAGMA [database.]journal_mode
92641   **  PRAGMA [database.]journal_mode =
92642   **                      (delete|persist|off|truncate|memory|wal|off)
92643   */
92644   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
92645     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
92646     int ii;           /* Loop counter */
92647
92648     /* Force the schema to be loaded on all databases.  This causes all
92649     ** database files to be opened and the journal_modes set.  This is
92650     ** necessary because subsequent processing must know if the databases
92651     ** are in WAL mode. */
92652     if( sqlite3ReadSchema(pParse) ){
92653       goto pragma_out;
92654     }
92655
92656     sqlite3VdbeSetNumCols(v, 1);
92657     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
92658
92659     if( zRight==0 ){
92660       /* If there is no "=MODE" part of the pragma, do a query for the
92661       ** current mode */
92662       eMode = PAGER_JOURNALMODE_QUERY;
92663     }else{
92664       const char *zMode;
92665       int n = sqlite3Strlen30(zRight);
92666       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
92667         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
92668       }
92669       if( !zMode ){
92670         /* If the "=MODE" part does not match any known journal mode,
92671         ** then do a query */
92672         eMode = PAGER_JOURNALMODE_QUERY;
92673       }
92674     }
92675     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
92676       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
92677       iDb = 0;
92678       pId2->n = 1;
92679     }
92680     for(ii=db->nDb-1; ii>=0; ii--){
92681       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
92682         sqlite3VdbeUsesBtree(v, ii);
92683         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
92684       }
92685     }
92686     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92687   }else
92688
92689   /*
92690   **  PRAGMA [database.]journal_size_limit
92691   **  PRAGMA [database.]journal_size_limit=N
92692   **
92693   ** Get or set the size limit on rollback journal files.
92694   */
92695   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
92696     Pager *pPager = sqlite3BtreePager(pDb->pBt);
92697     i64 iLimit = -2;
92698     if( zRight ){
92699       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
92700       if( iLimit<-1 ) iLimit = -1;
92701     }
92702     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
92703     returnSingleInt(pParse, "journal_size_limit", iLimit);
92704   }else
92705
92706 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
92707
92708   /*
92709   **  PRAGMA [database.]auto_vacuum
92710   **  PRAGMA [database.]auto_vacuum=N
92711   **
92712   ** Get or set the value of the database 'auto-vacuum' parameter.
92713   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
92714   */
92715 #ifndef SQLITE_OMIT_AUTOVACUUM
92716   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
92717     Btree *pBt = pDb->pBt;
92718     assert( pBt!=0 );
92719     if( sqlite3ReadSchema(pParse) ){
92720       goto pragma_out;
92721     }
92722     if( !zRight ){
92723       int auto_vacuum;
92724       if( ALWAYS(pBt) ){
92725          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
92726       }else{
92727          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
92728       }
92729       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
92730     }else{
92731       int eAuto = getAutoVacuum(zRight);
92732       assert( eAuto>=0 && eAuto<=2 );
92733       db->nextAutovac = (u8)eAuto;
92734       if( ALWAYS(eAuto>=0) ){
92735         /* Call SetAutoVacuum() to set initialize the internal auto and
92736         ** incr-vacuum flags. This is required in case this connection
92737         ** creates the database file. It is important that it is created
92738         ** as an auto-vacuum capable db.
92739         */
92740         rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
92741         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
92742           /* When setting the auto_vacuum mode to either "full" or 
92743           ** "incremental", write the value of meta[6] in the database
92744           ** file. Before writing to meta[6], check that meta[3] indicates
92745           ** that this really is an auto-vacuum capable database.
92746           */
92747           static const VdbeOpList setMeta6[] = {
92748             { OP_Transaction,    0,         1,                 0},    /* 0 */
92749             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
92750             { OP_If,             1,         0,                 0},    /* 2 */
92751             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
92752             { OP_Integer,        0,         1,                 0},    /* 4 */
92753             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
92754           };
92755           int iAddr;
92756           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
92757           sqlite3VdbeChangeP1(v, iAddr, iDb);
92758           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
92759           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
92760           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
92761           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
92762           sqlite3VdbeUsesBtree(v, iDb);
92763         }
92764       }
92765     }
92766   }else
92767 #endif
92768
92769   /*
92770   **  PRAGMA [database.]incremental_vacuum(N)
92771   **
92772   ** Do N steps of incremental vacuuming on a database.
92773   */
92774 #ifndef SQLITE_OMIT_AUTOVACUUM
92775   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
92776     int iLimit, addr;
92777     if( sqlite3ReadSchema(pParse) ){
92778       goto pragma_out;
92779     }
92780     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
92781       iLimit = 0x7fffffff;
92782     }
92783     sqlite3BeginWriteOperation(pParse, 0, iDb);
92784     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
92785     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
92786     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
92787     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
92788     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
92789     sqlite3VdbeJumpHere(v, addr);
92790   }else
92791 #endif
92792
92793 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
92794   /*
92795   **  PRAGMA [database.]cache_size
92796   **  PRAGMA [database.]cache_size=N
92797   **
92798   ** The first form reports the current local setting for the
92799   ** page cache size. The second form sets the local
92800   ** page cache size value.  If N is positive then that is the
92801   ** number of pages in the cache.  If N is negative, then the
92802   ** number of pages is adjusted so that the cache uses -N kibibytes
92803   ** of memory.
92804   */
92805   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
92806     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92807     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92808     if( !zRight ){
92809       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
92810     }else{
92811       int size = sqlite3Atoi(zRight);
92812       pDb->pSchema->cache_size = size;
92813       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92814     }
92815   }else
92816
92817   /*
92818   **   PRAGMA temp_store
92819   **   PRAGMA temp_store = "default"|"memory"|"file"
92820   **
92821   ** Return or set the local value of the temp_store flag.  Changing
92822   ** the local value does not make changes to the disk file and the default
92823   ** value will be restored the next time the database is opened.
92824   **
92825   ** Note that it is possible for the library compile-time options to
92826   ** override this setting
92827   */
92828   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
92829     if( !zRight ){
92830       returnSingleInt(pParse, "temp_store", db->temp_store);
92831     }else{
92832       changeTempStorage(pParse, zRight);
92833     }
92834   }else
92835
92836   /*
92837   **   PRAGMA temp_store_directory
92838   **   PRAGMA temp_store_directory = ""|"directory_name"
92839   **
92840   ** Return or set the local value of the temp_store_directory flag.  Changing
92841   ** the value sets a specific directory to be used for temporary files.
92842   ** Setting to a null string reverts to the default temporary directory search.
92843   ** If temporary directory is changed, then invalidateTempStorage.
92844   **
92845   */
92846   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
92847     if( !zRight ){
92848       if( sqlite3_temp_directory ){
92849         sqlite3VdbeSetNumCols(v, 1);
92850         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
92851             "temp_store_directory", SQLITE_STATIC);
92852         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
92853         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92854       }
92855     }else{
92856 #ifndef SQLITE_OMIT_WSD
92857       if( zRight[0] ){
92858         int res;
92859         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
92860         if( rc!=SQLITE_OK || res==0 ){
92861           sqlite3ErrorMsg(pParse, "not a writable directory");
92862           goto pragma_out;
92863         }
92864       }
92865       if( SQLITE_TEMP_STORE==0
92866        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
92867        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
92868       ){
92869         invalidateTempStorage(pParse);
92870       }
92871       sqlite3_free(sqlite3_temp_directory);
92872       if( zRight[0] ){
92873         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
92874       }else{
92875         sqlite3_temp_directory = 0;
92876       }
92877 #endif /* SQLITE_OMIT_WSD */
92878     }
92879   }else
92880
92881 #if SQLITE_OS_WIN
92882   /*
92883   **   PRAGMA data_store_directory
92884   **   PRAGMA data_store_directory = ""|"directory_name"
92885   **
92886   ** Return or set the local value of the data_store_directory flag.  Changing
92887   ** the value sets a specific directory to be used for database files that
92888   ** were specified with a relative pathname.  Setting to a null string reverts
92889   ** to the default database directory, which for database files specified with
92890   ** a relative path will probably be based on the current directory for the
92891   ** process.  Database file specified with an absolute path are not impacted
92892   ** by this setting, regardless of its value.
92893   **
92894   */
92895   if( sqlite3StrICmp(zLeft, "data_store_directory")==0 ){
92896     if( !zRight ){
92897       if( sqlite3_data_directory ){
92898         sqlite3VdbeSetNumCols(v, 1);
92899         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
92900             "data_store_directory", SQLITE_STATIC);
92901         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
92902         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92903       }
92904     }else{
92905 #ifndef SQLITE_OMIT_WSD
92906       if( zRight[0] ){
92907         int res;
92908         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
92909         if( rc!=SQLITE_OK || res==0 ){
92910           sqlite3ErrorMsg(pParse, "not a writable directory");
92911           goto pragma_out;
92912         }
92913       }
92914       sqlite3_free(sqlite3_data_directory);
92915       if( zRight[0] ){
92916         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
92917       }else{
92918         sqlite3_data_directory = 0;
92919       }
92920 #endif /* SQLITE_OMIT_WSD */
92921     }
92922   }else
92923 #endif
92924
92925 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
92926 #  if defined(__APPLE__)
92927 #    define SQLITE_ENABLE_LOCKING_STYLE 1
92928 #  else
92929 #    define SQLITE_ENABLE_LOCKING_STYLE 0
92930 #  endif
92931 #endif
92932 #if SQLITE_ENABLE_LOCKING_STYLE
92933   /*
92934    **   PRAGMA [database.]lock_proxy_file
92935    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
92936    **
92937    ** Return or set the value of the lock_proxy_file flag.  Changing
92938    ** the value sets a specific file to be used for database access locks.
92939    **
92940    */
92941   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
92942     if( !zRight ){
92943       Pager *pPager = sqlite3BtreePager(pDb->pBt);
92944       char *proxy_file_path = NULL;
92945       sqlite3_file *pFile = sqlite3PagerFile(pPager);
92946       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
92947                            &proxy_file_path);
92948       
92949       if( proxy_file_path ){
92950         sqlite3VdbeSetNumCols(v, 1);
92951         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
92952                               "lock_proxy_file", SQLITE_STATIC);
92953         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
92954         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92955       }
92956     }else{
92957       Pager *pPager = sqlite3BtreePager(pDb->pBt);
92958       sqlite3_file *pFile = sqlite3PagerFile(pPager);
92959       int res;
92960       if( zRight[0] ){
92961         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
92962                                      zRight);
92963       } else {
92964         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
92965                                      NULL);
92966       }
92967       if( res!=SQLITE_OK ){
92968         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
92969         goto pragma_out;
92970       }
92971     }
92972   }else
92973 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
92974     
92975   /*
92976   **   PRAGMA [database.]synchronous
92977   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
92978   **
92979   ** Return or set the local value of the synchronous flag.  Changing
92980   ** the local value does not make changes to the disk file and the
92981   ** default value will be restored the next time the database is
92982   ** opened.
92983   */
92984   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
92985     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92986     if( !zRight ){
92987       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
92988     }else{
92989       if( !db->autoCommit ){
92990         sqlite3ErrorMsg(pParse, 
92991             "Safety level may not be changed inside a transaction");
92992       }else{
92993         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
92994       }
92995     }
92996   }else
92997 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
92998
92999 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
93000   if( flagPragma(pParse, zLeft, zRight) ){
93001     /* The flagPragma() subroutine also generates any necessary code
93002     ** there is nothing more to do here */
93003   }else
93004 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
93005
93006 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
93007   /*
93008   **   PRAGMA table_info(<table>)
93009   **
93010   ** Return a single row for each column of the named table. The columns of
93011   ** the returned data set are:
93012   **
93013   ** cid:        Column id (numbered from left to right, starting at 0)
93014   ** name:       Column name
93015   ** type:       Column declaration type.
93016   ** notnull:    True if 'NOT NULL' is part of column declaration
93017   ** dflt_value: The default value for the column, if any.
93018   */
93019   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
93020     Table *pTab;
93021     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93022     pTab = sqlite3FindTable(db, zRight, zDb);
93023     if( pTab ){
93024       int i, k;
93025       int nHidden = 0;
93026       Column *pCol;
93027       Index *pPk;
93028       for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){}
93029       sqlite3VdbeSetNumCols(v, 6);
93030       pParse->nMem = 6;
93031       sqlite3CodeVerifySchema(pParse, iDb);
93032       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
93033       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93034       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
93035       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
93036       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
93037       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
93038       sqlite3ViewGetColumnNames(pParse, pTab);
93039       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
93040         if( IsHiddenColumn(pCol) ){
93041           nHidden++;
93042           continue;
93043         }
93044         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
93045         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
93046         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
93047            pCol->zType ? pCol->zType : "", 0);
93048         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
93049         if( pCol->zDflt ){
93050           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
93051         }else{
93052           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
93053         }
93054         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
93055           k = 0;
93056         }else if( pPk==0 ){
93057           k = 1;
93058         }else{
93059           for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
93060         }
93061         sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
93062         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
93063       }
93064     }
93065   }else
93066
93067   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
93068     Index *pIdx;
93069     Table *pTab;
93070     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93071     pIdx = sqlite3FindIndex(db, zRight, zDb);
93072     if( pIdx ){
93073       int i;
93074       pTab = pIdx->pTable;
93075       sqlite3VdbeSetNumCols(v, 3);
93076       pParse->nMem = 3;
93077       sqlite3CodeVerifySchema(pParse, iDb);
93078       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
93079       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
93080       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
93081       for(i=0; i<pIdx->nColumn; i++){
93082         int cnum = pIdx->aiColumn[i];
93083         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93084         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
93085         assert( pTab->nCol>cnum );
93086         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
93087         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93088       }
93089     }
93090   }else
93091
93092   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
93093     Index *pIdx;
93094     Table *pTab;
93095     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93096     pTab = sqlite3FindTable(db, zRight, zDb);
93097     if( pTab ){
93098       v = sqlite3GetVdbe(pParse);
93099       pIdx = pTab->pIndex;
93100       if( pIdx ){
93101         int i = 0; 
93102         sqlite3VdbeSetNumCols(v, 3);
93103         pParse->nMem = 3;
93104         sqlite3CodeVerifySchema(pParse, iDb);
93105         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
93106         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93107         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
93108         while(pIdx){
93109           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93110           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
93111           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
93112           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93113           ++i;
93114           pIdx = pIdx->pNext;
93115         }
93116       }
93117     }
93118   }else
93119
93120   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
93121     int i;
93122     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93123     sqlite3VdbeSetNumCols(v, 3);
93124     pParse->nMem = 3;
93125     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
93126     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93127     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
93128     for(i=0; i<db->nDb; i++){
93129       if( db->aDb[i].pBt==0 ) continue;
93130       assert( db->aDb[i].zName!=0 );
93131       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93132       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
93133       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
93134            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
93135       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93136     }
93137   }else
93138
93139   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
93140     int i = 0;
93141     HashElem *p;
93142     sqlite3VdbeSetNumCols(v, 2);
93143     pParse->nMem = 2;
93144     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
93145     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93146     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
93147       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
93148       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
93149       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
93150       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
93151     }
93152   }else
93153 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
93154
93155 #ifndef SQLITE_OMIT_FOREIGN_KEY
93156   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
93157     FKey *pFK;
93158     Table *pTab;
93159     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93160     pTab = sqlite3FindTable(db, zRight, zDb);
93161     if( pTab ){
93162       v = sqlite3GetVdbe(pParse);
93163       pFK = pTab->pFKey;
93164       if( pFK ){
93165         int i = 0; 
93166         sqlite3VdbeSetNumCols(v, 8);
93167         pParse->nMem = 8;
93168         sqlite3CodeVerifySchema(pParse, iDb);
93169         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
93170         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
93171         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
93172         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
93173         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
93174         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
93175         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
93176         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
93177         while(pFK){
93178           int j;
93179           for(j=0; j<pFK->nCol; j++){
93180             char *zCol = pFK->aCol[j].zCol;
93181             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
93182             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
93183             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93184             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
93185             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
93186             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
93187                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
93188             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
93189             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
93190             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
93191             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
93192             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
93193           }
93194           ++i;
93195           pFK = pFK->pNextFrom;
93196         }
93197       }
93198     }
93199   }else
93200 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
93201
93202 #ifndef SQLITE_OMIT_FOREIGN_KEY
93203 #ifndef SQLITE_OMIT_TRIGGER
93204   if( sqlite3StrICmp(zLeft, "foreign_key_check")==0 ){
93205     FKey *pFK;             /* A foreign key constraint */
93206     Table *pTab;           /* Child table contain "REFERENCES" keyword */
93207     Table *pParent;        /* Parent table that child points to */
93208     Index *pIdx;           /* Index in the parent table */
93209     int i;                 /* Loop counter:  Foreign key number for pTab */
93210     int j;                 /* Loop counter:  Field of the foreign key */
93211     HashElem *k;           /* Loop counter:  Next table in schema */
93212     int x;                 /* result variable */
93213     int regResult;         /* 3 registers to hold a result row */
93214     int regKey;            /* Register to hold key for checking the FK */
93215     int regRow;            /* Registers to hold a row from pTab */
93216     int addrTop;           /* Top of a loop checking foreign keys */
93217     int addrOk;            /* Jump here if the key is OK */
93218     int *aiCols;           /* child to parent column mapping */
93219
93220     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93221     regResult = pParse->nMem+1;
93222     pParse->nMem += 4;
93223     regKey = ++pParse->nMem;
93224     regRow = ++pParse->nMem;
93225     v = sqlite3GetVdbe(pParse);
93226     sqlite3VdbeSetNumCols(v, 4);
93227     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
93228     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
93229     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
93230     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
93231     sqlite3CodeVerifySchema(pParse, iDb);
93232     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
93233     while( k ){
93234       if( zRight ){
93235         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
93236         k = 0;
93237       }else{
93238         pTab = (Table*)sqliteHashData(k);
93239         k = sqliteHashNext(k);
93240       }
93241       if( pTab==0 || pTab->pFKey==0 ) continue;
93242       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
93243       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
93244       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
93245       sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
93246                         P4_TRANSIENT);
93247       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
93248         pParent = sqlite3LocateTable(pParse, 0, pFK->zTo, zDb);
93249         if( pParent==0 ) break;
93250         pIdx = 0;
93251         sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
93252         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
93253         if( x==0 ){
93254           if( pIdx==0 ){
93255             sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
93256           }else{
93257             KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
93258             sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
93259             sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
93260           }
93261         }else{
93262           k = 0;
93263           break;
93264         }
93265       }
93266       if( pFK ) break;
93267       if( pParse->nTab<i ) pParse->nTab = i;
93268       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
93269       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
93270         pParent = sqlite3LocateTable(pParse, 0, pFK->zTo, zDb);
93271         assert( pParent!=0 );
93272         pIdx = 0;
93273         aiCols = 0;
93274         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
93275         assert( x==0 );
93276         addrOk = sqlite3VdbeMakeLabel(v);
93277         if( pIdx==0 ){
93278           int iKey = pFK->aCol[0].iFrom;
93279           assert( iKey>=0 && iKey<pTab->nCol );
93280           if( iKey!=pTab->iPKey ){
93281             sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
93282             sqlite3ColumnDefault(v, pTab, iKey, regRow);
93283             sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
93284             sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
93285                sqlite3VdbeCurrentAddr(v)+3);
93286           }else{
93287             sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
93288           }
93289           sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
93290           sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
93291           sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
93292         }else{
93293           for(j=0; j<pFK->nCol; j++){
93294             sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
93295                             aiCols ? aiCols[j] : pFK->aCol[0].iFrom, regRow+j);
93296             sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
93297           }
93298           sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
93299           sqlite3VdbeChangeP4(v, -1,
93300                    sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
93301           sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
93302         }
93303         sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
93304         sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0, 
93305                           pFK->zTo, P4_TRANSIENT);
93306         sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
93307         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
93308         sqlite3VdbeResolveLabel(v, addrOk);
93309         sqlite3DbFree(db, aiCols);
93310       }
93311       sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
93312       sqlite3VdbeJumpHere(v, addrTop);
93313     }
93314   }else
93315 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
93316 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
93317
93318 #ifndef NDEBUG
93319   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
93320     if( zRight ){
93321       if( sqlite3GetBoolean(zRight, 0) ){
93322         sqlite3ParserTrace(stderr, "parser: ");
93323       }else{
93324         sqlite3ParserTrace(0, 0);
93325       }
93326     }
93327   }else
93328 #endif
93329
93330   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
93331   ** used will be case sensitive or not depending on the RHS.
93332   */
93333   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
93334     if( zRight ){
93335       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
93336     }
93337   }else
93338
93339 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
93340 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
93341 #endif
93342
93343 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
93344   /* Pragma "quick_check" is an experimental reduced version of 
93345   ** integrity_check designed to detect most database corruption
93346   ** without most of the overhead of a full integrity-check.
93347   */
93348   if( sqlite3StrICmp(zLeft, "integrity_check")==0
93349    || sqlite3StrICmp(zLeft, "quick_check")==0 
93350   ){
93351     int i, j, addr, mxErr;
93352
93353     /* Code that appears at the end of the integrity check.  If no error
93354     ** messages have been generated, output OK.  Otherwise output the
93355     ** error message
93356     */
93357     static const VdbeOpList endCode[] = {
93358       { OP_AddImm,      1, 0,        0},    /* 0 */
93359       { OP_IfNeg,       1, 0,        0},    /* 1 */
93360       { OP_String8,     0, 3,        0},    /* 2 */
93361       { OP_ResultRow,   3, 1,        0},
93362     };
93363
93364     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
93365
93366     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
93367     ** then iDb is set to the index of the database identified by <db>.
93368     ** In this case, the integrity of database iDb only is verified by
93369     ** the VDBE created below.
93370     **
93371     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
93372     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
93373     ** to -1 here, to indicate that the VDBE should verify the integrity
93374     ** of all attached databases.  */
93375     assert( iDb>=0 );
93376     assert( iDb==0 || pId2->z );
93377     if( pId2->z==0 ) iDb = -1;
93378
93379     /* Initialize the VDBE program */
93380     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93381     pParse->nMem = 6;
93382     sqlite3VdbeSetNumCols(v, 1);
93383     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
93384
93385     /* Set the maximum error count */
93386     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
93387     if( zRight ){
93388       sqlite3GetInt32(zRight, &mxErr);
93389       if( mxErr<=0 ){
93390         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
93391       }
93392     }
93393     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
93394
93395     /* Do an integrity check on each database file */
93396     for(i=0; i<db->nDb; i++){
93397       HashElem *x;
93398       Hash *pTbls;
93399       int cnt = 0;
93400
93401       if( OMIT_TEMPDB && i==1 ) continue;
93402       if( iDb>=0 && i!=iDb ) continue;
93403
93404       sqlite3CodeVerifySchema(pParse, i);
93405       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
93406       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93407       sqlite3VdbeJumpHere(v, addr);
93408
93409       /* Do an integrity check of the B-Tree
93410       **
93411       ** Begin by filling registers 2, 3, ... with the root pages numbers
93412       ** for all tables and indices in the database.
93413       */
93414       assert( sqlite3SchemaMutexHeld(db, i, 0) );
93415       pTbls = &db->aDb[i].pSchema->tblHash;
93416       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
93417         Table *pTab = sqliteHashData(x);
93418         Index *pIdx;
93419         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
93420         cnt++;
93421         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93422           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
93423           cnt++;
93424         }
93425       }
93426
93427       /* Make sure sufficient number of registers have been allocated */
93428       if( pParse->nMem < cnt+4 ){
93429         pParse->nMem = cnt+4;
93430       }
93431
93432       /* Do the b-tree integrity checks */
93433       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
93434       sqlite3VdbeChangeP5(v, (u8)i);
93435       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
93436       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
93437          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
93438          P4_DYNAMIC);
93439       sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
93440       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
93441       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
93442       sqlite3VdbeJumpHere(v, addr);
93443
93444       /* Make sure all the indices are constructed correctly.
93445       */
93446       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
93447         Table *pTab = sqliteHashData(x);
93448         Index *pIdx;
93449         int loopTop;
93450
93451         if( pTab->pIndex==0 ) continue;
93452         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
93453         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93454         sqlite3VdbeJumpHere(v, addr);
93455         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
93456         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
93457         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
93458         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
93459         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
93460           int jmp2;
93461           int r1;
93462           static const VdbeOpList idxErr[] = {
93463             { OP_AddImm,      1, -1,  0},
93464             { OP_String8,     0,  3,  0},    /* 1 */
93465             { OP_Rowid,       1,  4,  0},
93466             { OP_String8,     0,  5,  0},    /* 3 */
93467             { OP_String8,     0,  6,  0},    /* 4 */
93468             { OP_Concat,      4,  3,  3},
93469             { OP_Concat,      5,  3,  3},
93470             { OP_Concat,      6,  3,  3},
93471             { OP_ResultRow,   3,  1,  0},
93472             { OP_IfPos,       1,  0,  0},    /* 9 */
93473             { OP_Halt,        0,  0,  0},
93474           };
93475           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
93476           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
93477           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
93478           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
93479           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
93480           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
93481           sqlite3VdbeJumpHere(v, addr+9);
93482           sqlite3VdbeJumpHere(v, jmp2);
93483         }
93484         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
93485         sqlite3VdbeJumpHere(v, loopTop);
93486         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
93487           static const VdbeOpList cntIdx[] = {
93488              { OP_Integer,      0,  3,  0},
93489              { OP_Rewind,       0,  0,  0},  /* 1 */
93490              { OP_AddImm,       3,  1,  0},
93491              { OP_Next,         0,  0,  0},  /* 3 */
93492              { OP_Eq,           2,  0,  3},  /* 4 */
93493              { OP_AddImm,       1, -1,  0},
93494              { OP_String8,      0,  2,  0},  /* 6 */
93495              { OP_String8,      0,  3,  0},  /* 7 */
93496              { OP_Concat,       3,  2,  2},
93497              { OP_ResultRow,    2,  1,  0},
93498           };
93499           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
93500           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93501           sqlite3VdbeJumpHere(v, addr);
93502           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
93503           sqlite3VdbeChangeP1(v, addr+1, j+2);
93504           sqlite3VdbeChangeP2(v, addr+1, addr+4);
93505           sqlite3VdbeChangeP1(v, addr+3, j+2);
93506           sqlite3VdbeChangeP2(v, addr+3, addr+2);
93507           sqlite3VdbeJumpHere(v, addr+4);
93508           sqlite3VdbeChangeP4(v, addr+6, 
93509                      "wrong # of entries in index ", P4_STATIC);
93510           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
93511         }
93512       } 
93513     }
93514     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
93515     sqlite3VdbeChangeP2(v, addr, -mxErr);
93516     sqlite3VdbeJumpHere(v, addr+1);
93517     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
93518   }else
93519 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
93520
93521 #ifndef SQLITE_OMIT_UTF16
93522   /*
93523   **   PRAGMA encoding
93524   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
93525   **
93526   ** In its first form, this pragma returns the encoding of the main
93527   ** database. If the database is not initialized, it is initialized now.
93528   **
93529   ** The second form of this pragma is a no-op if the main database file
93530   ** has not already been initialized. In this case it sets the default
93531   ** encoding that will be used for the main database file if a new file
93532   ** is created. If an existing main database file is opened, then the
93533   ** default text encoding for the existing database is used.
93534   ** 
93535   ** In all cases new databases created using the ATTACH command are
93536   ** created to use the same default text encoding as the main database. If
93537   ** the main database has not been initialized and/or created when ATTACH
93538   ** is executed, this is done before the ATTACH operation.
93539   **
93540   ** In the second form this pragma sets the text encoding to be used in
93541   ** new database files created using this database handle. It is only
93542   ** useful if invoked immediately after the main database i
93543   */
93544   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
93545     static const struct EncName {
93546       char *zName;
93547       u8 enc;
93548     } encnames[] = {
93549       { "UTF8",     SQLITE_UTF8        },
93550       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
93551       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
93552       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
93553       { "UTF16le",  SQLITE_UTF16LE     },
93554       { "UTF16be",  SQLITE_UTF16BE     },
93555       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
93556       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
93557       { 0, 0 }
93558     };
93559     const struct EncName *pEnc;
93560     if( !zRight ){    /* "PRAGMA encoding" */
93561       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93562       sqlite3VdbeSetNumCols(v, 1);
93563       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
93564       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
93565       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
93566       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
93567       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
93568       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
93569       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93570     }else{                        /* "PRAGMA encoding = XXX" */
93571       /* Only change the value of sqlite.enc if the database handle is not
93572       ** initialized. If the main database exists, the new sqlite.enc value
93573       ** will be overwritten when the schema is next loaded. If it does not
93574       ** already exists, it will be created to use the new encoding value.
93575       */
93576       if( 
93577         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
93578         DbHasProperty(db, 0, DB_Empty) 
93579       ){
93580         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
93581           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
93582             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
93583             break;
93584           }
93585         }
93586         if( !pEnc->zName ){
93587           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
93588         }
93589       }
93590     }
93591   }else
93592 #endif /* SQLITE_OMIT_UTF16 */
93593
93594 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
93595   /*
93596   **   PRAGMA [database.]schema_version
93597   **   PRAGMA [database.]schema_version = <integer>
93598   **
93599   **   PRAGMA [database.]user_version
93600   **   PRAGMA [database.]user_version = <integer>
93601   **
93602   ** The pragma's schema_version and user_version are used to set or get
93603   ** the value of the schema-version and user-version, respectively. Both
93604   ** the schema-version and the user-version are 32-bit signed integers
93605   ** stored in the database header.
93606   **
93607   ** The schema-cookie is usually only manipulated internally by SQLite. It
93608   ** is incremented by SQLite whenever the database schema is modified (by
93609   ** creating or dropping a table or index). The schema version is used by
93610   ** SQLite each time a query is executed to ensure that the internal cache
93611   ** of the schema used when compiling the SQL query matches the schema of
93612   ** the database against which the compiled query is actually executed.
93613   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
93614   ** the schema-version is potentially dangerous and may lead to program
93615   ** crashes or database corruption. Use with caution!
93616   **
93617   ** The user-version is not used internally by SQLite. It may be used by
93618   ** applications for any purpose.
93619   */
93620   if( sqlite3StrICmp(zLeft, "schema_version")==0 
93621    || sqlite3StrICmp(zLeft, "user_version")==0 
93622    || sqlite3StrICmp(zLeft, "freelist_count")==0 
93623   ){
93624     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
93625     sqlite3VdbeUsesBtree(v, iDb);
93626     switch( zLeft[0] ){
93627       case 'f': case 'F':
93628         iCookie = BTREE_FREE_PAGE_COUNT;
93629         break;
93630       case 's': case 'S':
93631         iCookie = BTREE_SCHEMA_VERSION;
93632         break;
93633       default:
93634         iCookie = BTREE_USER_VERSION;
93635         break;
93636     }
93637
93638     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
93639       /* Write the specified cookie value */
93640       static const VdbeOpList setCookie[] = {
93641         { OP_Transaction,    0,  1,  0},    /* 0 */
93642         { OP_Integer,        0,  1,  0},    /* 1 */
93643         { OP_SetCookie,      0,  0,  1},    /* 2 */
93644       };
93645       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
93646       sqlite3VdbeChangeP1(v, addr, iDb);
93647       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
93648       sqlite3VdbeChangeP1(v, addr+2, iDb);
93649       sqlite3VdbeChangeP2(v, addr+2, iCookie);
93650     }else{
93651       /* Read the specified cookie value */
93652       static const VdbeOpList readCookie[] = {
93653         { OP_Transaction,     0,  0,  0},    /* 0 */
93654         { OP_ReadCookie,      0,  1,  0},    /* 1 */
93655         { OP_ResultRow,       1,  1,  0}
93656       };
93657       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
93658       sqlite3VdbeChangeP1(v, addr, iDb);
93659       sqlite3VdbeChangeP1(v, addr+1, iDb);
93660       sqlite3VdbeChangeP3(v, addr+1, iCookie);
93661       sqlite3VdbeSetNumCols(v, 1);
93662       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
93663     }
93664   }else
93665 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
93666
93667 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
93668   /*
93669   **   PRAGMA compile_options
93670   **
93671   ** Return the names of all compile-time options used in this build,
93672   ** one option per row.
93673   */
93674   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
93675     int i = 0;
93676     const char *zOpt;
93677     sqlite3VdbeSetNumCols(v, 1);
93678     pParse->nMem = 1;
93679     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
93680     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
93681       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
93682       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93683     }
93684   }else
93685 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
93686
93687 #ifndef SQLITE_OMIT_WAL
93688   /*
93689   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
93690   **
93691   ** Checkpoint the database.
93692   */
93693   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
93694     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
93695     int eMode = SQLITE_CHECKPOINT_PASSIVE;
93696     if( zRight ){
93697       if( sqlite3StrICmp(zRight, "full")==0 ){
93698         eMode = SQLITE_CHECKPOINT_FULL;
93699       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
93700         eMode = SQLITE_CHECKPOINT_RESTART;
93701       }
93702     }
93703     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93704     sqlite3VdbeSetNumCols(v, 3);
93705     pParse->nMem = 3;
93706     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
93707     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
93708     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
93709
93710     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
93711     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93712   }else
93713
93714   /*
93715   **   PRAGMA wal_autocheckpoint
93716   **   PRAGMA wal_autocheckpoint = N
93717   **
93718   ** Configure a database connection to automatically checkpoint a database
93719   ** after accumulating N frames in the log. Or query for the current value
93720   ** of N.
93721   */
93722   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
93723     if( zRight ){
93724       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
93725     }
93726     returnSingleInt(pParse, "wal_autocheckpoint", 
93727        db->xWalCallback==sqlite3WalDefaultHook ? 
93728            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
93729   }else
93730 #endif
93731
93732   /*
93733   **  PRAGMA shrink_memory
93734   **
93735   ** This pragma attempts to free as much memory as possible from the
93736   ** current database connection.
93737   */
93738   if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
93739     sqlite3_db_release_memory(db);
93740   }else
93741
93742   /*
93743   **   PRAGMA busy_timeout
93744   **   PRAGMA busy_timeout = N
93745   **
93746   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
93747   ** if one is set.  If no busy handler or a different busy handler is set
93748   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
93749   ** disables the timeout.
93750   */
93751   if( sqlite3StrICmp(zLeft, "busy_timeout")==0 ){
93752     if( zRight ){
93753       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
93754     }
93755     returnSingleInt(pParse, "timeout",  db->busyTimeout);
93756   }else
93757
93758 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
93759   /*
93760   ** Report the current state of file logs for all databases
93761   */
93762   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
93763     static const char *const azLockName[] = {
93764       "unlocked", "shared", "reserved", "pending", "exclusive"
93765     };
93766     int i;
93767     sqlite3VdbeSetNumCols(v, 2);
93768     pParse->nMem = 2;
93769     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
93770     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
93771     for(i=0; i<db->nDb; i++){
93772       Btree *pBt;
93773       const char *zState = "unknown";
93774       int j;
93775       if( db->aDb[i].zName==0 ) continue;
93776       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
93777       pBt = db->aDb[i].pBt;
93778       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
93779         zState = "closed";
93780       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
93781                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
93782          zState = azLockName[j];
93783       }
93784       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
93785       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
93786     }
93787
93788   }else
93789 #endif
93790
93791 #ifdef SQLITE_HAS_CODEC
93792   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
93793     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
93794   }else
93795   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
93796     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
93797   }else
93798   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
93799                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
93800     int i, h1, h2;
93801     char zKey[40];
93802     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
93803       h1 += 9*(1&(h1>>6));
93804       h2 += 9*(1&(h2>>6));
93805       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
93806     }
93807     if( (zLeft[3] & 0xf)==0xb ){
93808       sqlite3_key(db, zKey, i/2);
93809     }else{
93810       sqlite3_rekey(db, zKey, i/2);
93811     }
93812   }else
93813 #endif
93814 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
93815   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 && zRight ){
93816 #ifdef SQLITE_HAS_CODEC
93817     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
93818       sqlite3_activate_see(&zRight[4]);
93819     }
93820 #endif
93821 #ifdef SQLITE_ENABLE_CEROD
93822     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
93823       sqlite3_activate_cerod(&zRight[6]);
93824     }
93825 #endif
93826   }else
93827 #endif
93828
93829  
93830   {/* Empty ELSE clause */}
93831
93832   /*
93833   ** Reset the safety level, in case the fullfsync flag or synchronous
93834   ** setting changed.
93835   */
93836 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93837   if( db->autoCommit ){
93838     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
93839                (db->flags&SQLITE_FullFSync)!=0,
93840                (db->flags&SQLITE_CkptFullFSync)!=0);
93841   }
93842 #endif
93843 pragma_out:
93844   sqlite3DbFree(db, zLeft);
93845   sqlite3DbFree(db, zRight);
93846 }
93847
93848 #endif /* SQLITE_OMIT_PRAGMA */
93849
93850 /************** End of pragma.c **********************************************/
93851 /************** Begin file prepare.c *****************************************/
93852 /*
93853 ** 2005 May 25
93854 **
93855 ** The author disclaims copyright to this source code.  In place of
93856 ** a legal notice, here is a blessing:
93857 **
93858 **    May you do good and not evil.
93859 **    May you find forgiveness for yourself and forgive others.
93860 **    May you share freely, never taking more than you give.
93861 **
93862 *************************************************************************
93863 ** This file contains the implementation of the sqlite3_prepare()
93864 ** interface, and routines that contribute to loading the database schema
93865 ** from disk.
93866 */
93867
93868 /*
93869 ** Fill the InitData structure with an error message that indicates
93870 ** that the database is corrupt.
93871 */
93872 static void corruptSchema(
93873   InitData *pData,     /* Initialization context */
93874   const char *zObj,    /* Object being parsed at the point of error */
93875   const char *zExtra   /* Error information */
93876 ){
93877   sqlite3 *db = pData->db;
93878   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
93879     if( zObj==0 ) zObj = "?";
93880     sqlite3SetString(pData->pzErrMsg, db,
93881       "malformed database schema (%s)", zObj);
93882     if( zExtra ){
93883       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
93884                                  "%s - %s", *pData->pzErrMsg, zExtra);
93885     }
93886   }
93887   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
93888 }
93889
93890 /*
93891 ** This is the callback routine for the code that initializes the
93892 ** database.  See sqlite3Init() below for additional information.
93893 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
93894 **
93895 ** Each callback contains the following information:
93896 **
93897 **     argv[0] = name of thing being created
93898 **     argv[1] = root page number for table or index. 0 for trigger or view.
93899 **     argv[2] = SQL text for the CREATE statement.
93900 **
93901 */
93902 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
93903   InitData *pData = (InitData*)pInit;
93904   sqlite3 *db = pData->db;
93905   int iDb = pData->iDb;
93906
93907   assert( argc==3 );
93908   UNUSED_PARAMETER2(NotUsed, argc);
93909   assert( sqlite3_mutex_held(db->mutex) );
93910   DbClearProperty(db, iDb, DB_Empty);
93911   if( db->mallocFailed ){
93912     corruptSchema(pData, argv[0], 0);
93913     return 1;
93914   }
93915
93916   assert( iDb>=0 && iDb<db->nDb );
93917   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
93918   if( argv[1]==0 ){
93919     corruptSchema(pData, argv[0], 0);
93920   }else if( argv[2] && argv[2][0] ){
93921     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
93922     ** But because db->init.busy is set to 1, no VDBE code is generated
93923     ** or executed.  All the parser does is build the internal data
93924     ** structures that describe the table, index, or view.
93925     */
93926     int rc;
93927     sqlite3_stmt *pStmt;
93928     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
93929
93930     assert( db->init.busy );
93931     db->init.iDb = iDb;
93932     db->init.newTnum = sqlite3Atoi(argv[1]);
93933     db->init.orphanTrigger = 0;
93934     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
93935     rc = db->errCode;
93936     assert( (rc&0xFF)==(rcp&0xFF) );
93937     db->init.iDb = 0;
93938     if( SQLITE_OK!=rc ){
93939       if( db->init.orphanTrigger ){
93940         assert( iDb==1 );
93941       }else{
93942         pData->rc = rc;
93943         if( rc==SQLITE_NOMEM ){
93944           db->mallocFailed = 1;
93945         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
93946           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
93947         }
93948       }
93949     }
93950     sqlite3_finalize(pStmt);
93951   }else if( argv[0]==0 ){
93952     corruptSchema(pData, 0, 0);
93953   }else{
93954     /* If the SQL column is blank it means this is an index that
93955     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
93956     ** constraint for a CREATE TABLE.  The index should have already
93957     ** been created when we processed the CREATE TABLE.  All we have
93958     ** to do here is record the root page number for that index.
93959     */
93960     Index *pIndex;
93961     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
93962     if( pIndex==0 ){
93963       /* This can occur if there exists an index on a TEMP table which
93964       ** has the same name as another index on a permanent index.  Since
93965       ** the permanent table is hidden by the TEMP table, we can also
93966       ** safely ignore the index on the permanent table.
93967       */
93968       /* Do Nothing */;
93969     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
93970       corruptSchema(pData, argv[0], "invalid rootpage");
93971     }
93972   }
93973   return 0;
93974 }
93975
93976 /*
93977 ** Attempt to read the database schema and initialize internal
93978 ** data structures for a single database file.  The index of the
93979 ** database file is given by iDb.  iDb==0 is used for the main
93980 ** database.  iDb==1 should never be used.  iDb>=2 is used for
93981 ** auxiliary databases.  Return one of the SQLITE_ error codes to
93982 ** indicate success or failure.
93983 */
93984 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
93985   int rc;
93986   int i;
93987 #ifndef SQLITE_OMIT_DEPRECATED
93988   int size;
93989 #endif
93990   Table *pTab;
93991   Db *pDb;
93992   char const *azArg[4];
93993   int meta[5];
93994   InitData initData;
93995   char const *zMasterSchema;
93996   char const *zMasterName;
93997   int openedTransaction = 0;
93998
93999   /*
94000   ** The master database table has a structure like this
94001   */
94002   static const char master_schema[] = 
94003      "CREATE TABLE sqlite_master(\n"
94004      "  type text,\n"
94005      "  name text,\n"
94006      "  tbl_name text,\n"
94007      "  rootpage integer,\n"
94008      "  sql text\n"
94009      ")"
94010   ;
94011 #ifndef SQLITE_OMIT_TEMPDB
94012   static const char temp_master_schema[] = 
94013      "CREATE TEMP TABLE sqlite_temp_master(\n"
94014      "  type text,\n"
94015      "  name text,\n"
94016      "  tbl_name text,\n"
94017      "  rootpage integer,\n"
94018      "  sql text\n"
94019      ")"
94020   ;
94021 #else
94022   #define temp_master_schema 0
94023 #endif
94024
94025   assert( iDb>=0 && iDb<db->nDb );
94026   assert( db->aDb[iDb].pSchema );
94027   assert( sqlite3_mutex_held(db->mutex) );
94028   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
94029
94030   /* zMasterSchema and zInitScript are set to point at the master schema
94031   ** and initialisation script appropriate for the database being
94032   ** initialized. zMasterName is the name of the master table.
94033   */
94034   if( !OMIT_TEMPDB && iDb==1 ){
94035     zMasterSchema = temp_master_schema;
94036   }else{
94037     zMasterSchema = master_schema;
94038   }
94039   zMasterName = SCHEMA_TABLE(iDb);
94040
94041   /* Construct the schema tables.  */
94042   azArg[0] = zMasterName;
94043   azArg[1] = "1";
94044   azArg[2] = zMasterSchema;
94045   azArg[3] = 0;
94046   initData.db = db;
94047   initData.iDb = iDb;
94048   initData.rc = SQLITE_OK;
94049   initData.pzErrMsg = pzErrMsg;
94050   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
94051   if( initData.rc ){
94052     rc = initData.rc;
94053     goto error_out;
94054   }
94055   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
94056   if( ALWAYS(pTab) ){
94057     pTab->tabFlags |= TF_Readonly;
94058   }
94059
94060   /* Create a cursor to hold the database open
94061   */
94062   pDb = &db->aDb[iDb];
94063   if( pDb->pBt==0 ){
94064     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
94065       DbSetProperty(db, 1, DB_SchemaLoaded);
94066     }
94067     return SQLITE_OK;
94068   }
94069
94070   /* If there is not already a read-only (or read-write) transaction opened
94071   ** on the b-tree database, open one now. If a transaction is opened, it 
94072   ** will be closed before this function returns.  */
94073   sqlite3BtreeEnter(pDb->pBt);
94074   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
94075     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
94076     if( rc!=SQLITE_OK ){
94077       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
94078       goto initone_error_out;
94079     }
94080     openedTransaction = 1;
94081   }
94082
94083   /* Get the database meta information.
94084   **
94085   ** Meta values are as follows:
94086   **    meta[0]   Schema cookie.  Changes with each schema change.
94087   **    meta[1]   File format of schema layer.
94088   **    meta[2]   Size of the page cache.
94089   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
94090   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
94091   **    meta[5]   User version
94092   **    meta[6]   Incremental vacuum mode
94093   **    meta[7]   unused
94094   **    meta[8]   unused
94095   **    meta[9]   unused
94096   **
94097   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
94098   ** the possible values of meta[4].
94099   */
94100   for(i=0; i<ArraySize(meta); i++){
94101     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
94102   }
94103   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
94104
94105   /* If opening a non-empty database, check the text encoding. For the
94106   ** main database, set sqlite3.enc to the encoding of the main database.
94107   ** For an attached db, it is an error if the encoding is not the same
94108   ** as sqlite3.enc.
94109   */
94110   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
94111     if( iDb==0 ){
94112 #ifndef SQLITE_OMIT_UTF16
94113       u8 encoding;
94114       /* If opening the main database, set ENC(db). */
94115       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
94116       if( encoding==0 ) encoding = SQLITE_UTF8;
94117       ENC(db) = encoding;
94118 #else
94119       ENC(db) = SQLITE_UTF8;
94120 #endif
94121     }else{
94122       /* If opening an attached database, the encoding much match ENC(db) */
94123       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
94124         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
94125             " text encoding as main database");
94126         rc = SQLITE_ERROR;
94127         goto initone_error_out;
94128       }
94129     }
94130   }else{
94131     DbSetProperty(db, iDb, DB_Empty);
94132   }
94133   pDb->pSchema->enc = ENC(db);
94134
94135   if( pDb->pSchema->cache_size==0 ){
94136 #ifndef SQLITE_OMIT_DEPRECATED
94137     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
94138     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
94139     pDb->pSchema->cache_size = size;
94140 #else
94141     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
94142 #endif
94143     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
94144   }
94145
94146   /*
94147   ** file_format==1    Version 3.0.0.
94148   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
94149   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
94150   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
94151   */
94152   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
94153   if( pDb->pSchema->file_format==0 ){
94154     pDb->pSchema->file_format = 1;
94155   }
94156   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
94157     sqlite3SetString(pzErrMsg, db, "unsupported file format");
94158     rc = SQLITE_ERROR;
94159     goto initone_error_out;
94160   }
94161
94162   /* Ticket #2804:  When we open a database in the newer file format,
94163   ** clear the legacy_file_format pragma flag so that a VACUUM will
94164   ** not downgrade the database and thus invalidate any descending
94165   ** indices that the user might have created.
94166   */
94167   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
94168     db->flags &= ~SQLITE_LegacyFileFmt;
94169   }
94170
94171   /* Read the schema information out of the schema tables
94172   */
94173   assert( db->init.busy );
94174   {
94175     char *zSql;
94176     zSql = sqlite3MPrintf(db, 
94177         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
94178         db->aDb[iDb].zName, zMasterName);
94179 #ifndef SQLITE_OMIT_AUTHORIZATION
94180     {
94181       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
94182       xAuth = db->xAuth;
94183       db->xAuth = 0;
94184 #endif
94185       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
94186 #ifndef SQLITE_OMIT_AUTHORIZATION
94187       db->xAuth = xAuth;
94188     }
94189 #endif
94190     if( rc==SQLITE_OK ) rc = initData.rc;
94191     sqlite3DbFree(db, zSql);
94192 #ifndef SQLITE_OMIT_ANALYZE
94193     if( rc==SQLITE_OK ){
94194       sqlite3AnalysisLoad(db, iDb);
94195     }
94196 #endif
94197   }
94198   if( db->mallocFailed ){
94199     rc = SQLITE_NOMEM;
94200     sqlite3ResetAllSchemasOfConnection(db);
94201   }
94202   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
94203     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
94204     ** the schema loaded, even if errors occurred. In this situation the 
94205     ** current sqlite3_prepare() operation will fail, but the following one
94206     ** will attempt to compile the supplied statement against whatever subset
94207     ** of the schema was loaded before the error occurred. The primary
94208     ** purpose of this is to allow access to the sqlite_master table
94209     ** even when its contents have been corrupted.
94210     */
94211     DbSetProperty(db, iDb, DB_SchemaLoaded);
94212     rc = SQLITE_OK;
94213   }
94214
94215   /* Jump here for an error that occurs after successfully allocating
94216   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
94217   ** before that point, jump to error_out.
94218   */
94219 initone_error_out:
94220   if( openedTransaction ){
94221     sqlite3BtreeCommit(pDb->pBt);
94222   }
94223   sqlite3BtreeLeave(pDb->pBt);
94224
94225 error_out:
94226   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
94227     db->mallocFailed = 1;
94228   }
94229   return rc;
94230 }
94231
94232 /*
94233 ** Initialize all database files - the main database file, the file
94234 ** used to store temporary tables, and any additional database files
94235 ** created using ATTACH statements.  Return a success code.  If an
94236 ** error occurs, write an error message into *pzErrMsg.
94237 **
94238 ** After a database is initialized, the DB_SchemaLoaded bit is set
94239 ** bit is set in the flags field of the Db structure. If the database
94240 ** file was of zero-length, then the DB_Empty flag is also set.
94241 */
94242 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
94243   int i, rc;
94244   int commit_internal = !(db->flags&SQLITE_InternChanges);
94245   
94246   assert( sqlite3_mutex_held(db->mutex) );
94247   rc = SQLITE_OK;
94248   db->init.busy = 1;
94249   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
94250     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
94251     rc = sqlite3InitOne(db, i, pzErrMsg);
94252     if( rc ){
94253       sqlite3ResetOneSchema(db, i);
94254     }
94255   }
94256
94257   /* Once all the other databases have been initialized, load the schema
94258   ** for the TEMP database. This is loaded last, as the TEMP database
94259   ** schema may contain references to objects in other databases.
94260   */
94261 #ifndef SQLITE_OMIT_TEMPDB
94262   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
94263                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
94264     rc = sqlite3InitOne(db, 1, pzErrMsg);
94265     if( rc ){
94266       sqlite3ResetOneSchema(db, 1);
94267     }
94268   }
94269 #endif
94270
94271   db->init.busy = 0;
94272   if( rc==SQLITE_OK && commit_internal ){
94273     sqlite3CommitInternalChanges(db);
94274   }
94275
94276   return rc; 
94277 }
94278
94279 /*
94280 ** This routine is a no-op if the database schema is already initialized.
94281 ** Otherwise, the schema is loaded. An error code is returned.
94282 */
94283 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
94284   int rc = SQLITE_OK;
94285   sqlite3 *db = pParse->db;
94286   assert( sqlite3_mutex_held(db->mutex) );
94287   if( !db->init.busy ){
94288     rc = sqlite3Init(db, &pParse->zErrMsg);
94289   }
94290   if( rc!=SQLITE_OK ){
94291     pParse->rc = rc;
94292     pParse->nErr++;
94293   }
94294   return rc;
94295 }
94296
94297
94298 /*
94299 ** Check schema cookies in all databases.  If any cookie is out
94300 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
94301 ** make no changes to pParse->rc.
94302 */
94303 static void schemaIsValid(Parse *pParse){
94304   sqlite3 *db = pParse->db;
94305   int iDb;
94306   int rc;
94307   int cookie;
94308
94309   assert( pParse->checkSchema );
94310   assert( sqlite3_mutex_held(db->mutex) );
94311   for(iDb=0; iDb<db->nDb; iDb++){
94312     int openedTransaction = 0;         /* True if a transaction is opened */
94313     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
94314     if( pBt==0 ) continue;
94315
94316     /* If there is not already a read-only (or read-write) transaction opened
94317     ** on the b-tree database, open one now. If a transaction is opened, it 
94318     ** will be closed immediately after reading the meta-value. */
94319     if( !sqlite3BtreeIsInReadTrans(pBt) ){
94320       rc = sqlite3BtreeBeginTrans(pBt, 0);
94321       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
94322         db->mallocFailed = 1;
94323       }
94324       if( rc!=SQLITE_OK ) return;
94325       openedTransaction = 1;
94326     }
94327
94328     /* Read the schema cookie from the database. If it does not match the 
94329     ** value stored as part of the in-memory schema representation,
94330     ** set Parse.rc to SQLITE_SCHEMA. */
94331     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
94332     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94333     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
94334       sqlite3ResetOneSchema(db, iDb);
94335       pParse->rc = SQLITE_SCHEMA;
94336     }
94337
94338     /* Close the transaction, if one was opened. */
94339     if( openedTransaction ){
94340       sqlite3BtreeCommit(pBt);
94341     }
94342   }
94343 }
94344
94345 /*
94346 ** Convert a schema pointer into the iDb index that indicates
94347 ** which database file in db->aDb[] the schema refers to.
94348 **
94349 ** If the same database is attached more than once, the first
94350 ** attached database is returned.
94351 */
94352 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
94353   int i = -1000000;
94354
94355   /* If pSchema is NULL, then return -1000000. This happens when code in 
94356   ** expr.c is trying to resolve a reference to a transient table (i.e. one
94357   ** created by a sub-select). In this case the return value of this 
94358   ** function should never be used.
94359   **
94360   ** We return -1000000 instead of the more usual -1 simply because using
94361   ** -1000000 as the incorrect index into db->aDb[] is much 
94362   ** more likely to cause a segfault than -1 (of course there are assert()
94363   ** statements too, but it never hurts to play the odds).
94364   */
94365   assert( sqlite3_mutex_held(db->mutex) );
94366   if( pSchema ){
94367     for(i=0; ALWAYS(i<db->nDb); i++){
94368       if( db->aDb[i].pSchema==pSchema ){
94369         break;
94370       }
94371     }
94372     assert( i>=0 && i<db->nDb );
94373   }
94374   return i;
94375 }
94376
94377 /*
94378 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
94379 */
94380 static int sqlite3Prepare(
94381   sqlite3 *db,              /* Database handle. */
94382   const char *zSql,         /* UTF-8 encoded SQL statement. */
94383   int nBytes,               /* Length of zSql in bytes. */
94384   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
94385   Vdbe *pReprepare,         /* VM being reprepared */
94386   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94387   const char **pzTail       /* OUT: End of parsed string */
94388 ){
94389   Parse *pParse;            /* Parsing context */
94390   char *zErrMsg = 0;        /* Error message */
94391   int rc = SQLITE_OK;       /* Result code */
94392   int i;                    /* Loop counter */
94393
94394   /* Allocate the parsing context */
94395   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
94396   if( pParse==0 ){
94397     rc = SQLITE_NOMEM;
94398     goto end_prepare;
94399   }
94400   pParse->pReprepare = pReprepare;
94401   assert( ppStmt && *ppStmt==0 );
94402   assert( !db->mallocFailed );
94403   assert( sqlite3_mutex_held(db->mutex) );
94404
94405   /* Check to verify that it is possible to get a read lock on all
94406   ** database schemas.  The inability to get a read lock indicates that
94407   ** some other database connection is holding a write-lock, which in
94408   ** turn means that the other connection has made uncommitted changes
94409   ** to the schema.
94410   **
94411   ** Were we to proceed and prepare the statement against the uncommitted
94412   ** schema changes and if those schema changes are subsequently rolled
94413   ** back and different changes are made in their place, then when this
94414   ** prepared statement goes to run the schema cookie would fail to detect
94415   ** the schema change.  Disaster would follow.
94416   **
94417   ** This thread is currently holding mutexes on all Btrees (because
94418   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
94419   ** is not possible for another thread to start a new schema change
94420   ** while this routine is running.  Hence, we do not need to hold 
94421   ** locks on the schema, we just need to make sure nobody else is 
94422   ** holding them.
94423   **
94424   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
94425   ** but it does *not* override schema lock detection, so this all still
94426   ** works even if READ_UNCOMMITTED is set.
94427   */
94428   for(i=0; i<db->nDb; i++) {
94429     Btree *pBt = db->aDb[i].pBt;
94430     if( pBt ){
94431       assert( sqlite3BtreeHoldsMutex(pBt) );
94432       rc = sqlite3BtreeSchemaLocked(pBt);
94433       if( rc ){
94434         const char *zDb = db->aDb[i].zName;
94435         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
94436         testcase( db->flags & SQLITE_ReadUncommitted );
94437         goto end_prepare;
94438       }
94439     }
94440   }
94441
94442   sqlite3VtabUnlockList(db);
94443
94444   pParse->db = db;
94445   pParse->nQueryLoop = (double)1;
94446   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
94447     char *zSqlCopy;
94448     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
94449     testcase( nBytes==mxLen );
94450     testcase( nBytes==mxLen+1 );
94451     if( nBytes>mxLen ){
94452       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
94453       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
94454       goto end_prepare;
94455     }
94456     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
94457     if( zSqlCopy ){
94458       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
94459       sqlite3DbFree(db, zSqlCopy);
94460       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
94461     }else{
94462       pParse->zTail = &zSql[nBytes];
94463     }
94464   }else{
94465     sqlite3RunParser(pParse, zSql, &zErrMsg);
94466   }
94467   assert( 1==(int)pParse->nQueryLoop );
94468
94469   if( db->mallocFailed ){
94470     pParse->rc = SQLITE_NOMEM;
94471   }
94472   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
94473   if( pParse->checkSchema ){
94474     schemaIsValid(pParse);
94475   }
94476   if( db->mallocFailed ){
94477     pParse->rc = SQLITE_NOMEM;
94478   }
94479   if( pzTail ){
94480     *pzTail = pParse->zTail;
94481   }
94482   rc = pParse->rc;
94483
94484 #ifndef SQLITE_OMIT_EXPLAIN
94485   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
94486     static const char * const azColName[] = {
94487        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
94488        "selectid", "order", "from", "detail"
94489     };
94490     int iFirst, mx;
94491     if( pParse->explain==2 ){
94492       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
94493       iFirst = 8;
94494       mx = 12;
94495     }else{
94496       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
94497       iFirst = 0;
94498       mx = 8;
94499     }
94500     for(i=iFirst; i<mx; i++){
94501       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
94502                             azColName[i], SQLITE_STATIC);
94503     }
94504   }
94505 #endif
94506
94507   assert( db->init.busy==0 || saveSqlFlag==0 );
94508   if( db->init.busy==0 ){
94509     Vdbe *pVdbe = pParse->pVdbe;
94510     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
94511   }
94512   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
94513     sqlite3VdbeFinalize(pParse->pVdbe);
94514     assert(!(*ppStmt));
94515   }else{
94516     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
94517   }
94518
94519   if( zErrMsg ){
94520     sqlite3Error(db, rc, "%s", zErrMsg);
94521     sqlite3DbFree(db, zErrMsg);
94522   }else{
94523     sqlite3Error(db, rc, 0);
94524   }
94525
94526   /* Delete any TriggerPrg structures allocated while parsing this statement. */
94527   while( pParse->pTriggerPrg ){
94528     TriggerPrg *pT = pParse->pTriggerPrg;
94529     pParse->pTriggerPrg = pT->pNext;
94530     sqlite3DbFree(db, pT);
94531   }
94532
94533 end_prepare:
94534
94535   sqlite3StackFree(db, pParse);
94536   rc = sqlite3ApiExit(db, rc);
94537   assert( (rc&db->errMask)==rc );
94538   return rc;
94539 }
94540 static int sqlite3LockAndPrepare(
94541   sqlite3 *db,              /* Database handle. */
94542   const char *zSql,         /* UTF-8 encoded SQL statement. */
94543   int nBytes,               /* Length of zSql in bytes. */
94544   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
94545   Vdbe *pOld,               /* VM being reprepared */
94546   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94547   const char **pzTail       /* OUT: End of parsed string */
94548 ){
94549   int rc;
94550   assert( ppStmt!=0 );
94551   *ppStmt = 0;
94552   if( !sqlite3SafetyCheckOk(db) ){
94553     return SQLITE_MISUSE_BKPT;
94554   }
94555   sqlite3_mutex_enter(db->mutex);
94556   sqlite3BtreeEnterAll(db);
94557   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
94558   if( rc==SQLITE_SCHEMA ){
94559     sqlite3_finalize(*ppStmt);
94560     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
94561   }
94562   sqlite3BtreeLeaveAll(db);
94563   sqlite3_mutex_leave(db->mutex);
94564   assert( rc==SQLITE_OK || *ppStmt==0 );
94565   return rc;
94566 }
94567
94568 /*
94569 ** Rerun the compilation of a statement after a schema change.
94570 **
94571 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
94572 ** if the statement cannot be recompiled because another connection has
94573 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
94574 ** occurs, return SQLITE_SCHEMA.
94575 */
94576 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
94577   int rc;
94578   sqlite3_stmt *pNew;
94579   const char *zSql;
94580   sqlite3 *db;
94581
94582   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
94583   zSql = sqlite3_sql((sqlite3_stmt *)p);
94584   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
94585   db = sqlite3VdbeDb(p);
94586   assert( sqlite3_mutex_held(db->mutex) );
94587   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
94588   if( rc ){
94589     if( rc==SQLITE_NOMEM ){
94590       db->mallocFailed = 1;
94591     }
94592     assert( pNew==0 );
94593     return rc;
94594   }else{
94595     assert( pNew!=0 );
94596   }
94597   sqlite3VdbeSwap((Vdbe*)pNew, p);
94598   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
94599   sqlite3VdbeResetStepResult((Vdbe*)pNew);
94600   sqlite3VdbeFinalize((Vdbe*)pNew);
94601   return SQLITE_OK;
94602 }
94603
94604
94605 /*
94606 ** Two versions of the official API.  Legacy and new use.  In the legacy
94607 ** version, the original SQL text is not saved in the prepared statement
94608 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
94609 ** sqlite3_step().  In the new version, the original SQL text is retained
94610 ** and the statement is automatically recompiled if an schema change
94611 ** occurs.
94612 */
94613 SQLITE_API int sqlite3_prepare(
94614   sqlite3 *db,              /* Database handle. */
94615   const char *zSql,         /* UTF-8 encoded SQL statement. */
94616   int nBytes,               /* Length of zSql in bytes. */
94617   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94618   const char **pzTail       /* OUT: End of parsed string */
94619 ){
94620   int rc;
94621   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
94622   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94623   return rc;
94624 }
94625 SQLITE_API int sqlite3_prepare_v2(
94626   sqlite3 *db,              /* Database handle. */
94627   const char *zSql,         /* UTF-8 encoded SQL statement. */
94628   int nBytes,               /* Length of zSql in bytes. */
94629   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94630   const char **pzTail       /* OUT: End of parsed string */
94631 ){
94632   int rc;
94633   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
94634   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94635   return rc;
94636 }
94637
94638
94639 #ifndef SQLITE_OMIT_UTF16
94640 /*
94641 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
94642 */
94643 static int sqlite3Prepare16(
94644   sqlite3 *db,              /* Database handle. */ 
94645   const void *zSql,         /* UTF-16 encoded SQL statement. */
94646   int nBytes,               /* Length of zSql in bytes. */
94647   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
94648   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94649   const void **pzTail       /* OUT: End of parsed string */
94650 ){
94651   /* This function currently works by first transforming the UTF-16
94652   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
94653   ** tricky bit is figuring out the pointer to return in *pzTail.
94654   */
94655   char *zSql8;
94656   const char *zTail8 = 0;
94657   int rc = SQLITE_OK;
94658
94659   assert( ppStmt );
94660   *ppStmt = 0;
94661   if( !sqlite3SafetyCheckOk(db) ){
94662     return SQLITE_MISUSE_BKPT;
94663   }
94664   sqlite3_mutex_enter(db->mutex);
94665   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
94666   if( zSql8 ){
94667     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
94668   }
94669
94670   if( zTail8 && pzTail ){
94671     /* If sqlite3_prepare returns a tail pointer, we calculate the
94672     ** equivalent pointer into the UTF-16 string by counting the unicode
94673     ** characters between zSql8 and zTail8, and then returning a pointer
94674     ** the same number of characters into the UTF-16 string.
94675     */
94676     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
94677     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
94678   }
94679   sqlite3DbFree(db, zSql8); 
94680   rc = sqlite3ApiExit(db, rc);
94681   sqlite3_mutex_leave(db->mutex);
94682   return rc;
94683 }
94684
94685 /*
94686 ** Two versions of the official API.  Legacy and new use.  In the legacy
94687 ** version, the original SQL text is not saved in the prepared statement
94688 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
94689 ** sqlite3_step().  In the new version, the original SQL text is retained
94690 ** and the statement is automatically recompiled if an schema change
94691 ** occurs.
94692 */
94693 SQLITE_API int sqlite3_prepare16(
94694   sqlite3 *db,              /* Database handle. */ 
94695   const void *zSql,         /* UTF-16 encoded SQL statement. */
94696   int nBytes,               /* Length of zSql in bytes. */
94697   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94698   const void **pzTail       /* OUT: End of parsed string */
94699 ){
94700   int rc;
94701   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
94702   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94703   return rc;
94704 }
94705 SQLITE_API int sqlite3_prepare16_v2(
94706   sqlite3 *db,              /* Database handle. */ 
94707   const void *zSql,         /* UTF-16 encoded SQL statement. */
94708   int nBytes,               /* Length of zSql in bytes. */
94709   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94710   const void **pzTail       /* OUT: End of parsed string */
94711 ){
94712   int rc;
94713   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
94714   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94715   return rc;
94716 }
94717
94718 #endif /* SQLITE_OMIT_UTF16 */
94719
94720 /************** End of prepare.c *********************************************/
94721 /************** Begin file select.c ******************************************/
94722 /*
94723 ** 2001 September 15
94724 **
94725 ** The author disclaims copyright to this source code.  In place of
94726 ** a legal notice, here is a blessing:
94727 **
94728 **    May you do good and not evil.
94729 **    May you find forgiveness for yourself and forgive others.
94730 **    May you share freely, never taking more than you give.
94731 **
94732 *************************************************************************
94733 ** This file contains C code routines that are called by the parser
94734 ** to handle SELECT statements in SQLite.
94735 */
94736
94737
94738 /*
94739 ** Delete all the content of a Select structure but do not deallocate
94740 ** the select structure itself.
94741 */
94742 static void clearSelect(sqlite3 *db, Select *p){
94743   sqlite3ExprListDelete(db, p->pEList);
94744   sqlite3SrcListDelete(db, p->pSrc);
94745   sqlite3ExprDelete(db, p->pWhere);
94746   sqlite3ExprListDelete(db, p->pGroupBy);
94747   sqlite3ExprDelete(db, p->pHaving);
94748   sqlite3ExprListDelete(db, p->pOrderBy);
94749   sqlite3SelectDelete(db, p->pPrior);
94750   sqlite3ExprDelete(db, p->pLimit);
94751   sqlite3ExprDelete(db, p->pOffset);
94752 }
94753
94754 /*
94755 ** Initialize a SelectDest structure.
94756 */
94757 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
94758   pDest->eDest = (u8)eDest;
94759   pDest->iSDParm = iParm;
94760   pDest->affSdst = 0;
94761   pDest->iSdst = 0;
94762   pDest->nSdst = 0;
94763 }
94764
94765
94766 /*
94767 ** Allocate a new Select structure and return a pointer to that
94768 ** structure.
94769 */
94770 SQLITE_PRIVATE Select *sqlite3SelectNew(
94771   Parse *pParse,        /* Parsing context */
94772   ExprList *pEList,     /* which columns to include in the result */
94773   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
94774   Expr *pWhere,         /* the WHERE clause */
94775   ExprList *pGroupBy,   /* the GROUP BY clause */
94776   Expr *pHaving,        /* the HAVING clause */
94777   ExprList *pOrderBy,   /* the ORDER BY clause */
94778   u16 selFlags,         /* Flag parameters, such as SF_Distinct */
94779   Expr *pLimit,         /* LIMIT value.  NULL means not used */
94780   Expr *pOffset         /* OFFSET value.  NULL means no offset */
94781 ){
94782   Select *pNew;
94783   Select standin;
94784   sqlite3 *db = pParse->db;
94785   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
94786   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
94787   if( pNew==0 ){
94788     assert( db->mallocFailed );
94789     pNew = &standin;
94790     memset(pNew, 0, sizeof(*pNew));
94791   }
94792   if( pEList==0 ){
94793     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
94794   }
94795   pNew->pEList = pEList;
94796   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
94797   pNew->pSrc = pSrc;
94798   pNew->pWhere = pWhere;
94799   pNew->pGroupBy = pGroupBy;
94800   pNew->pHaving = pHaving;
94801   pNew->pOrderBy = pOrderBy;
94802   pNew->selFlags = selFlags;
94803   pNew->op = TK_SELECT;
94804   pNew->pLimit = pLimit;
94805   pNew->pOffset = pOffset;
94806   assert( pOffset==0 || pLimit!=0 );
94807   pNew->addrOpenEphm[0] = -1;
94808   pNew->addrOpenEphm[1] = -1;
94809   pNew->addrOpenEphm[2] = -1;
94810   if( db->mallocFailed ) {
94811     clearSelect(db, pNew);
94812     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
94813     pNew = 0;
94814   }else{
94815     assert( pNew->pSrc!=0 || pParse->nErr>0 );
94816   }
94817   assert( pNew!=&standin );
94818   return pNew;
94819 }
94820
94821 /*
94822 ** Delete the given Select structure and all of its substructures.
94823 */
94824 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
94825   if( p ){
94826     clearSelect(db, p);
94827     sqlite3DbFree(db, p);
94828   }
94829 }
94830
94831 /*
94832 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
94833 ** type of join.  Return an integer constant that expresses that type
94834 ** in terms of the following bit values:
94835 **
94836 **     JT_INNER
94837 **     JT_CROSS
94838 **     JT_OUTER
94839 **     JT_NATURAL
94840 **     JT_LEFT
94841 **     JT_RIGHT
94842 **
94843 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
94844 **
94845 ** If an illegal or unsupported join type is seen, then still return
94846 ** a join type, but put an error in the pParse structure.
94847 */
94848 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
94849   int jointype = 0;
94850   Token *apAll[3];
94851   Token *p;
94852                              /*   0123456789 123456789 123456789 123 */
94853   static const char zKeyText[] = "naturaleftouterightfullinnercross";
94854   static const struct {
94855     u8 i;        /* Beginning of keyword text in zKeyText[] */
94856     u8 nChar;    /* Length of the keyword in characters */
94857     u8 code;     /* Join type mask */
94858   } aKeyword[] = {
94859     /* natural */ { 0,  7, JT_NATURAL                },
94860     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
94861     /* outer   */ { 10, 5, JT_OUTER                  },
94862     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
94863     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
94864     /* inner   */ { 23, 5, JT_INNER                  },
94865     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
94866   };
94867   int i, j;
94868   apAll[0] = pA;
94869   apAll[1] = pB;
94870   apAll[2] = pC;
94871   for(i=0; i<3 && apAll[i]; i++){
94872     p = apAll[i];
94873     for(j=0; j<ArraySize(aKeyword); j++){
94874       if( p->n==aKeyword[j].nChar 
94875           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
94876         jointype |= aKeyword[j].code;
94877         break;
94878       }
94879     }
94880     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
94881     if( j>=ArraySize(aKeyword) ){
94882       jointype |= JT_ERROR;
94883       break;
94884     }
94885   }
94886   if(
94887      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
94888      (jointype & JT_ERROR)!=0
94889   ){
94890     const char *zSp = " ";
94891     assert( pB!=0 );
94892     if( pC==0 ){ zSp++; }
94893     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
94894        "%T %T%s%T", pA, pB, zSp, pC);
94895     jointype = JT_INNER;
94896   }else if( (jointype & JT_OUTER)!=0 
94897          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
94898     sqlite3ErrorMsg(pParse, 
94899       "RIGHT and FULL OUTER JOINs are not currently supported");
94900     jointype = JT_INNER;
94901   }
94902   return jointype;
94903 }
94904
94905 /*
94906 ** Return the index of a column in a table.  Return -1 if the column
94907 ** is not contained in the table.
94908 */
94909 static int columnIndex(Table *pTab, const char *zCol){
94910   int i;
94911   for(i=0; i<pTab->nCol; i++){
94912     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
94913   }
94914   return -1;
94915 }
94916
94917 /*
94918 ** Search the first N tables in pSrc, from left to right, looking for a
94919 ** table that has a column named zCol.  
94920 **
94921 ** When found, set *piTab and *piCol to the table index and column index
94922 ** of the matching column and return TRUE.
94923 **
94924 ** If not found, return FALSE.
94925 */
94926 static int tableAndColumnIndex(
94927   SrcList *pSrc,       /* Array of tables to search */
94928   int N,               /* Number of tables in pSrc->a[] to search */
94929   const char *zCol,    /* Name of the column we are looking for */
94930   int *piTab,          /* Write index of pSrc->a[] here */
94931   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
94932 ){
94933   int i;               /* For looping over tables in pSrc */
94934   int iCol;            /* Index of column matching zCol */
94935
94936   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
94937   for(i=0; i<N; i++){
94938     iCol = columnIndex(pSrc->a[i].pTab, zCol);
94939     if( iCol>=0 ){
94940       if( piTab ){
94941         *piTab = i;
94942         *piCol = iCol;
94943       }
94944       return 1;
94945     }
94946   }
94947   return 0;
94948 }
94949
94950 /*
94951 ** This function is used to add terms implied by JOIN syntax to the
94952 ** WHERE clause expression of a SELECT statement. The new term, which
94953 ** is ANDed with the existing WHERE clause, is of the form:
94954 **
94955 **    (tab1.col1 = tab2.col2)
94956 **
94957 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
94958 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
94959 ** column iColRight of tab2.
94960 */
94961 static void addWhereTerm(
94962   Parse *pParse,                  /* Parsing context */
94963   SrcList *pSrc,                  /* List of tables in FROM clause */
94964   int iLeft,                      /* Index of first table to join in pSrc */
94965   int iColLeft,                   /* Index of column in first table */
94966   int iRight,                     /* Index of second table in pSrc */
94967   int iColRight,                  /* Index of column in second table */
94968   int isOuterJoin,                /* True if this is an OUTER join */
94969   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
94970 ){
94971   sqlite3 *db = pParse->db;
94972   Expr *pE1;
94973   Expr *pE2;
94974   Expr *pEq;
94975
94976   assert( iLeft<iRight );
94977   assert( pSrc->nSrc>iRight );
94978   assert( pSrc->a[iLeft].pTab );
94979   assert( pSrc->a[iRight].pTab );
94980
94981   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
94982   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
94983
94984   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
94985   if( pEq && isOuterJoin ){
94986     ExprSetProperty(pEq, EP_FromJoin);
94987     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
94988     ExprSetIrreducible(pEq);
94989     pEq->iRightJoinTable = (i16)pE2->iTable;
94990   }
94991   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
94992 }
94993
94994 /*
94995 ** Set the EP_FromJoin property on all terms of the given expression.
94996 ** And set the Expr.iRightJoinTable to iTable for every term in the
94997 ** expression.
94998 **
94999 ** The EP_FromJoin property is used on terms of an expression to tell
95000 ** the LEFT OUTER JOIN processing logic that this term is part of the
95001 ** join restriction specified in the ON or USING clause and not a part
95002 ** of the more general WHERE clause.  These terms are moved over to the
95003 ** WHERE clause during join processing but we need to remember that they
95004 ** originated in the ON or USING clause.
95005 **
95006 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
95007 ** expression depends on table iRightJoinTable even if that table is not
95008 ** explicitly mentioned in the expression.  That information is needed
95009 ** for cases like this:
95010 **
95011 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
95012 **
95013 ** The where clause needs to defer the handling of the t1.x=5
95014 ** term until after the t2 loop of the join.  In that way, a
95015 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
95016 ** defer the handling of t1.x=5, it will be processed immediately
95017 ** after the t1 loop and rows with t1.x!=5 will never appear in
95018 ** the output, which is incorrect.
95019 */
95020 static void setJoinExpr(Expr *p, int iTable){
95021   while( p ){
95022     ExprSetProperty(p, EP_FromJoin);
95023     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
95024     ExprSetIrreducible(p);
95025     p->iRightJoinTable = (i16)iTable;
95026     setJoinExpr(p->pLeft, iTable);
95027     p = p->pRight;
95028   } 
95029 }
95030
95031 /*
95032 ** This routine processes the join information for a SELECT statement.
95033 ** ON and USING clauses are converted into extra terms of the WHERE clause.
95034 ** NATURAL joins also create extra WHERE clause terms.
95035 **
95036 ** The terms of a FROM clause are contained in the Select.pSrc structure.
95037 ** The left most table is the first entry in Select.pSrc.  The right-most
95038 ** table is the last entry.  The join operator is held in the entry to
95039 ** the left.  Thus entry 0 contains the join operator for the join between
95040 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
95041 ** also attached to the left entry.
95042 **
95043 ** This routine returns the number of errors encountered.
95044 */
95045 static int sqliteProcessJoin(Parse *pParse, Select *p){
95046   SrcList *pSrc;                  /* All tables in the FROM clause */
95047   int i, j;                       /* Loop counters */
95048   struct SrcList_item *pLeft;     /* Left table being joined */
95049   struct SrcList_item *pRight;    /* Right table being joined */
95050
95051   pSrc = p->pSrc;
95052   pLeft = &pSrc->a[0];
95053   pRight = &pLeft[1];
95054   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
95055     Table *pLeftTab = pLeft->pTab;
95056     Table *pRightTab = pRight->pTab;
95057     int isOuter;
95058
95059     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
95060     isOuter = (pRight->jointype & JT_OUTER)!=0;
95061
95062     /* When the NATURAL keyword is present, add WHERE clause terms for
95063     ** every column that the two tables have in common.
95064     */
95065     if( pRight->jointype & JT_NATURAL ){
95066       if( pRight->pOn || pRight->pUsing ){
95067         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
95068            "an ON or USING clause", 0);
95069         return 1;
95070       }
95071       for(j=0; j<pRightTab->nCol; j++){
95072         char *zName;   /* Name of column in the right table */
95073         int iLeft;     /* Matching left table */
95074         int iLeftCol;  /* Matching column in the left table */
95075
95076         zName = pRightTab->aCol[j].zName;
95077         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
95078           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
95079                        isOuter, &p->pWhere);
95080         }
95081       }
95082     }
95083
95084     /* Disallow both ON and USING clauses in the same join
95085     */
95086     if( pRight->pOn && pRight->pUsing ){
95087       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
95088         "clauses in the same join");
95089       return 1;
95090     }
95091
95092     /* Add the ON clause to the end of the WHERE clause, connected by
95093     ** an AND operator.
95094     */
95095     if( pRight->pOn ){
95096       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
95097       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
95098       pRight->pOn = 0;
95099     }
95100
95101     /* Create extra terms on the WHERE clause for each column named
95102     ** in the USING clause.  Example: If the two tables to be joined are 
95103     ** A and B and the USING clause names X, Y, and Z, then add this
95104     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
95105     ** Report an error if any column mentioned in the USING clause is
95106     ** not contained in both tables to be joined.
95107     */
95108     if( pRight->pUsing ){
95109       IdList *pList = pRight->pUsing;
95110       for(j=0; j<pList->nId; j++){
95111         char *zName;     /* Name of the term in the USING clause */
95112         int iLeft;       /* Table on the left with matching column name */
95113         int iLeftCol;    /* Column number of matching column on the left */
95114         int iRightCol;   /* Column number of matching column on the right */
95115
95116         zName = pList->a[j].zName;
95117         iRightCol = columnIndex(pRightTab, zName);
95118         if( iRightCol<0
95119          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
95120         ){
95121           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
95122             "not present in both tables", zName);
95123           return 1;
95124         }
95125         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
95126                      isOuter, &p->pWhere);
95127       }
95128     }
95129   }
95130   return 0;
95131 }
95132
95133 /*
95134 ** Insert code into "v" that will push the record on the top of the
95135 ** stack into the sorter.
95136 */
95137 static void pushOntoSorter(
95138   Parse *pParse,         /* Parser context */
95139   ExprList *pOrderBy,    /* The ORDER BY clause */
95140   Select *pSelect,       /* The whole SELECT statement */
95141   int regData            /* Register holding data to be sorted */
95142 ){
95143   Vdbe *v = pParse->pVdbe;
95144   int nExpr = pOrderBy->nExpr;
95145   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
95146   int regRecord = sqlite3GetTempReg(pParse);
95147   int op;
95148   sqlite3ExprCacheClear(pParse);
95149   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
95150   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
95151   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
95152   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
95153   if( pSelect->selFlags & SF_UseSorter ){
95154     op = OP_SorterInsert;
95155   }else{
95156     op = OP_IdxInsert;
95157   }
95158   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
95159   sqlite3ReleaseTempReg(pParse, regRecord);
95160   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
95161   if( pSelect->iLimit ){
95162     int addr1, addr2;
95163     int iLimit;
95164     if( pSelect->iOffset ){
95165       iLimit = pSelect->iOffset+1;
95166     }else{
95167       iLimit = pSelect->iLimit;
95168     }
95169     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
95170     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
95171     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
95172     sqlite3VdbeJumpHere(v, addr1);
95173     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
95174     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
95175     sqlite3VdbeJumpHere(v, addr2);
95176   }
95177 }
95178
95179 /*
95180 ** Add code to implement the OFFSET
95181 */
95182 static void codeOffset(
95183   Vdbe *v,          /* Generate code into this VM */
95184   Select *p,        /* The SELECT statement being coded */
95185   int iContinue     /* Jump here to skip the current record */
95186 ){
95187   if( p->iOffset && iContinue!=0 ){
95188     int addr;
95189     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
95190     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
95191     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
95192     VdbeComment((v, "skip OFFSET records"));
95193     sqlite3VdbeJumpHere(v, addr);
95194   }
95195 }
95196
95197 /*
95198 ** Add code that will check to make sure the N registers starting at iMem
95199 ** form a distinct entry.  iTab is a sorting index that holds previously
95200 ** seen combinations of the N values.  A new entry is made in iTab
95201 ** if the current N values are new.
95202 **
95203 ** A jump to addrRepeat is made and the N+1 values are popped from the
95204 ** stack if the top N elements are not distinct.
95205 */
95206 static void codeDistinct(
95207   Parse *pParse,     /* Parsing and code generating context */
95208   int iTab,          /* A sorting index used to test for distinctness */
95209   int addrRepeat,    /* Jump to here if not distinct */
95210   int N,             /* Number of elements */
95211   int iMem           /* First element */
95212 ){
95213   Vdbe *v;
95214   int r1;
95215
95216   v = pParse->pVdbe;
95217   r1 = sqlite3GetTempReg(pParse);
95218   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
95219   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
95220   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
95221   sqlite3ReleaseTempReg(pParse, r1);
95222 }
95223
95224 #ifndef SQLITE_OMIT_SUBQUERY
95225 /*
95226 ** Generate an error message when a SELECT is used within a subexpression
95227 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
95228 ** column.  We do this in a subroutine because the error used to occur
95229 ** in multiple places.  (The error only occurs in one place now, but we
95230 ** retain the subroutine to minimize code disruption.)
95231 */
95232 static int checkForMultiColumnSelectError(
95233   Parse *pParse,       /* Parse context. */
95234   SelectDest *pDest,   /* Destination of SELECT results */
95235   int nExpr            /* Number of result columns returned by SELECT */
95236 ){
95237   int eDest = pDest->eDest;
95238   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
95239     sqlite3ErrorMsg(pParse, "only a single result allowed for "
95240        "a SELECT that is part of an expression");
95241     return 1;
95242   }else{
95243     return 0;
95244   }
95245 }
95246 #endif
95247
95248 /*
95249 ** An instance of the following object is used to record information about
95250 ** how to process the DISTINCT keyword, to simplify passing that information
95251 ** into the selectInnerLoop() routine.
95252 */
95253 typedef struct DistinctCtx DistinctCtx;
95254 struct DistinctCtx {
95255   u8 isTnct;      /* True if the DISTINCT keyword is present */
95256   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
95257   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
95258   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
95259 };
95260
95261 /*
95262 ** This routine generates the code for the inside of the inner loop
95263 ** of a SELECT.
95264 **
95265 ** If srcTab and nColumn are both zero, then the pEList expressions
95266 ** are evaluated in order to get the data for this row.  If nColumn>0
95267 ** then data is pulled from srcTab and pEList is used only to get the
95268 ** datatypes for each column.
95269 */
95270 static void selectInnerLoop(
95271   Parse *pParse,          /* The parser context */
95272   Select *p,              /* The complete select statement being coded */
95273   ExprList *pEList,       /* List of values being extracted */
95274   int srcTab,             /* Pull data from this table */
95275   int nColumn,            /* Number of columns in the source table */
95276   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
95277   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
95278   SelectDest *pDest,      /* How to dispose of the results */
95279   int iContinue,          /* Jump here to continue with next row */
95280   int iBreak              /* Jump here to break out of the inner loop */
95281 ){
95282   Vdbe *v = pParse->pVdbe;
95283   int i;
95284   int hasDistinct;        /* True if the DISTINCT keyword is present */
95285   int regResult;              /* Start of memory holding result set */
95286   int eDest = pDest->eDest;   /* How to dispose of results */
95287   int iParm = pDest->iSDParm; /* First argument to disposal method */
95288   int nResultCol;             /* Number of result columns */
95289
95290   assert( v );
95291   if( NEVER(v==0) ) return;
95292   assert( pEList!=0 );
95293   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
95294   if( pOrderBy==0 && !hasDistinct ){
95295     codeOffset(v, p, iContinue);
95296   }
95297
95298   /* Pull the requested columns.
95299   */
95300   if( nColumn>0 ){
95301     nResultCol = nColumn;
95302   }else{
95303     nResultCol = pEList->nExpr;
95304   }
95305   if( pDest->iSdst==0 ){
95306     pDest->iSdst = pParse->nMem+1;
95307     pDest->nSdst = nResultCol;
95308     pParse->nMem += nResultCol;
95309   }else{ 
95310     assert( pDest->nSdst==nResultCol );
95311   }
95312   regResult = pDest->iSdst;
95313   if( nColumn>0 ){
95314     for(i=0; i<nColumn; i++){
95315       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
95316     }
95317   }else if( eDest!=SRT_Exists ){
95318     /* If the destination is an EXISTS(...) expression, the actual
95319     ** values returned by the SELECT are not required.
95320     */
95321     sqlite3ExprCacheClear(pParse);
95322     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
95323   }
95324   nColumn = nResultCol;
95325
95326   /* If the DISTINCT keyword was present on the SELECT statement
95327   ** and this row has been seen before, then do not make this row
95328   ** part of the result.
95329   */
95330   if( hasDistinct ){
95331     assert( pEList!=0 );
95332     assert( pEList->nExpr==nColumn );
95333     switch( pDistinct->eTnctType ){
95334       case WHERE_DISTINCT_ORDERED: {
95335         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
95336         int iJump;              /* Jump destination */
95337         int regPrev;            /* Previous row content */
95338
95339         /* Allocate space for the previous row */
95340         regPrev = pParse->nMem+1;
95341         pParse->nMem += nColumn;
95342
95343         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
95344         ** sets the MEM_Cleared bit on the first register of the
95345         ** previous value.  This will cause the OP_Ne below to always
95346         ** fail on the first iteration of the loop even if the first
95347         ** row is all NULLs.
95348         */
95349         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
95350         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
95351         pOp->opcode = OP_Null;
95352         pOp->p1 = 1;
95353         pOp->p2 = regPrev;
95354
95355         iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
95356         for(i=0; i<nColumn; i++){
95357           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
95358           if( i<nColumn-1 ){
95359             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
95360           }else{
95361             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
95362           }
95363           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
95364           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
95365         }
95366         assert( sqlite3VdbeCurrentAddr(v)==iJump );
95367         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
95368         break;
95369       }
95370
95371       case WHERE_DISTINCT_UNIQUE: {
95372         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
95373         break;
95374       }
95375
95376       default: {
95377         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
95378         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
95379         break;
95380       }
95381     }
95382     if( pOrderBy==0 ){
95383       codeOffset(v, p, iContinue);
95384     }
95385   }
95386
95387   switch( eDest ){
95388     /* In this mode, write each query result to the key of the temporary
95389     ** table iParm.
95390     */
95391 #ifndef SQLITE_OMIT_COMPOUND_SELECT
95392     case SRT_Union: {
95393       int r1;
95394       r1 = sqlite3GetTempReg(pParse);
95395       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95396       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
95397       sqlite3ReleaseTempReg(pParse, r1);
95398       break;
95399     }
95400
95401     /* Construct a record from the query result, but instead of
95402     ** saving that record, use it as a key to delete elements from
95403     ** the temporary table iParm.
95404     */
95405     case SRT_Except: {
95406       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
95407       break;
95408     }
95409 #endif
95410
95411     /* Store the result as data using a unique key.
95412     */
95413     case SRT_Table:
95414     case SRT_EphemTab: {
95415       int r1 = sqlite3GetTempReg(pParse);
95416       testcase( eDest==SRT_Table );
95417       testcase( eDest==SRT_EphemTab );
95418       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95419       if( pOrderBy ){
95420         pushOntoSorter(pParse, pOrderBy, p, r1);
95421       }else{
95422         int r2 = sqlite3GetTempReg(pParse);
95423         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
95424         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
95425         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95426         sqlite3ReleaseTempReg(pParse, r2);
95427       }
95428       sqlite3ReleaseTempReg(pParse, r1);
95429       break;
95430     }
95431
95432 #ifndef SQLITE_OMIT_SUBQUERY
95433     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
95434     ** then there should be a single item on the stack.  Write this
95435     ** item into the set table with bogus data.
95436     */
95437     case SRT_Set: {
95438       assert( nColumn==1 );
95439       pDest->affSdst =
95440                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
95441       if( pOrderBy ){
95442         /* At first glance you would think we could optimize out the
95443         ** ORDER BY in this case since the order of entries in the set
95444         ** does not matter.  But there might be a LIMIT clause, in which
95445         ** case the order does matter */
95446         pushOntoSorter(pParse, pOrderBy, p, regResult);
95447       }else{
95448         int r1 = sqlite3GetTempReg(pParse);
95449         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
95450         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
95451         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
95452         sqlite3ReleaseTempReg(pParse, r1);
95453       }
95454       break;
95455     }
95456
95457     /* If any row exist in the result set, record that fact and abort.
95458     */
95459     case SRT_Exists: {
95460       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
95461       /* The LIMIT clause will terminate the loop for us */
95462       break;
95463     }
95464
95465     /* If this is a scalar select that is part of an expression, then
95466     ** store the results in the appropriate memory cell and break out
95467     ** of the scan loop.
95468     */
95469     case SRT_Mem: {
95470       assert( nColumn==1 );
95471       if( pOrderBy ){
95472         pushOntoSorter(pParse, pOrderBy, p, regResult);
95473       }else{
95474         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
95475         /* The LIMIT clause will jump out of the loop for us */
95476       }
95477       break;
95478     }
95479 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
95480
95481     /* Send the data to the callback function or to a subroutine.  In the
95482     ** case of a subroutine, the subroutine itself is responsible for
95483     ** popping the data from the stack.
95484     */
95485     case SRT_Coroutine:
95486     case SRT_Output: {
95487       testcase( eDest==SRT_Coroutine );
95488       testcase( eDest==SRT_Output );
95489       if( pOrderBy ){
95490         int r1 = sqlite3GetTempReg(pParse);
95491         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95492         pushOntoSorter(pParse, pOrderBy, p, r1);
95493         sqlite3ReleaseTempReg(pParse, r1);
95494       }else if( eDest==SRT_Coroutine ){
95495         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
95496       }else{
95497         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
95498         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
95499       }
95500       break;
95501     }
95502
95503 #if !defined(SQLITE_OMIT_TRIGGER)
95504     /* Discard the results.  This is used for SELECT statements inside
95505     ** the body of a TRIGGER.  The purpose of such selects is to call
95506     ** user-defined functions that have side effects.  We do not care
95507     ** about the actual results of the select.
95508     */
95509     default: {
95510       assert( eDest==SRT_Discard );
95511       break;
95512     }
95513 #endif
95514   }
95515
95516   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
95517   ** there is a sorter, in which case the sorter has already limited
95518   ** the output for us.
95519   */
95520   if( pOrderBy==0 && p->iLimit ){
95521     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
95522   }
95523 }
95524
95525 /*
95526 ** Given an expression list, generate a KeyInfo structure that records
95527 ** the collating sequence for each expression in that expression list.
95528 **
95529 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
95530 ** KeyInfo structure is appropriate for initializing a virtual index to
95531 ** implement that clause.  If the ExprList is the result set of a SELECT
95532 ** then the KeyInfo structure is appropriate for initializing a virtual
95533 ** index to implement a DISTINCT test.
95534 **
95535 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
95536 ** function is responsible for seeing that this structure is eventually
95537 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
95538 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
95539 */
95540 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
95541   sqlite3 *db = pParse->db;
95542   int nExpr;
95543   KeyInfo *pInfo;
95544   struct ExprList_item *pItem;
95545   int i;
95546
95547   nExpr = pList->nExpr;
95548   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
95549   if( pInfo ){
95550     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
95551     pInfo->nField = (u16)nExpr;
95552     pInfo->enc = ENC(db);
95553     pInfo->db = db;
95554     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
95555       CollSeq *pColl;
95556       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
95557       if( !pColl ){
95558         pColl = db->pDfltColl;
95559       }
95560       pInfo->aColl[i] = pColl;
95561       pInfo->aSortOrder[i] = pItem->sortOrder;
95562     }
95563   }
95564   return pInfo;
95565 }
95566
95567 #ifndef SQLITE_OMIT_COMPOUND_SELECT
95568 /*
95569 ** Name of the connection operator, used for error messages.
95570 */
95571 static const char *selectOpName(int id){
95572   char *z;
95573   switch( id ){
95574     case TK_ALL:       z = "UNION ALL";   break;
95575     case TK_INTERSECT: z = "INTERSECT";   break;
95576     case TK_EXCEPT:    z = "EXCEPT";      break;
95577     default:           z = "UNION";       break;
95578   }
95579   return z;
95580 }
95581 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
95582
95583 #ifndef SQLITE_OMIT_EXPLAIN
95584 /*
95585 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
95586 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
95587 ** where the caption is of the form:
95588 **
95589 **   "USE TEMP B-TREE FOR xxx"
95590 **
95591 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
95592 ** is determined by the zUsage argument.
95593 */
95594 static void explainTempTable(Parse *pParse, const char *zUsage){
95595   if( pParse->explain==2 ){
95596     Vdbe *v = pParse->pVdbe;
95597     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
95598     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
95599   }
95600 }
95601
95602 /*
95603 ** Assign expression b to lvalue a. A second, no-op, version of this macro
95604 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
95605 ** in sqlite3Select() to assign values to structure member variables that
95606 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
95607 ** code with #ifndef directives.
95608 */
95609 # define explainSetInteger(a, b) a = b
95610
95611 #else
95612 /* No-op versions of the explainXXX() functions and macros. */
95613 # define explainTempTable(y,z)
95614 # define explainSetInteger(y,z)
95615 #endif
95616
95617 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
95618 /*
95619 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
95620 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
95621 ** where the caption is of one of the two forms:
95622 **
95623 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
95624 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
95625 **
95626 ** where iSub1 and iSub2 are the integers passed as the corresponding
95627 ** function parameters, and op is the text representation of the parameter
95628 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
95629 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
95630 ** false, or the second form if it is true.
95631 */
95632 static void explainComposite(
95633   Parse *pParse,                  /* Parse context */
95634   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
95635   int iSub1,                      /* Subquery id 1 */
95636   int iSub2,                      /* Subquery id 2 */
95637   int bUseTmp                     /* True if a temp table was used */
95638 ){
95639   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
95640   if( pParse->explain==2 ){
95641     Vdbe *v = pParse->pVdbe;
95642     char *zMsg = sqlite3MPrintf(
95643         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
95644         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
95645     );
95646     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
95647   }
95648 }
95649 #else
95650 /* No-op versions of the explainXXX() functions and macros. */
95651 # define explainComposite(v,w,x,y,z)
95652 #endif
95653
95654 /*
95655 ** If the inner loop was generated using a non-null pOrderBy argument,
95656 ** then the results were placed in a sorter.  After the loop is terminated
95657 ** we need to run the sorter and output the results.  The following
95658 ** routine generates the code needed to do that.
95659 */
95660 static void generateSortTail(
95661   Parse *pParse,    /* Parsing context */
95662   Select *p,        /* The SELECT statement */
95663   Vdbe *v,          /* Generate code into this VDBE */
95664   int nColumn,      /* Number of columns of data */
95665   SelectDest *pDest /* Write the sorted results here */
95666 ){
95667   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
95668   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
95669   int addr;
95670   int iTab;
95671   int pseudoTab = 0;
95672   ExprList *pOrderBy = p->pOrderBy;
95673
95674   int eDest = pDest->eDest;
95675   int iParm = pDest->iSDParm;
95676
95677   int regRow;
95678   int regRowid;
95679
95680   iTab = pOrderBy->iECursor;
95681   regRow = sqlite3GetTempReg(pParse);
95682   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95683     pseudoTab = pParse->nTab++;
95684     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
95685     regRowid = 0;
95686   }else{
95687     regRowid = sqlite3GetTempReg(pParse);
95688   }
95689   if( p->selFlags & SF_UseSorter ){
95690     int regSortOut = ++pParse->nMem;
95691     int ptab2 = pParse->nTab++;
95692     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
95693     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
95694     codeOffset(v, p, addrContinue);
95695     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
95696     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
95697     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95698   }else{
95699     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
95700     codeOffset(v, p, addrContinue);
95701     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
95702   }
95703   switch( eDest ){
95704     case SRT_Table:
95705     case SRT_EphemTab: {
95706       testcase( eDest==SRT_Table );
95707       testcase( eDest==SRT_EphemTab );
95708       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
95709       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
95710       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95711       break;
95712     }
95713 #ifndef SQLITE_OMIT_SUBQUERY
95714     case SRT_Set: {
95715       assert( nColumn==1 );
95716       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
95717                         &pDest->affSdst, 1);
95718       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
95719       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
95720       break;
95721     }
95722     case SRT_Mem: {
95723       assert( nColumn==1 );
95724       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
95725       /* The LIMIT clause will terminate the loop for us */
95726       break;
95727     }
95728 #endif
95729     default: {
95730       int i;
95731       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
95732       testcase( eDest==SRT_Output );
95733       testcase( eDest==SRT_Coroutine );
95734       for(i=0; i<nColumn; i++){
95735         assert( regRow!=pDest->iSdst+i );
95736         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
95737         if( i==0 ){
95738           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95739         }
95740       }
95741       if( eDest==SRT_Output ){
95742         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
95743         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
95744       }else{
95745         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
95746       }
95747       break;
95748     }
95749   }
95750   sqlite3ReleaseTempReg(pParse, regRow);
95751   sqlite3ReleaseTempReg(pParse, regRowid);
95752
95753   /* The bottom of the loop
95754   */
95755   sqlite3VdbeResolveLabel(v, addrContinue);
95756   if( p->selFlags & SF_UseSorter ){
95757     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
95758   }else{
95759     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
95760   }
95761   sqlite3VdbeResolveLabel(v, addrBreak);
95762   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95763     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
95764   }
95765 }
95766
95767 /*
95768 ** Return a pointer to a string containing the 'declaration type' of the
95769 ** expression pExpr. The string may be treated as static by the caller.
95770 **
95771 ** The declaration type is the exact datatype definition extracted from the
95772 ** original CREATE TABLE statement if the expression is a column. The
95773 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
95774 ** is considered a column can be complex in the presence of subqueries. The
95775 ** result-set expression in all of the following SELECT statements is 
95776 ** considered a column by this function.
95777 **
95778 **   SELECT col FROM tbl;
95779 **   SELECT (SELECT col FROM tbl;
95780 **   SELECT (SELECT col FROM tbl);
95781 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
95782 ** 
95783 ** The declaration type for any expression other than a column is NULL.
95784 */
95785 static const char *columnType(
95786   NameContext *pNC, 
95787   Expr *pExpr,
95788   const char **pzOriginDb,
95789   const char **pzOriginTab,
95790   const char **pzOriginCol
95791 ){
95792   char const *zType = 0;
95793   char const *zOriginDb = 0;
95794   char const *zOriginTab = 0;
95795   char const *zOriginCol = 0;
95796   int j;
95797   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
95798
95799   switch( pExpr->op ){
95800     case TK_AGG_COLUMN:
95801     case TK_COLUMN: {
95802       /* The expression is a column. Locate the table the column is being
95803       ** extracted from in NameContext.pSrcList. This table may be real
95804       ** database table or a subquery.
95805       */
95806       Table *pTab = 0;            /* Table structure column is extracted from */
95807       Select *pS = 0;             /* Select the column is extracted from */
95808       int iCol = pExpr->iColumn;  /* Index of column in pTab */
95809       testcase( pExpr->op==TK_AGG_COLUMN );
95810       testcase( pExpr->op==TK_COLUMN );
95811       while( pNC && !pTab ){
95812         SrcList *pTabList = pNC->pSrcList;
95813         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
95814         if( j<pTabList->nSrc ){
95815           pTab = pTabList->a[j].pTab;
95816           pS = pTabList->a[j].pSelect;
95817         }else{
95818           pNC = pNC->pNext;
95819         }
95820       }
95821
95822       if( pTab==0 ){
95823         /* At one time, code such as "SELECT new.x" within a trigger would
95824         ** cause this condition to run.  Since then, we have restructured how
95825         ** trigger code is generated and so this condition is no longer 
95826         ** possible. However, it can still be true for statements like
95827         ** the following:
95828         **
95829         **   CREATE TABLE t1(col INTEGER);
95830         **   SELECT (SELECT t1.col) FROM FROM t1;
95831         **
95832         ** when columnType() is called on the expression "t1.col" in the 
95833         ** sub-select. In this case, set the column type to NULL, even
95834         ** though it should really be "INTEGER".
95835         **
95836         ** This is not a problem, as the column type of "t1.col" is never
95837         ** used. When columnType() is called on the expression 
95838         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
95839         ** branch below.  */
95840         break;
95841       }
95842
95843       assert( pTab && pExpr->pTab==pTab );
95844       if( pS ){
95845         /* The "table" is actually a sub-select or a view in the FROM clause
95846         ** of the SELECT statement. Return the declaration type and origin
95847         ** data for the result-set column of the sub-select.
95848         */
95849         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
95850           /* If iCol is less than zero, then the expression requests the
95851           ** rowid of the sub-select or view. This expression is legal (see 
95852           ** test case misc2.2.2) - it always evaluates to NULL.
95853           */
95854           NameContext sNC;
95855           Expr *p = pS->pEList->a[iCol].pExpr;
95856           sNC.pSrcList = pS->pSrc;
95857           sNC.pNext = pNC;
95858           sNC.pParse = pNC->pParse;
95859           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
95860         }
95861       }else if( ALWAYS(pTab->pSchema) ){
95862         /* A real table */
95863         assert( !pS );
95864         if( iCol<0 ) iCol = pTab->iPKey;
95865         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95866         if( iCol<0 ){
95867           zType = "INTEGER";
95868           zOriginCol = "rowid";
95869         }else{
95870           zType = pTab->aCol[iCol].zType;
95871           zOriginCol = pTab->aCol[iCol].zName;
95872         }
95873         zOriginTab = pTab->zName;
95874         if( pNC->pParse ){
95875           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
95876           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
95877         }
95878       }
95879       break;
95880     }
95881 #ifndef SQLITE_OMIT_SUBQUERY
95882     case TK_SELECT: {
95883       /* The expression is a sub-select. Return the declaration type and
95884       ** origin info for the single column in the result set of the SELECT
95885       ** statement.
95886       */
95887       NameContext sNC;
95888       Select *pS = pExpr->x.pSelect;
95889       Expr *p = pS->pEList->a[0].pExpr;
95890       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
95891       sNC.pSrcList = pS->pSrc;
95892       sNC.pNext = pNC;
95893       sNC.pParse = pNC->pParse;
95894       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
95895       break;
95896     }
95897 #endif
95898   }
95899   
95900   if( pzOriginDb ){
95901     assert( pzOriginTab && pzOriginCol );
95902     *pzOriginDb = zOriginDb;
95903     *pzOriginTab = zOriginTab;
95904     *pzOriginCol = zOriginCol;
95905   }
95906   return zType;
95907 }
95908
95909 /*
95910 ** Generate code that will tell the VDBE the declaration types of columns
95911 ** in the result set.
95912 */
95913 static void generateColumnTypes(
95914   Parse *pParse,      /* Parser context */
95915   SrcList *pTabList,  /* List of tables */
95916   ExprList *pEList    /* Expressions defining the result set */
95917 ){
95918 #ifndef SQLITE_OMIT_DECLTYPE
95919   Vdbe *v = pParse->pVdbe;
95920   int i;
95921   NameContext sNC;
95922   sNC.pSrcList = pTabList;
95923   sNC.pParse = pParse;
95924   for(i=0; i<pEList->nExpr; i++){
95925     Expr *p = pEList->a[i].pExpr;
95926     const char *zType;
95927 #ifdef SQLITE_ENABLE_COLUMN_METADATA
95928     const char *zOrigDb = 0;
95929     const char *zOrigTab = 0;
95930     const char *zOrigCol = 0;
95931     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
95932
95933     /* The vdbe must make its own copy of the column-type and other 
95934     ** column specific strings, in case the schema is reset before this
95935     ** virtual machine is deleted.
95936     */
95937     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
95938     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
95939     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
95940 #else
95941     zType = columnType(&sNC, p, 0, 0, 0);
95942 #endif
95943     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
95944   }
95945 #endif /* SQLITE_OMIT_DECLTYPE */
95946 }
95947
95948 /*
95949 ** Generate code that will tell the VDBE the names of columns
95950 ** in the result set.  This information is used to provide the
95951 ** azCol[] values in the callback.
95952 */
95953 static void generateColumnNames(
95954   Parse *pParse,      /* Parser context */
95955   SrcList *pTabList,  /* List of tables */
95956   ExprList *pEList    /* Expressions defining the result set */
95957 ){
95958   Vdbe *v = pParse->pVdbe;
95959   int i, j;
95960   sqlite3 *db = pParse->db;
95961   int fullNames, shortNames;
95962
95963 #ifndef SQLITE_OMIT_EXPLAIN
95964   /* If this is an EXPLAIN, skip this step */
95965   if( pParse->explain ){
95966     return;
95967   }
95968 #endif
95969
95970   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
95971   pParse->colNamesSet = 1;
95972   fullNames = (db->flags & SQLITE_FullColNames)!=0;
95973   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
95974   sqlite3VdbeSetNumCols(v, pEList->nExpr);
95975   for(i=0; i<pEList->nExpr; i++){
95976     Expr *p;
95977     p = pEList->a[i].pExpr;
95978     if( NEVER(p==0) ) continue;
95979     if( pEList->a[i].zName ){
95980       char *zName = pEList->a[i].zName;
95981       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
95982     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
95983       Table *pTab;
95984       char *zCol;
95985       int iCol = p->iColumn;
95986       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
95987         if( pTabList->a[j].iCursor==p->iTable ) break;
95988       }
95989       assert( j<pTabList->nSrc );
95990       pTab = pTabList->a[j].pTab;
95991       if( iCol<0 ) iCol = pTab->iPKey;
95992       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95993       if( iCol<0 ){
95994         zCol = "rowid";
95995       }else{
95996         zCol = pTab->aCol[iCol].zName;
95997       }
95998       if( !shortNames && !fullNames ){
95999         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
96000             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
96001       }else if( fullNames ){
96002         char *zName = 0;
96003         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
96004         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
96005       }else{
96006         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
96007       }
96008     }else{
96009       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
96010           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
96011     }
96012   }
96013   generateColumnTypes(pParse, pTabList, pEList);
96014 }
96015
96016 /*
96017 ** Given a an expression list (which is really the list of expressions
96018 ** that form the result set of a SELECT statement) compute appropriate
96019 ** column names for a table that would hold the expression list.
96020 **
96021 ** All column names will be unique.
96022 **
96023 ** Only the column names are computed.  Column.zType, Column.zColl,
96024 ** and other fields of Column are zeroed.
96025 **
96026 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
96027 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
96028 */
96029 static int selectColumnsFromExprList(
96030   Parse *pParse,          /* Parsing context */
96031   ExprList *pEList,       /* Expr list from which to derive column names */
96032   i16 *pnCol,             /* Write the number of columns here */
96033   Column **paCol          /* Write the new column list here */
96034 ){
96035   sqlite3 *db = pParse->db;   /* Database connection */
96036   int i, j;                   /* Loop counters */
96037   int cnt;                    /* Index added to make the name unique */
96038   Column *aCol, *pCol;        /* For looping over result columns */
96039   int nCol;                   /* Number of columns in the result set */
96040   Expr *p;                    /* Expression for a single result column */
96041   char *zName;                /* Column name */
96042   int nName;                  /* Size of name in zName[] */
96043
96044   if( pEList ){
96045     nCol = pEList->nExpr;
96046     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
96047     testcase( aCol==0 );
96048   }else{
96049     nCol = 0;
96050     aCol = 0;
96051   }
96052   *pnCol = nCol;
96053   *paCol = aCol;
96054
96055   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
96056     /* Get an appropriate name for the column
96057     */
96058     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
96059     if( (zName = pEList->a[i].zName)!=0 ){
96060       /* If the column contains an "AS <name>" phrase, use <name> as the name */
96061       zName = sqlite3DbStrDup(db, zName);
96062     }else{
96063       Expr *pColExpr = p;  /* The expression that is the result column name */
96064       Table *pTab;         /* Table associated with this expression */
96065       while( pColExpr->op==TK_DOT ){
96066         pColExpr = pColExpr->pRight;
96067         assert( pColExpr!=0 );
96068       }
96069       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
96070         /* For columns use the column name name */
96071         int iCol = pColExpr->iColumn;
96072         pTab = pColExpr->pTab;
96073         if( iCol<0 ) iCol = pTab->iPKey;
96074         zName = sqlite3MPrintf(db, "%s",
96075                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
96076       }else if( pColExpr->op==TK_ID ){
96077         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
96078         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
96079       }else{
96080         /* Use the original text of the column expression as its name */
96081         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
96082       }
96083     }
96084     if( db->mallocFailed ){
96085       sqlite3DbFree(db, zName);
96086       break;
96087     }
96088
96089     /* Make sure the column name is unique.  If the name is not unique,
96090     ** append a integer to the name so that it becomes unique.
96091     */
96092     nName = sqlite3Strlen30(zName);
96093     for(j=cnt=0; j<i; j++){
96094       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
96095         char *zNewName;
96096         int k;
96097         for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
96098         if( zName[k]==':' ) nName = k;
96099         zName[nName] = 0;
96100         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
96101         sqlite3DbFree(db, zName);
96102         zName = zNewName;
96103         j = -1;
96104         if( zName==0 ) break;
96105       }
96106     }
96107     pCol->zName = zName;
96108   }
96109   if( db->mallocFailed ){
96110     for(j=0; j<i; j++){
96111       sqlite3DbFree(db, aCol[j].zName);
96112     }
96113     sqlite3DbFree(db, aCol);
96114     *paCol = 0;
96115     *pnCol = 0;
96116     return SQLITE_NOMEM;
96117   }
96118   return SQLITE_OK;
96119 }
96120
96121 /*
96122 ** Add type and collation information to a column list based on
96123 ** a SELECT statement.
96124 ** 
96125 ** The column list presumably came from selectColumnNamesFromExprList().
96126 ** The column list has only names, not types or collations.  This
96127 ** routine goes through and adds the types and collations.
96128 **
96129 ** This routine requires that all identifiers in the SELECT
96130 ** statement be resolved.
96131 */
96132 static void selectAddColumnTypeAndCollation(
96133   Parse *pParse,        /* Parsing contexts */
96134   int nCol,             /* Number of columns */
96135   Column *aCol,         /* List of columns */
96136   Select *pSelect       /* SELECT used to determine types and collations */
96137 ){
96138   sqlite3 *db = pParse->db;
96139   NameContext sNC;
96140   Column *pCol;
96141   CollSeq *pColl;
96142   int i;
96143   Expr *p;
96144   struct ExprList_item *a;
96145
96146   assert( pSelect!=0 );
96147   assert( (pSelect->selFlags & SF_Resolved)!=0 );
96148   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
96149   if( db->mallocFailed ) return;
96150   memset(&sNC, 0, sizeof(sNC));
96151   sNC.pSrcList = pSelect->pSrc;
96152   a = pSelect->pEList->a;
96153   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
96154     p = a[i].pExpr;
96155     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
96156     pCol->affinity = sqlite3ExprAffinity(p);
96157     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
96158     pColl = sqlite3ExprCollSeq(pParse, p);
96159     if( pColl ){
96160       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
96161     }
96162   }
96163 }
96164
96165 /*
96166 ** Given a SELECT statement, generate a Table structure that describes
96167 ** the result set of that SELECT.
96168 */
96169 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
96170   Table *pTab;
96171   sqlite3 *db = pParse->db;
96172   int savedFlags;
96173
96174   savedFlags = db->flags;
96175   db->flags &= ~SQLITE_FullColNames;
96176   db->flags |= SQLITE_ShortColNames;
96177   sqlite3SelectPrep(pParse, pSelect, 0);
96178   if( pParse->nErr ) return 0;
96179   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
96180   db->flags = savedFlags;
96181   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
96182   if( pTab==0 ){
96183     return 0;
96184   }
96185   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
96186   ** is disabled */
96187   assert( db->lookaside.bEnabled==0 );
96188   pTab->nRef = 1;
96189   pTab->zName = 0;
96190   pTab->nRowEst = 1000000;
96191   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
96192   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
96193   pTab->iPKey = -1;
96194   if( db->mallocFailed ){
96195     sqlite3DeleteTable(db, pTab);
96196     return 0;
96197   }
96198   return pTab;
96199 }
96200
96201 /*
96202 ** Get a VDBE for the given parser context.  Create a new one if necessary.
96203 ** If an error occurs, return NULL and leave a message in pParse.
96204 */
96205 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
96206   Vdbe *v = pParse->pVdbe;
96207   if( v==0 ){
96208     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
96209 #ifndef SQLITE_OMIT_TRACE
96210     if( v ){
96211       sqlite3VdbeAddOp0(v, OP_Trace);
96212     }
96213 #endif
96214   }
96215   return v;
96216 }
96217
96218
96219 /*
96220 ** Compute the iLimit and iOffset fields of the SELECT based on the
96221 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
96222 ** that appear in the original SQL statement after the LIMIT and OFFSET
96223 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
96224 ** are the integer memory register numbers for counters used to compute 
96225 ** the limit and offset.  If there is no limit and/or offset, then 
96226 ** iLimit and iOffset are negative.
96227 **
96228 ** This routine changes the values of iLimit and iOffset only if
96229 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
96230 ** iOffset should have been preset to appropriate default values
96231 ** (usually but not always -1) prior to calling this routine.
96232 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
96233 ** redefined.  The UNION ALL operator uses this property to force
96234 ** the reuse of the same limit and offset registers across multiple
96235 ** SELECT statements.
96236 */
96237 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
96238   Vdbe *v = 0;
96239   int iLimit = 0;
96240   int iOffset;
96241   int addr1, n;
96242   if( p->iLimit ) return;
96243
96244   /* 
96245   ** "LIMIT -1" always shows all rows.  There is some
96246   ** contraversy about what the correct behavior should be.
96247   ** The current implementation interprets "LIMIT 0" to mean
96248   ** no rows.
96249   */
96250   sqlite3ExprCacheClear(pParse);
96251   assert( p->pOffset==0 || p->pLimit!=0 );
96252   if( p->pLimit ){
96253     p->iLimit = iLimit = ++pParse->nMem;
96254     v = sqlite3GetVdbe(pParse);
96255     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
96256     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
96257       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
96258       VdbeComment((v, "LIMIT counter"));
96259       if( n==0 ){
96260         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
96261       }else{
96262         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
96263       }
96264     }else{
96265       sqlite3ExprCode(pParse, p->pLimit, iLimit);
96266       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
96267       VdbeComment((v, "LIMIT counter"));
96268       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
96269     }
96270     if( p->pOffset ){
96271       p->iOffset = iOffset = ++pParse->nMem;
96272       pParse->nMem++;   /* Allocate an extra register for limit+offset */
96273       sqlite3ExprCode(pParse, p->pOffset, iOffset);
96274       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
96275       VdbeComment((v, "OFFSET counter"));
96276       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
96277       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
96278       sqlite3VdbeJumpHere(v, addr1);
96279       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
96280       VdbeComment((v, "LIMIT+OFFSET"));
96281       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
96282       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
96283       sqlite3VdbeJumpHere(v, addr1);
96284     }
96285   }
96286 }
96287
96288 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96289 /*
96290 ** Return the appropriate collating sequence for the iCol-th column of
96291 ** the result set for the compound-select statement "p".  Return NULL if
96292 ** the column has no default collating sequence.
96293 **
96294 ** The collating sequence for the compound select is taken from the
96295 ** left-most term of the select that has a collating sequence.
96296 */
96297 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
96298   CollSeq *pRet;
96299   if( p->pPrior ){
96300     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
96301   }else{
96302     pRet = 0;
96303   }
96304   assert( iCol>=0 );
96305   if( pRet==0 && iCol<p->pEList->nExpr ){
96306     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
96307   }
96308   return pRet;
96309 }
96310 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
96311
96312 /* Forward reference */
96313 static int multiSelectOrderBy(
96314   Parse *pParse,        /* Parsing context */
96315   Select *p,            /* The right-most of SELECTs to be coded */
96316   SelectDest *pDest     /* What to do with query results */
96317 );
96318
96319
96320 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96321 /*
96322 ** This routine is called to process a compound query form from
96323 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
96324 ** INTERSECT
96325 **
96326 ** "p" points to the right-most of the two queries.  the query on the
96327 ** left is p->pPrior.  The left query could also be a compound query
96328 ** in which case this routine will be called recursively. 
96329 **
96330 ** The results of the total query are to be written into a destination
96331 ** of type eDest with parameter iParm.
96332 **
96333 ** Example 1:  Consider a three-way compound SQL statement.
96334 **
96335 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
96336 **
96337 ** This statement is parsed up as follows:
96338 **
96339 **     SELECT c FROM t3
96340 **      |
96341 **      `----->  SELECT b FROM t2
96342 **                |
96343 **                `------>  SELECT a FROM t1
96344 **
96345 ** The arrows in the diagram above represent the Select.pPrior pointer.
96346 ** So if this routine is called with p equal to the t3 query, then
96347 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
96348 **
96349 ** Notice that because of the way SQLite parses compound SELECTs, the
96350 ** individual selects always group from left to right.
96351 */
96352 static int multiSelect(
96353   Parse *pParse,        /* Parsing context */
96354   Select *p,            /* The right-most of SELECTs to be coded */
96355   SelectDest *pDest     /* What to do with query results */
96356 ){
96357   int rc = SQLITE_OK;   /* Success code from a subroutine */
96358   Select *pPrior;       /* Another SELECT immediately to our left */
96359   Vdbe *v;              /* Generate code to this VDBE */
96360   SelectDest dest;      /* Alternative data destination */
96361   Select *pDelete = 0;  /* Chain of simple selects to delete */
96362   sqlite3 *db;          /* Database connection */
96363 #ifndef SQLITE_OMIT_EXPLAIN
96364   int iSub1;            /* EQP id of left-hand query */
96365   int iSub2;            /* EQP id of right-hand query */
96366 #endif
96367
96368   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
96369   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
96370   */
96371   assert( p && p->pPrior );  /* Calling function guarantees this much */
96372   db = pParse->db;
96373   pPrior = p->pPrior;
96374   assert( pPrior->pRightmost!=pPrior );
96375   assert( pPrior->pRightmost==p->pRightmost );
96376   dest = *pDest;
96377   if( pPrior->pOrderBy ){
96378     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
96379       selectOpName(p->op));
96380     rc = 1;
96381     goto multi_select_end;
96382   }
96383   if( pPrior->pLimit ){
96384     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
96385       selectOpName(p->op));
96386     rc = 1;
96387     goto multi_select_end;
96388   }
96389
96390   v = sqlite3GetVdbe(pParse);
96391   assert( v!=0 );  /* The VDBE already created by calling function */
96392
96393   /* Create the destination temporary table if necessary
96394   */
96395   if( dest.eDest==SRT_EphemTab ){
96396     assert( p->pEList );
96397     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
96398     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
96399     dest.eDest = SRT_Table;
96400   }
96401
96402   /* Make sure all SELECTs in the statement have the same number of elements
96403   ** in their result sets.
96404   */
96405   assert( p->pEList && pPrior->pEList );
96406   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
96407     if( p->selFlags & SF_Values ){
96408       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
96409     }else{
96410       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
96411         " do not have the same number of result columns", selectOpName(p->op));
96412     }
96413     rc = 1;
96414     goto multi_select_end;
96415   }
96416
96417   /* Compound SELECTs that have an ORDER BY clause are handled separately.
96418   */
96419   if( p->pOrderBy ){
96420     return multiSelectOrderBy(pParse, p, pDest);
96421   }
96422
96423   /* Generate code for the left and right SELECT statements.
96424   */
96425   switch( p->op ){
96426     case TK_ALL: {
96427       int addr = 0;
96428       int nLimit;
96429       assert( !pPrior->pLimit );
96430       pPrior->iLimit = p->iLimit;
96431       pPrior->iOffset = p->iOffset;
96432       pPrior->pLimit = p->pLimit;
96433       pPrior->pOffset = p->pOffset;
96434       explainSetInteger(iSub1, pParse->iNextSelectId);
96435       rc = sqlite3Select(pParse, pPrior, &dest);
96436       p->pLimit = 0;
96437       p->pOffset = 0;
96438       if( rc ){
96439         goto multi_select_end;
96440       }
96441       p->pPrior = 0;
96442       p->iLimit = pPrior->iLimit;
96443       p->iOffset = pPrior->iOffset;
96444       if( p->iLimit ){
96445         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
96446         VdbeComment((v, "Jump ahead if LIMIT reached"));
96447       }
96448       explainSetInteger(iSub2, pParse->iNextSelectId);
96449       rc = sqlite3Select(pParse, p, &dest);
96450       testcase( rc!=SQLITE_OK );
96451       pDelete = p->pPrior;
96452       p->pPrior = pPrior;
96453       p->nSelectRow += pPrior->nSelectRow;
96454       if( pPrior->pLimit
96455        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
96456        && p->nSelectRow > (double)nLimit 
96457       ){
96458         p->nSelectRow = (double)nLimit;
96459       }
96460       if( addr ){
96461         sqlite3VdbeJumpHere(v, addr);
96462       }
96463       break;
96464     }
96465     case TK_EXCEPT:
96466     case TK_UNION: {
96467       int unionTab;    /* Cursor number of the temporary table holding result */
96468       u8 op = 0;       /* One of the SRT_ operations to apply to self */
96469       int priorOp;     /* The SRT_ operation to apply to prior selects */
96470       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
96471       int addr;
96472       SelectDest uniondest;
96473
96474       testcase( p->op==TK_EXCEPT );
96475       testcase( p->op==TK_UNION );
96476       priorOp = SRT_Union;
96477       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
96478         /* We can reuse a temporary table generated by a SELECT to our
96479         ** right.
96480         */
96481         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
96482                                      ** of a 3-way or more compound */
96483         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
96484         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
96485         unionTab = dest.iSDParm;
96486       }else{
96487         /* We will need to create our own temporary table to hold the
96488         ** intermediate results.
96489         */
96490         unionTab = pParse->nTab++;
96491         assert( p->pOrderBy==0 );
96492         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
96493         assert( p->addrOpenEphm[0] == -1 );
96494         p->addrOpenEphm[0] = addr;
96495         p->pRightmost->selFlags |= SF_UsesEphemeral;
96496         assert( p->pEList );
96497       }
96498
96499       /* Code the SELECT statements to our left
96500       */
96501       assert( !pPrior->pOrderBy );
96502       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
96503       explainSetInteger(iSub1, pParse->iNextSelectId);
96504       rc = sqlite3Select(pParse, pPrior, &uniondest);
96505       if( rc ){
96506         goto multi_select_end;
96507       }
96508
96509       /* Code the current SELECT statement
96510       */
96511       if( p->op==TK_EXCEPT ){
96512         op = SRT_Except;
96513       }else{
96514         assert( p->op==TK_UNION );
96515         op = SRT_Union;
96516       }
96517       p->pPrior = 0;
96518       pLimit = p->pLimit;
96519       p->pLimit = 0;
96520       pOffset = p->pOffset;
96521       p->pOffset = 0;
96522       uniondest.eDest = op;
96523       explainSetInteger(iSub2, pParse->iNextSelectId);
96524       rc = sqlite3Select(pParse, p, &uniondest);
96525       testcase( rc!=SQLITE_OK );
96526       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
96527       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
96528       sqlite3ExprListDelete(db, p->pOrderBy);
96529       pDelete = p->pPrior;
96530       p->pPrior = pPrior;
96531       p->pOrderBy = 0;
96532       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
96533       sqlite3ExprDelete(db, p->pLimit);
96534       p->pLimit = pLimit;
96535       p->pOffset = pOffset;
96536       p->iLimit = 0;
96537       p->iOffset = 0;
96538
96539       /* Convert the data in the temporary table into whatever form
96540       ** it is that we currently need.
96541       */
96542       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
96543       if( dest.eDest!=priorOp ){
96544         int iCont, iBreak, iStart;
96545         assert( p->pEList );
96546         if( dest.eDest==SRT_Output ){
96547           Select *pFirst = p;
96548           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96549           generateColumnNames(pParse, 0, pFirst->pEList);
96550         }
96551         iBreak = sqlite3VdbeMakeLabel(v);
96552         iCont = sqlite3VdbeMakeLabel(v);
96553         computeLimitRegisters(pParse, p, iBreak);
96554         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
96555         iStart = sqlite3VdbeCurrentAddr(v);
96556         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
96557                         0, 0, &dest, iCont, iBreak);
96558         sqlite3VdbeResolveLabel(v, iCont);
96559         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
96560         sqlite3VdbeResolveLabel(v, iBreak);
96561         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
96562       }
96563       break;
96564     }
96565     default: assert( p->op==TK_INTERSECT ); {
96566       int tab1, tab2;
96567       int iCont, iBreak, iStart;
96568       Expr *pLimit, *pOffset;
96569       int addr;
96570       SelectDest intersectdest;
96571       int r1;
96572
96573       /* INTERSECT is different from the others since it requires
96574       ** two temporary tables.  Hence it has its own case.  Begin
96575       ** by allocating the tables we will need.
96576       */
96577       tab1 = pParse->nTab++;
96578       tab2 = pParse->nTab++;
96579       assert( p->pOrderBy==0 );
96580
96581       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
96582       assert( p->addrOpenEphm[0] == -1 );
96583       p->addrOpenEphm[0] = addr;
96584       p->pRightmost->selFlags |= SF_UsesEphemeral;
96585       assert( p->pEList );
96586
96587       /* Code the SELECTs to our left into temporary table "tab1".
96588       */
96589       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
96590       explainSetInteger(iSub1, pParse->iNextSelectId);
96591       rc = sqlite3Select(pParse, pPrior, &intersectdest);
96592       if( rc ){
96593         goto multi_select_end;
96594       }
96595
96596       /* Code the current SELECT into temporary table "tab2"
96597       */
96598       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
96599       assert( p->addrOpenEphm[1] == -1 );
96600       p->addrOpenEphm[1] = addr;
96601       p->pPrior = 0;
96602       pLimit = p->pLimit;
96603       p->pLimit = 0;
96604       pOffset = p->pOffset;
96605       p->pOffset = 0;
96606       intersectdest.iSDParm = tab2;
96607       explainSetInteger(iSub2, pParse->iNextSelectId);
96608       rc = sqlite3Select(pParse, p, &intersectdest);
96609       testcase( rc!=SQLITE_OK );
96610       pDelete = p->pPrior;
96611       p->pPrior = pPrior;
96612       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
96613       sqlite3ExprDelete(db, p->pLimit);
96614       p->pLimit = pLimit;
96615       p->pOffset = pOffset;
96616
96617       /* Generate code to take the intersection of the two temporary
96618       ** tables.
96619       */
96620       assert( p->pEList );
96621       if( dest.eDest==SRT_Output ){
96622         Select *pFirst = p;
96623         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96624         generateColumnNames(pParse, 0, pFirst->pEList);
96625       }
96626       iBreak = sqlite3VdbeMakeLabel(v);
96627       iCont = sqlite3VdbeMakeLabel(v);
96628       computeLimitRegisters(pParse, p, iBreak);
96629       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
96630       r1 = sqlite3GetTempReg(pParse);
96631       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
96632       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
96633       sqlite3ReleaseTempReg(pParse, r1);
96634       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
96635                       0, 0, &dest, iCont, iBreak);
96636       sqlite3VdbeResolveLabel(v, iCont);
96637       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
96638       sqlite3VdbeResolveLabel(v, iBreak);
96639       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
96640       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
96641       break;
96642     }
96643   }
96644
96645   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
96646
96647   /* Compute collating sequences used by 
96648   ** temporary tables needed to implement the compound select.
96649   ** Attach the KeyInfo structure to all temporary tables.
96650   **
96651   ** This section is run by the right-most SELECT statement only.
96652   ** SELECT statements to the left always skip this part.  The right-most
96653   ** SELECT might also skip this part if it has no ORDER BY clause and
96654   ** no temp tables are required.
96655   */
96656   if( p->selFlags & SF_UsesEphemeral ){
96657     int i;                        /* Loop counter */
96658     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
96659     Select *pLoop;                /* For looping through SELECT statements */
96660     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
96661     int nCol;                     /* Number of columns in result set */
96662
96663     assert( p->pRightmost==p );
96664     nCol = p->pEList->nExpr;
96665     pKeyInfo = sqlite3DbMallocZero(db,
96666                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
96667     if( !pKeyInfo ){
96668       rc = SQLITE_NOMEM;
96669       goto multi_select_end;
96670     }
96671
96672     pKeyInfo->enc = ENC(db);
96673     pKeyInfo->nField = (u16)nCol;
96674
96675     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
96676       *apColl = multiSelectCollSeq(pParse, p, i);
96677       if( 0==*apColl ){
96678         *apColl = db->pDfltColl;
96679       }
96680     }
96681     pKeyInfo->aSortOrder = (u8*)apColl;
96682
96683     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
96684       for(i=0; i<2; i++){
96685         int addr = pLoop->addrOpenEphm[i];
96686         if( addr<0 ){
96687           /* If [0] is unused then [1] is also unused.  So we can
96688           ** always safely abort as soon as the first unused slot is found */
96689           assert( pLoop->addrOpenEphm[1]<0 );
96690           break;
96691         }
96692         sqlite3VdbeChangeP2(v, addr, nCol);
96693         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
96694         pLoop->addrOpenEphm[i] = -1;
96695       }
96696     }
96697     sqlite3DbFree(db, pKeyInfo);
96698   }
96699
96700 multi_select_end:
96701   pDest->iSdst = dest.iSdst;
96702   pDest->nSdst = dest.nSdst;
96703   sqlite3SelectDelete(db, pDelete);
96704   return rc;
96705 }
96706 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
96707
96708 /*
96709 ** Code an output subroutine for a coroutine implementation of a
96710 ** SELECT statment.
96711 **
96712 ** The data to be output is contained in pIn->iSdst.  There are
96713 ** pIn->nSdst columns to be output.  pDest is where the output should
96714 ** be sent.
96715 **
96716 ** regReturn is the number of the register holding the subroutine
96717 ** return address.
96718 **
96719 ** If regPrev>0 then it is the first register in a vector that
96720 ** records the previous output.  mem[regPrev] is a flag that is false
96721 ** if there has been no previous output.  If regPrev>0 then code is
96722 ** generated to suppress duplicates.  pKeyInfo is used for comparing
96723 ** keys.
96724 **
96725 ** If the LIMIT found in p->iLimit is reached, jump immediately to
96726 ** iBreak.
96727 */
96728 static int generateOutputSubroutine(
96729   Parse *pParse,          /* Parsing context */
96730   Select *p,              /* The SELECT statement */
96731   SelectDest *pIn,        /* Coroutine supplying data */
96732   SelectDest *pDest,      /* Where to send the data */
96733   int regReturn,          /* The return address register */
96734   int regPrev,            /* Previous result register.  No uniqueness if 0 */
96735   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
96736   int p4type,             /* The p4 type for pKeyInfo */
96737   int iBreak              /* Jump here if we hit the LIMIT */
96738 ){
96739   Vdbe *v = pParse->pVdbe;
96740   int iContinue;
96741   int addr;
96742
96743   addr = sqlite3VdbeCurrentAddr(v);
96744   iContinue = sqlite3VdbeMakeLabel(v);
96745
96746   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
96747   */
96748   if( regPrev ){
96749     int j1, j2;
96750     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
96751     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
96752                               (char*)pKeyInfo, p4type);
96753     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
96754     sqlite3VdbeJumpHere(v, j1);
96755     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
96756     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
96757   }
96758   if( pParse->db->mallocFailed ) return 0;
96759
96760   /* Suppress the first OFFSET entries if there is an OFFSET clause
96761   */
96762   codeOffset(v, p, iContinue);
96763
96764   switch( pDest->eDest ){
96765     /* Store the result as data using a unique key.
96766     */
96767     case SRT_Table:
96768     case SRT_EphemTab: {
96769       int r1 = sqlite3GetTempReg(pParse);
96770       int r2 = sqlite3GetTempReg(pParse);
96771       testcase( pDest->eDest==SRT_Table );
96772       testcase( pDest->eDest==SRT_EphemTab );
96773       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
96774       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
96775       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
96776       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96777       sqlite3ReleaseTempReg(pParse, r2);
96778       sqlite3ReleaseTempReg(pParse, r1);
96779       break;
96780     }
96781
96782 #ifndef SQLITE_OMIT_SUBQUERY
96783     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
96784     ** then there should be a single item on the stack.  Write this
96785     ** item into the set table with bogus data.
96786     */
96787     case SRT_Set: {
96788       int r1;
96789       assert( pIn->nSdst==1 );
96790       pDest->affSdst = 
96791          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
96792       r1 = sqlite3GetTempReg(pParse);
96793       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
96794       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
96795       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
96796       sqlite3ReleaseTempReg(pParse, r1);
96797       break;
96798     }
96799
96800 #if 0  /* Never occurs on an ORDER BY query */
96801     /* If any row exist in the result set, record that fact and abort.
96802     */
96803     case SRT_Exists: {
96804       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
96805       /* The LIMIT clause will terminate the loop for us */
96806       break;
96807     }
96808 #endif
96809
96810     /* If this is a scalar select that is part of an expression, then
96811     ** store the results in the appropriate memory cell and break out
96812     ** of the scan loop.
96813     */
96814     case SRT_Mem: {
96815       assert( pIn->nSdst==1 );
96816       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
96817       /* The LIMIT clause will jump out of the loop for us */
96818       break;
96819     }
96820 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
96821
96822     /* The results are stored in a sequence of registers
96823     ** starting at pDest->iSdst.  Then the co-routine yields.
96824     */
96825     case SRT_Coroutine: {
96826       if( pDest->iSdst==0 ){
96827         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
96828         pDest->nSdst = pIn->nSdst;
96829       }
96830       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
96831       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
96832       break;
96833     }
96834
96835     /* If none of the above, then the result destination must be
96836     ** SRT_Output.  This routine is never called with any other
96837     ** destination other than the ones handled above or SRT_Output.
96838     **
96839     ** For SRT_Output, results are stored in a sequence of registers.  
96840     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
96841     ** return the next row of result.
96842     */
96843     default: {
96844       assert( pDest->eDest==SRT_Output );
96845       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
96846       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
96847       break;
96848     }
96849   }
96850
96851   /* Jump to the end of the loop if the LIMIT is reached.
96852   */
96853   if( p->iLimit ){
96854     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
96855   }
96856
96857   /* Generate the subroutine return
96858   */
96859   sqlite3VdbeResolveLabel(v, iContinue);
96860   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
96861
96862   return addr;
96863 }
96864
96865 /*
96866 ** Alternative compound select code generator for cases when there
96867 ** is an ORDER BY clause.
96868 **
96869 ** We assume a query of the following form:
96870 **
96871 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
96872 **
96873 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
96874 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
96875 ** co-routines.  Then run the co-routines in parallel and merge the results
96876 ** into the output.  In addition to the two coroutines (called selectA and
96877 ** selectB) there are 7 subroutines:
96878 **
96879 **    outA:    Move the output of the selectA coroutine into the output
96880 **             of the compound query.
96881 **
96882 **    outB:    Move the output of the selectB coroutine into the output
96883 **             of the compound query.  (Only generated for UNION and
96884 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
96885 **             appears only in B.)
96886 **
96887 **    AltB:    Called when there is data from both coroutines and A<B.
96888 **
96889 **    AeqB:    Called when there is data from both coroutines and A==B.
96890 **
96891 **    AgtB:    Called when there is data from both coroutines and A>B.
96892 **
96893 **    EofA:    Called when data is exhausted from selectA.
96894 **
96895 **    EofB:    Called when data is exhausted from selectB.
96896 **
96897 ** The implementation of the latter five subroutines depend on which 
96898 ** <operator> is used:
96899 **
96900 **
96901 **             UNION ALL         UNION            EXCEPT          INTERSECT
96902 **          -------------  -----------------  --------------  -----------------
96903 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
96904 **
96905 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
96906 **
96907 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
96908 **
96909 **   EofA:   outB, nextB      outB, nextB          halt             halt
96910 **
96911 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
96912 **
96913 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
96914 ** causes an immediate jump to EofA and an EOF on B following nextB causes
96915 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
96916 ** following nextX causes a jump to the end of the select processing.
96917 **
96918 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
96919 ** within the output subroutine.  The regPrev register set holds the previously
96920 ** output value.  A comparison is made against this value and the output
96921 ** is skipped if the next results would be the same as the previous.
96922 **
96923 ** The implementation plan is to implement the two coroutines and seven
96924 ** subroutines first, then put the control logic at the bottom.  Like this:
96925 **
96926 **          goto Init
96927 **     coA: coroutine for left query (A)
96928 **     coB: coroutine for right query (B)
96929 **    outA: output one row of A
96930 **    outB: output one row of B (UNION and UNION ALL only)
96931 **    EofA: ...
96932 **    EofB: ...
96933 **    AltB: ...
96934 **    AeqB: ...
96935 **    AgtB: ...
96936 **    Init: initialize coroutine registers
96937 **          yield coA
96938 **          if eof(A) goto EofA
96939 **          yield coB
96940 **          if eof(B) goto EofB
96941 **    Cmpr: Compare A, B
96942 **          Jump AltB, AeqB, AgtB
96943 **     End: ...
96944 **
96945 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
96946 ** actually called using Gosub and they do not Return.  EofA and EofB loop
96947 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
96948 ** and AgtB jump to either L2 or to one of EofA or EofB.
96949 */
96950 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96951 static int multiSelectOrderBy(
96952   Parse *pParse,        /* Parsing context */
96953   Select *p,            /* The right-most of SELECTs to be coded */
96954   SelectDest *pDest     /* What to do with query results */
96955 ){
96956   int i, j;             /* Loop counters */
96957   Select *pPrior;       /* Another SELECT immediately to our left */
96958   Vdbe *v;              /* Generate code to this VDBE */
96959   SelectDest destA;     /* Destination for coroutine A */
96960   SelectDest destB;     /* Destination for coroutine B */
96961   int regAddrA;         /* Address register for select-A coroutine */
96962   int regEofA;          /* Flag to indicate when select-A is complete */
96963   int regAddrB;         /* Address register for select-B coroutine */
96964   int regEofB;          /* Flag to indicate when select-B is complete */
96965   int addrSelectA;      /* Address of the select-A coroutine */
96966   int addrSelectB;      /* Address of the select-B coroutine */
96967   int regOutA;          /* Address register for the output-A subroutine */
96968   int regOutB;          /* Address register for the output-B subroutine */
96969   int addrOutA;         /* Address of the output-A subroutine */
96970   int addrOutB = 0;     /* Address of the output-B subroutine */
96971   int addrEofA;         /* Address of the select-A-exhausted subroutine */
96972   int addrEofB;         /* Address of the select-B-exhausted subroutine */
96973   int addrAltB;         /* Address of the A<B subroutine */
96974   int addrAeqB;         /* Address of the A==B subroutine */
96975   int addrAgtB;         /* Address of the A>B subroutine */
96976   int regLimitA;        /* Limit register for select-A */
96977   int regLimitB;        /* Limit register for select-A */
96978   int regPrev;          /* A range of registers to hold previous output */
96979   int savedLimit;       /* Saved value of p->iLimit */
96980   int savedOffset;      /* Saved value of p->iOffset */
96981   int labelCmpr;        /* Label for the start of the merge algorithm */
96982   int labelEnd;         /* Label for the end of the overall SELECT stmt */
96983   int j1;               /* Jump instructions that get retargetted */
96984   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
96985   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
96986   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
96987   sqlite3 *db;          /* Database connection */
96988   ExprList *pOrderBy;   /* The ORDER BY clause */
96989   int nOrderBy;         /* Number of terms in the ORDER BY clause */
96990   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
96991 #ifndef SQLITE_OMIT_EXPLAIN
96992   int iSub1;            /* EQP id of left-hand query */
96993   int iSub2;            /* EQP id of right-hand query */
96994 #endif
96995
96996   assert( p->pOrderBy!=0 );
96997   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
96998   db = pParse->db;
96999   v = pParse->pVdbe;
97000   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
97001   labelEnd = sqlite3VdbeMakeLabel(v);
97002   labelCmpr = sqlite3VdbeMakeLabel(v);
97003
97004
97005   /* Patch up the ORDER BY clause
97006   */
97007   op = p->op;  
97008   pPrior = p->pPrior;
97009   assert( pPrior->pOrderBy==0 );
97010   pOrderBy = p->pOrderBy;
97011   assert( pOrderBy );
97012   nOrderBy = pOrderBy->nExpr;
97013
97014   /* For operators other than UNION ALL we have to make sure that
97015   ** the ORDER BY clause covers every term of the result set.  Add
97016   ** terms to the ORDER BY clause as necessary.
97017   */
97018   if( op!=TK_ALL ){
97019     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
97020       struct ExprList_item *pItem;
97021       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
97022         assert( pItem->iOrderByCol>0 );
97023         if( pItem->iOrderByCol==i ) break;
97024       }
97025       if( j==nOrderBy ){
97026         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
97027         if( pNew==0 ) return SQLITE_NOMEM;
97028         pNew->flags |= EP_IntValue;
97029         pNew->u.iValue = i;
97030         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
97031         if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
97032       }
97033     }
97034   }
97035
97036   /* Compute the comparison permutation and keyinfo that is used with
97037   ** the permutation used to determine if the next
97038   ** row of results comes from selectA or selectB.  Also add explicit
97039   ** collations to the ORDER BY clause terms so that when the subqueries
97040   ** to the right and the left are evaluated, they use the correct
97041   ** collation.
97042   */
97043   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
97044   if( aPermute ){
97045     struct ExprList_item *pItem;
97046     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
97047       assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
97048       aPermute[i] = pItem->iOrderByCol - 1;
97049     }
97050     pKeyMerge =
97051       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
97052     if( pKeyMerge ){
97053       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
97054       pKeyMerge->nField = (u16)nOrderBy;
97055       pKeyMerge->enc = ENC(db);
97056       for(i=0; i<nOrderBy; i++){
97057         CollSeq *pColl;
97058         Expr *pTerm = pOrderBy->a[i].pExpr;
97059         if( pTerm->flags & EP_Collate ){
97060           pColl = sqlite3ExprCollSeq(pParse, pTerm);
97061         }else{
97062           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
97063           if( pColl==0 ) pColl = db->pDfltColl;
97064           pOrderBy->a[i].pExpr =
97065              sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
97066         }
97067         pKeyMerge->aColl[i] = pColl;
97068         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
97069       }
97070     }
97071   }else{
97072     pKeyMerge = 0;
97073   }
97074
97075   /* Reattach the ORDER BY clause to the query.
97076   */
97077   p->pOrderBy = pOrderBy;
97078   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
97079
97080   /* Allocate a range of temporary registers and the KeyInfo needed
97081   ** for the logic that removes duplicate result rows when the
97082   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
97083   */
97084   if( op==TK_ALL ){
97085     regPrev = 0;
97086   }else{
97087     int nExpr = p->pEList->nExpr;
97088     assert( nOrderBy>=nExpr || db->mallocFailed );
97089     regPrev = pParse->nMem+1;
97090     pParse->nMem += nExpr+1;
97091     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
97092     pKeyDup = sqlite3DbMallocZero(db,
97093                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
97094     if( pKeyDup ){
97095       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
97096       pKeyDup->nField = (u16)nExpr;
97097       pKeyDup->enc = ENC(db);
97098       for(i=0; i<nExpr; i++){
97099         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
97100         pKeyDup->aSortOrder[i] = 0;
97101       }
97102     }
97103   }
97104  
97105   /* Separate the left and the right query from one another
97106   */
97107   p->pPrior = 0;
97108   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
97109   if( pPrior->pPrior==0 ){
97110     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
97111   }
97112
97113   /* Compute the limit registers */
97114   computeLimitRegisters(pParse, p, labelEnd);
97115   if( p->iLimit && op==TK_ALL ){
97116     regLimitA = ++pParse->nMem;
97117     regLimitB = ++pParse->nMem;
97118     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
97119                                   regLimitA);
97120     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
97121   }else{
97122     regLimitA = regLimitB = 0;
97123   }
97124   sqlite3ExprDelete(db, p->pLimit);
97125   p->pLimit = 0;
97126   sqlite3ExprDelete(db, p->pOffset);
97127   p->pOffset = 0;
97128
97129   regAddrA = ++pParse->nMem;
97130   regEofA = ++pParse->nMem;
97131   regAddrB = ++pParse->nMem;
97132   regEofB = ++pParse->nMem;
97133   regOutA = ++pParse->nMem;
97134   regOutB = ++pParse->nMem;
97135   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
97136   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
97137
97138   /* Jump past the various subroutines and coroutines to the main
97139   ** merge loop
97140   */
97141   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
97142   addrSelectA = sqlite3VdbeCurrentAddr(v);
97143
97144
97145   /* Generate a coroutine to evaluate the SELECT statement to the
97146   ** left of the compound operator - the "A" select.
97147   */
97148   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
97149   pPrior->iLimit = regLimitA;
97150   explainSetInteger(iSub1, pParse->iNextSelectId);
97151   sqlite3Select(pParse, pPrior, &destA);
97152   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
97153   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
97154   VdbeNoopComment((v, "End coroutine for left SELECT"));
97155
97156   /* Generate a coroutine to evaluate the SELECT statement on 
97157   ** the right - the "B" select
97158   */
97159   addrSelectB = sqlite3VdbeCurrentAddr(v);
97160   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
97161   savedLimit = p->iLimit;
97162   savedOffset = p->iOffset;
97163   p->iLimit = regLimitB;
97164   p->iOffset = 0;  
97165   explainSetInteger(iSub2, pParse->iNextSelectId);
97166   sqlite3Select(pParse, p, &destB);
97167   p->iLimit = savedLimit;
97168   p->iOffset = savedOffset;
97169   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
97170   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
97171   VdbeNoopComment((v, "End coroutine for right SELECT"));
97172
97173   /* Generate a subroutine that outputs the current row of the A
97174   ** select as the next output row of the compound select.
97175   */
97176   VdbeNoopComment((v, "Output routine for A"));
97177   addrOutA = generateOutputSubroutine(pParse,
97178                  p, &destA, pDest, regOutA,
97179                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
97180   
97181   /* Generate a subroutine that outputs the current row of the B
97182   ** select as the next output row of the compound select.
97183   */
97184   if( op==TK_ALL || op==TK_UNION ){
97185     VdbeNoopComment((v, "Output routine for B"));
97186     addrOutB = generateOutputSubroutine(pParse,
97187                  p, &destB, pDest, regOutB,
97188                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
97189   }
97190
97191   /* Generate a subroutine to run when the results from select A
97192   ** are exhausted and only data in select B remains.
97193   */
97194   VdbeNoopComment((v, "eof-A subroutine"));
97195   if( op==TK_EXCEPT || op==TK_INTERSECT ){
97196     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
97197   }else{  
97198     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
97199     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
97200     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
97201     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
97202     p->nSelectRow += pPrior->nSelectRow;
97203   }
97204
97205   /* Generate a subroutine to run when the results from select B
97206   ** are exhausted and only data in select A remains.
97207   */
97208   if( op==TK_INTERSECT ){
97209     addrEofB = addrEofA;
97210     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
97211   }else{  
97212     VdbeNoopComment((v, "eof-B subroutine"));
97213     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
97214     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
97215     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
97216     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
97217   }
97218
97219   /* Generate code to handle the case of A<B
97220   */
97221   VdbeNoopComment((v, "A-lt-B subroutine"));
97222   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
97223   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
97224   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
97225   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
97226
97227   /* Generate code to handle the case of A==B
97228   */
97229   if( op==TK_ALL ){
97230     addrAeqB = addrAltB;
97231   }else if( op==TK_INTERSECT ){
97232     addrAeqB = addrAltB;
97233     addrAltB++;
97234   }else{
97235     VdbeNoopComment((v, "A-eq-B subroutine"));
97236     addrAeqB =
97237     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
97238     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
97239     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
97240   }
97241
97242   /* Generate code to handle the case of A>B
97243   */
97244   VdbeNoopComment((v, "A-gt-B subroutine"));
97245   addrAgtB = sqlite3VdbeCurrentAddr(v);
97246   if( op==TK_ALL || op==TK_UNION ){
97247     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
97248   }
97249   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
97250   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
97251   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
97252
97253   /* This code runs once to initialize everything.
97254   */
97255   sqlite3VdbeJumpHere(v, j1);
97256   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
97257   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
97258   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
97259   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
97260   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
97261   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
97262
97263   /* Implement the main merge loop
97264   */
97265   sqlite3VdbeResolveLabel(v, labelCmpr);
97266   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
97267   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
97268                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
97269   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
97270   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
97271
97272   /* Jump to the this point in order to terminate the query.
97273   */
97274   sqlite3VdbeResolveLabel(v, labelEnd);
97275
97276   /* Set the number of output columns
97277   */
97278   if( pDest->eDest==SRT_Output ){
97279     Select *pFirst = pPrior;
97280     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
97281     generateColumnNames(pParse, 0, pFirst->pEList);
97282   }
97283
97284   /* Reassembly the compound query so that it will be freed correctly
97285   ** by the calling function */
97286   if( p->pPrior ){
97287     sqlite3SelectDelete(db, p->pPrior);
97288   }
97289   p->pPrior = pPrior;
97290
97291   /*** TBD:  Insert subroutine calls to close cursors on incomplete
97292   **** subqueries ****/
97293   explainComposite(pParse, p->op, iSub1, iSub2, 0);
97294   return SQLITE_OK;
97295 }
97296 #endif
97297
97298 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
97299 /* Forward Declarations */
97300 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
97301 static void substSelect(sqlite3*, Select *, int, ExprList *);
97302
97303 /*
97304 ** Scan through the expression pExpr.  Replace every reference to
97305 ** a column in table number iTable with a copy of the iColumn-th
97306 ** entry in pEList.  (But leave references to the ROWID column 
97307 ** unchanged.)
97308 **
97309 ** This routine is part of the flattening procedure.  A subquery
97310 ** whose result set is defined by pEList appears as entry in the
97311 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
97312 ** FORM clause entry is iTable.  This routine make the necessary 
97313 ** changes to pExpr so that it refers directly to the source table
97314 ** of the subquery rather the result set of the subquery.
97315 */
97316 static Expr *substExpr(
97317   sqlite3 *db,        /* Report malloc errors to this connection */
97318   Expr *pExpr,        /* Expr in which substitution occurs */
97319   int iTable,         /* Table to be substituted */
97320   ExprList *pEList    /* Substitute expressions */
97321 ){
97322   if( pExpr==0 ) return 0;
97323   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
97324     if( pExpr->iColumn<0 ){
97325       pExpr->op = TK_NULL;
97326     }else{
97327       Expr *pNew;
97328       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
97329       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
97330       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
97331       sqlite3ExprDelete(db, pExpr);
97332       pExpr = pNew;
97333     }
97334   }else{
97335     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
97336     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
97337     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
97338       substSelect(db, pExpr->x.pSelect, iTable, pEList);
97339     }else{
97340       substExprList(db, pExpr->x.pList, iTable, pEList);
97341     }
97342   }
97343   return pExpr;
97344 }
97345 static void substExprList(
97346   sqlite3 *db,         /* Report malloc errors here */
97347   ExprList *pList,     /* List to scan and in which to make substitutes */
97348   int iTable,          /* Table to be substituted */
97349   ExprList *pEList     /* Substitute values */
97350 ){
97351   int i;
97352   if( pList==0 ) return;
97353   for(i=0; i<pList->nExpr; i++){
97354     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
97355   }
97356 }
97357 static void substSelect(
97358   sqlite3 *db,         /* Report malloc errors here */
97359   Select *p,           /* SELECT statement in which to make substitutions */
97360   int iTable,          /* Table to be replaced */
97361   ExprList *pEList     /* Substitute values */
97362 ){
97363   SrcList *pSrc;
97364   struct SrcList_item *pItem;
97365   int i;
97366   if( !p ) return;
97367   substExprList(db, p->pEList, iTable, pEList);
97368   substExprList(db, p->pGroupBy, iTable, pEList);
97369   substExprList(db, p->pOrderBy, iTable, pEList);
97370   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
97371   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
97372   substSelect(db, p->pPrior, iTable, pEList);
97373   pSrc = p->pSrc;
97374   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
97375   if( ALWAYS(pSrc) ){
97376     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
97377       substSelect(db, pItem->pSelect, iTable, pEList);
97378     }
97379   }
97380 }
97381 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
97382
97383 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
97384 /*
97385 ** This routine attempts to flatten subqueries as a performance optimization.
97386 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
97387 **
97388 ** To understand the concept of flattening, consider the following
97389 ** query:
97390 **
97391 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
97392 **
97393 ** The default way of implementing this query is to execute the
97394 ** subquery first and store the results in a temporary table, then
97395 ** run the outer query on that temporary table.  This requires two
97396 ** passes over the data.  Furthermore, because the temporary table
97397 ** has no indices, the WHERE clause on the outer query cannot be
97398 ** optimized.
97399 **
97400 ** This routine attempts to rewrite queries such as the above into
97401 ** a single flat select, like this:
97402 **
97403 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
97404 **
97405 ** The code generated for this simpification gives the same result
97406 ** but only has to scan the data once.  And because indices might 
97407 ** exist on the table t1, a complete scan of the data might be
97408 ** avoided.
97409 **
97410 ** Flattening is only attempted if all of the following are true:
97411 **
97412 **   (1)  The subquery and the outer query do not both use aggregates.
97413 **
97414 **   (2)  The subquery is not an aggregate or the outer query is not a join.
97415 **
97416 **   (3)  The subquery is not the right operand of a left outer join
97417 **        (Originally ticket #306.  Strengthened by ticket #3300)
97418 **
97419 **   (4)  The subquery is not DISTINCT.
97420 **
97421 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
97422 **        sub-queries that were excluded from this optimization. Restriction 
97423 **        (4) has since been expanded to exclude all DISTINCT subqueries.
97424 **
97425 **   (6)  The subquery does not use aggregates or the outer query is not
97426 **        DISTINCT.
97427 **
97428 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
97429 **        A FROM clause, consider adding a FROM close with the special
97430 **        table sqlite_once that consists of a single row containing a
97431 **        single NULL.
97432 **
97433 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
97434 **
97435 **   (9)  The subquery does not use LIMIT or the outer query does not use
97436 **        aggregates.
97437 **
97438 **  (10)  The subquery does not use aggregates or the outer query does not
97439 **        use LIMIT.
97440 **
97441 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
97442 **
97443 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
97444 **        a separate restriction deriving from ticket #350.
97445 **
97446 **  (13)  The subquery and outer query do not both use LIMIT.
97447 **
97448 **  (14)  The subquery does not use OFFSET.
97449 **
97450 **  (15)  The outer query is not part of a compound select or the
97451 **        subquery does not have a LIMIT clause.
97452 **        (See ticket #2339 and ticket [02a8e81d44]).
97453 **
97454 **  (16)  The outer query is not an aggregate or the subquery does
97455 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
97456 **        until we introduced the group_concat() function.  
97457 **
97458 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
97459 **        compound clause made up entirely of non-aggregate queries, and 
97460 **        the parent query:
97461 **
97462 **          * is not itself part of a compound select,
97463 **          * is not an aggregate or DISTINCT query, and
97464 **          * is not a join
97465 **
97466 **        The parent and sub-query may contain WHERE clauses. Subject to
97467 **        rules (11), (13) and (14), they may also contain ORDER BY,
97468 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
97469 **        operator other than UNION ALL because all the other compound
97470 **        operators have an implied DISTINCT which is disallowed by
97471 **        restriction (4).
97472 **
97473 **        Also, each component of the sub-query must return the same number
97474 **        of result columns. This is actually a requirement for any compound
97475 **        SELECT statement, but all the code here does is make sure that no
97476 **        such (illegal) sub-query is flattened. The caller will detect the
97477 **        syntax error and return a detailed message.
97478 **
97479 **  (18)  If the sub-query is a compound select, then all terms of the
97480 **        ORDER by clause of the parent must be simple references to 
97481 **        columns of the sub-query.
97482 **
97483 **  (19)  The subquery does not use LIMIT or the outer query does not
97484 **        have a WHERE clause.
97485 **
97486 **  (20)  If the sub-query is a compound select, then it must not use
97487 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
97488 **        somewhat by saying that the terms of the ORDER BY clause must
97489 **        appear as unmodified result columns in the outer query.  But we
97490 **        have other optimizations in mind to deal with that case.
97491 **
97492 **  (21)  The subquery does not use LIMIT or the outer query is not
97493 **        DISTINCT.  (See ticket [752e1646fc]).
97494 **
97495 ** In this routine, the "p" parameter is a pointer to the outer query.
97496 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
97497 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
97498 **
97499 ** If flattening is not attempted, this routine is a no-op and returns 0.
97500 ** If flattening is attempted this routine returns 1.
97501 **
97502 ** All of the expression analysis must occur on both the outer query and
97503 ** the subquery before this routine runs.
97504 */
97505 static int flattenSubquery(
97506   Parse *pParse,       /* Parsing context */
97507   Select *p,           /* The parent or outer SELECT statement */
97508   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
97509   int isAgg,           /* True if outer SELECT uses aggregate functions */
97510   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
97511 ){
97512   const char *zSavedAuthContext = pParse->zAuthContext;
97513   Select *pParent;
97514   Select *pSub;       /* The inner query or "subquery" */
97515   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
97516   SrcList *pSrc;      /* The FROM clause of the outer query */
97517   SrcList *pSubSrc;   /* The FROM clause of the subquery */
97518   ExprList *pList;    /* The result set of the outer query */
97519   int iParent;        /* VDBE cursor number of the pSub result set temp table */
97520   int i;              /* Loop counter */
97521   Expr *pWhere;                    /* The WHERE clause */
97522   struct SrcList_item *pSubitem;   /* The subquery */
97523   sqlite3 *db = pParse->db;
97524
97525   /* Check to see if flattening is permitted.  Return 0 if not.
97526   */
97527   assert( p!=0 );
97528   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
97529   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
97530   pSrc = p->pSrc;
97531   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
97532   pSubitem = &pSrc->a[iFrom];
97533   iParent = pSubitem->iCursor;
97534   pSub = pSubitem->pSelect;
97535   assert( pSub!=0 );
97536   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
97537   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
97538   pSubSrc = pSub->pSrc;
97539   assert( pSubSrc );
97540   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
97541   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
97542   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
97543   ** became arbitrary expressions, we were forced to add restrictions (13)
97544   ** and (14). */
97545   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
97546   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
97547   if( p->pRightmost && pSub->pLimit ){
97548     return 0;                                            /* Restriction (15) */
97549   }
97550   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
97551   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
97552   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
97553      return 0;         /* Restrictions (8)(9) */
97554   }
97555   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
97556      return 0;         /* Restriction (6)  */
97557   }
97558   if( p->pOrderBy && pSub->pOrderBy ){
97559      return 0;                                           /* Restriction (11) */
97560   }
97561   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
97562   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
97563   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
97564      return 0;         /* Restriction (21) */
97565   }
97566
97567   /* OBSOLETE COMMENT 1:
97568   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
97569   ** not used as the right operand of an outer join.  Examples of why this
97570   ** is not allowed:
97571   **
97572   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
97573   **
97574   ** If we flatten the above, we would get
97575   **
97576   **         (t1 LEFT OUTER JOIN t2) JOIN t3
97577   **
97578   ** which is not at all the same thing.
97579   **
97580   ** OBSOLETE COMMENT 2:
97581   ** Restriction 12:  If the subquery is the right operand of a left outer
97582   ** join, make sure the subquery has no WHERE clause.
97583   ** An examples of why this is not allowed:
97584   **
97585   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
97586   **
97587   ** If we flatten the above, we would get
97588   **
97589   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
97590   **
97591   ** But the t2.x>0 test will always fail on a NULL row of t2, which
97592   ** effectively converts the OUTER JOIN into an INNER JOIN.
97593   **
97594   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
97595   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
97596   ** is fraught with danger.  Best to avoid the whole thing.  If the
97597   ** subquery is the right term of a LEFT JOIN, then do not flatten.
97598   */
97599   if( (pSubitem->jointype & JT_OUTER)!=0 ){
97600     return 0;
97601   }
97602
97603   /* Restriction 17: If the sub-query is a compound SELECT, then it must
97604   ** use only the UNION ALL operator. And none of the simple select queries
97605   ** that make up the compound SELECT are allowed to be aggregate or distinct
97606   ** queries.
97607   */
97608   if( pSub->pPrior ){
97609     if( pSub->pOrderBy ){
97610       return 0;  /* Restriction 20 */
97611     }
97612     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
97613       return 0;
97614     }
97615     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
97616       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
97617       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
97618       assert( pSub->pSrc!=0 );
97619       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
97620        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
97621        || pSub1->pSrc->nSrc<1
97622        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
97623       ){
97624         return 0;
97625       }
97626       testcase( pSub1->pSrc->nSrc>1 );
97627     }
97628
97629     /* Restriction 18. */
97630     if( p->pOrderBy ){
97631       int ii;
97632       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
97633         if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
97634       }
97635     }
97636   }
97637
97638   /***** If we reach this point, flattening is permitted. *****/
97639
97640   /* Authorize the subquery */
97641   pParse->zAuthContext = pSubitem->zName;
97642   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
97643   testcase( i==SQLITE_DENY );
97644   pParse->zAuthContext = zSavedAuthContext;
97645
97646   /* If the sub-query is a compound SELECT statement, then (by restrictions
97647   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
97648   ** be of the form:
97649   **
97650   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
97651   **
97652   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
97653   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
97654   ** OFFSET clauses and joins them to the left-hand-side of the original
97655   ** using UNION ALL operators. In this case N is the number of simple
97656   ** select statements in the compound sub-query.
97657   **
97658   ** Example:
97659   **
97660   **     SELECT a+1 FROM (
97661   **        SELECT x FROM tab
97662   **        UNION ALL
97663   **        SELECT y FROM tab
97664   **        UNION ALL
97665   **        SELECT abs(z*2) FROM tab2
97666   **     ) WHERE a!=5 ORDER BY 1
97667   **
97668   ** Transformed into:
97669   **
97670   **     SELECT x+1 FROM tab WHERE x+1!=5
97671   **     UNION ALL
97672   **     SELECT y+1 FROM tab WHERE y+1!=5
97673   **     UNION ALL
97674   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
97675   **     ORDER BY 1
97676   **
97677   ** We call this the "compound-subquery flattening".
97678   */
97679   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
97680     Select *pNew;
97681     ExprList *pOrderBy = p->pOrderBy;
97682     Expr *pLimit = p->pLimit;
97683     Expr *pOffset = p->pOffset;
97684     Select *pPrior = p->pPrior;
97685     p->pOrderBy = 0;
97686     p->pSrc = 0;
97687     p->pPrior = 0;
97688     p->pLimit = 0;
97689     p->pOffset = 0;
97690     pNew = sqlite3SelectDup(db, p, 0);
97691     p->pOffset = pOffset;
97692     p->pLimit = pLimit;
97693     p->pOrderBy = pOrderBy;
97694     p->pSrc = pSrc;
97695     p->op = TK_ALL;
97696     p->pRightmost = 0;
97697     if( pNew==0 ){
97698       pNew = pPrior;
97699     }else{
97700       pNew->pPrior = pPrior;
97701       pNew->pRightmost = 0;
97702     }
97703     p->pPrior = pNew;
97704     if( db->mallocFailed ) return 1;
97705   }
97706
97707   /* Begin flattening the iFrom-th entry of the FROM clause 
97708   ** in the outer query.
97709   */
97710   pSub = pSub1 = pSubitem->pSelect;
97711
97712   /* Delete the transient table structure associated with the
97713   ** subquery
97714   */
97715   sqlite3DbFree(db, pSubitem->zDatabase);
97716   sqlite3DbFree(db, pSubitem->zName);
97717   sqlite3DbFree(db, pSubitem->zAlias);
97718   pSubitem->zDatabase = 0;
97719   pSubitem->zName = 0;
97720   pSubitem->zAlias = 0;
97721   pSubitem->pSelect = 0;
97722
97723   /* Defer deleting the Table object associated with the
97724   ** subquery until code generation is
97725   ** complete, since there may still exist Expr.pTab entries that
97726   ** refer to the subquery even after flattening.  Ticket #3346.
97727   **
97728   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
97729   */
97730   if( ALWAYS(pSubitem->pTab!=0) ){
97731     Table *pTabToDel = pSubitem->pTab;
97732     if( pTabToDel->nRef==1 ){
97733       Parse *pToplevel = sqlite3ParseToplevel(pParse);
97734       pTabToDel->pNextZombie = pToplevel->pZombieTab;
97735       pToplevel->pZombieTab = pTabToDel;
97736     }else{
97737       pTabToDel->nRef--;
97738     }
97739     pSubitem->pTab = 0;
97740   }
97741
97742   /* The following loop runs once for each term in a compound-subquery
97743   ** flattening (as described above).  If we are doing a different kind
97744   ** of flattening - a flattening other than a compound-subquery flattening -
97745   ** then this loop only runs once.
97746   **
97747   ** This loop moves all of the FROM elements of the subquery into the
97748   ** the FROM clause of the outer query.  Before doing this, remember
97749   ** the cursor number for the original outer query FROM element in
97750   ** iParent.  The iParent cursor will never be used.  Subsequent code
97751   ** will scan expressions looking for iParent references and replace
97752   ** those references with expressions that resolve to the subquery FROM
97753   ** elements we are now copying in.
97754   */
97755   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
97756     int nSubSrc;
97757     u8 jointype = 0;
97758     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
97759     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
97760     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
97761
97762     if( pSrc ){
97763       assert( pParent==p );  /* First time through the loop */
97764       jointype = pSubitem->jointype;
97765     }else{
97766       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
97767       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
97768       if( pSrc==0 ){
97769         assert( db->mallocFailed );
97770         break;
97771       }
97772     }
97773
97774     /* The subquery uses a single slot of the FROM clause of the outer
97775     ** query.  If the subquery has more than one element in its FROM clause,
97776     ** then expand the outer query to make space for it to hold all elements
97777     ** of the subquery.
97778     **
97779     ** Example:
97780     **
97781     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
97782     **
97783     ** The outer query has 3 slots in its FROM clause.  One slot of the
97784     ** outer query (the middle slot) is used by the subquery.  The next
97785     ** block of code will expand the out query to 4 slots.  The middle
97786     ** slot is expanded to two slots in order to make space for the
97787     ** two elements in the FROM clause of the subquery.
97788     */
97789     if( nSubSrc>1 ){
97790       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
97791       if( db->mallocFailed ){
97792         break;
97793       }
97794     }
97795
97796     /* Transfer the FROM clause terms from the subquery into the
97797     ** outer query.
97798     */
97799     for(i=0; i<nSubSrc; i++){
97800       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
97801       pSrc->a[i+iFrom] = pSubSrc->a[i];
97802       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
97803     }
97804     pSrc->a[iFrom].jointype = jointype;
97805   
97806     /* Now begin substituting subquery result set expressions for 
97807     ** references to the iParent in the outer query.
97808     ** 
97809     ** Example:
97810     **
97811     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
97812     **   \                     \_____________ subquery __________/          /
97813     **    \_____________________ outer query ______________________________/
97814     **
97815     ** We look at every expression in the outer query and every place we see
97816     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
97817     */
97818     pList = pParent->pEList;
97819     for(i=0; i<pList->nExpr; i++){
97820       if( pList->a[i].zName==0 ){
97821         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
97822         sqlite3Dequote(zName);
97823         pList->a[i].zName = zName;
97824       }
97825     }
97826     substExprList(db, pParent->pEList, iParent, pSub->pEList);
97827     if( isAgg ){
97828       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
97829       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97830     }
97831     if( pSub->pOrderBy ){
97832       assert( pParent->pOrderBy==0 );
97833       pParent->pOrderBy = pSub->pOrderBy;
97834       pSub->pOrderBy = 0;
97835     }else if( pParent->pOrderBy ){
97836       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
97837     }
97838     if( pSub->pWhere ){
97839       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
97840     }else{
97841       pWhere = 0;
97842     }
97843     if( subqueryIsAgg ){
97844       assert( pParent->pHaving==0 );
97845       pParent->pHaving = pParent->pWhere;
97846       pParent->pWhere = pWhere;
97847       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97848       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
97849                                   sqlite3ExprDup(db, pSub->pHaving, 0));
97850       assert( pParent->pGroupBy==0 );
97851       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
97852     }else{
97853       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
97854       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
97855     }
97856   
97857     /* The flattened query is distinct if either the inner or the
97858     ** outer query is distinct. 
97859     */
97860     pParent->selFlags |= pSub->selFlags & SF_Distinct;
97861   
97862     /*
97863     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
97864     **
97865     ** One is tempted to try to add a and b to combine the limits.  But this
97866     ** does not work if either limit is negative.
97867     */
97868     if( pSub->pLimit ){
97869       pParent->pLimit = pSub->pLimit;
97870       pSub->pLimit = 0;
97871     }
97872   }
97873
97874   /* Finially, delete what is left of the subquery and return
97875   ** success.
97876   */
97877   sqlite3SelectDelete(db, pSub1);
97878
97879   return 1;
97880 }
97881 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
97882
97883 /*
97884 ** Based on the contents of the AggInfo structure indicated by the first
97885 ** argument, this function checks if the following are true:
97886 **
97887 **    * the query contains just a single aggregate function,
97888 **    * the aggregate function is either min() or max(), and
97889 **    * the argument to the aggregate function is a column value.
97890 **
97891 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
97892 ** is returned as appropriate. Also, *ppMinMax is set to point to the 
97893 ** list of arguments passed to the aggregate before returning.
97894 **
97895 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
97896 ** WHERE_ORDERBY_NORMAL is returned.
97897 */
97898 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
97899   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
97900
97901   *ppMinMax = 0;
97902   if( pAggInfo->nFunc==1 ){
97903     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
97904     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
97905
97906     assert( pExpr->op==TK_AGG_FUNCTION );
97907     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
97908       const char *zFunc = pExpr->u.zToken;
97909       if( sqlite3StrICmp(zFunc, "min")==0 ){
97910         eRet = WHERE_ORDERBY_MIN;
97911         *ppMinMax = pEList;
97912       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
97913         eRet = WHERE_ORDERBY_MAX;
97914         *ppMinMax = pEList;
97915       }
97916     }
97917   }
97918
97919   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
97920   return eRet;
97921 }
97922
97923 /*
97924 ** The select statement passed as the first argument is an aggregate query.
97925 ** The second argment is the associated aggregate-info object. This 
97926 ** function tests if the SELECT is of the form:
97927 **
97928 **   SELECT count(*) FROM <tbl>
97929 **
97930 ** where table is a database table, not a sub-select or view. If the query
97931 ** does match this pattern, then a pointer to the Table object representing
97932 ** <tbl> is returned. Otherwise, 0 is returned.
97933 */
97934 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
97935   Table *pTab;
97936   Expr *pExpr;
97937
97938   assert( !p->pGroupBy );
97939
97940   if( p->pWhere || p->pEList->nExpr!=1 
97941    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
97942   ){
97943     return 0;
97944   }
97945   pTab = p->pSrc->a[0].pTab;
97946   pExpr = p->pEList->a[0].pExpr;
97947   assert( pTab && !pTab->pSelect && pExpr );
97948
97949   if( IsVirtual(pTab) ) return 0;
97950   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
97951   if( NEVER(pAggInfo->nFunc==0) ) return 0;
97952   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
97953   if( pExpr->flags&EP_Distinct ) return 0;
97954
97955   return pTab;
97956 }
97957
97958 /*
97959 ** If the source-list item passed as an argument was augmented with an
97960 ** INDEXED BY clause, then try to locate the specified index. If there
97961 ** was such a clause and the named index cannot be found, return 
97962 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
97963 ** pFrom->pIndex and return SQLITE_OK.
97964 */
97965 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
97966   if( pFrom->pTab && pFrom->zIndex ){
97967     Table *pTab = pFrom->pTab;
97968     char *zIndex = pFrom->zIndex;
97969     Index *pIdx;
97970     for(pIdx=pTab->pIndex; 
97971         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
97972         pIdx=pIdx->pNext
97973     );
97974     if( !pIdx ){
97975       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
97976       pParse->checkSchema = 1;
97977       return SQLITE_ERROR;
97978     }
97979     pFrom->pIndex = pIdx;
97980   }
97981   return SQLITE_OK;
97982 }
97983
97984 /*
97985 ** This routine is a Walker callback for "expanding" a SELECT statement.
97986 ** "Expanding" means to do the following:
97987 **
97988 **    (1)  Make sure VDBE cursor numbers have been assigned to every
97989 **         element of the FROM clause.
97990 **
97991 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
97992 **         defines FROM clause.  When views appear in the FROM clause,
97993 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
97994 **         that implements the view.  A copy is made of the view's SELECT
97995 **         statement so that we can freely modify or delete that statement
97996 **         without worrying about messing up the presistent representation
97997 **         of the view.
97998 **
97999 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
98000 **         on joins and the ON and USING clause of joins.
98001 **
98002 **    (4)  Scan the list of columns in the result set (pEList) looking
98003 **         for instances of the "*" operator or the TABLE.* operator.
98004 **         If found, expand each "*" to be every column in every table
98005 **         and TABLE.* to be every column in TABLE.
98006 **
98007 */
98008 static int selectExpander(Walker *pWalker, Select *p){
98009   Parse *pParse = pWalker->pParse;
98010   int i, j, k;
98011   SrcList *pTabList;
98012   ExprList *pEList;
98013   struct SrcList_item *pFrom;
98014   sqlite3 *db = pParse->db;
98015   Expr *pE, *pRight, *pExpr;
98016   u16 selFlags = p->selFlags;
98017
98018   p->selFlags |= SF_Expanded;
98019   if( db->mallocFailed  ){
98020     return WRC_Abort;
98021   }
98022   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
98023     return WRC_Prune;
98024   }
98025   pTabList = p->pSrc;
98026   pEList = p->pEList;
98027
98028   /* Make sure cursor numbers have been assigned to all entries in
98029   ** the FROM clause of the SELECT statement.
98030   */
98031   sqlite3SrcListAssignCursors(pParse, pTabList);
98032
98033   /* Look up every table named in the FROM clause of the select.  If
98034   ** an entry of the FROM clause is a subquery instead of a table or view,
98035   ** then create a transient table structure to describe the subquery.
98036   */
98037   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
98038     Table *pTab;
98039     if( pFrom->pTab!=0 ){
98040       /* This statement has already been prepared.  There is no need
98041       ** to go further. */
98042       assert( i==0 );
98043       return WRC_Prune;
98044     }
98045     if( pFrom->zName==0 ){
98046 #ifndef SQLITE_OMIT_SUBQUERY
98047       Select *pSel = pFrom->pSelect;
98048       /* A sub-query in the FROM clause of a SELECT */
98049       assert( pSel!=0 );
98050       assert( pFrom->pTab==0 );
98051       sqlite3WalkSelect(pWalker, pSel);
98052       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
98053       if( pTab==0 ) return WRC_Abort;
98054       pTab->nRef = 1;
98055       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
98056       while( pSel->pPrior ){ pSel = pSel->pPrior; }
98057       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
98058       pTab->iPKey = -1;
98059       pTab->nRowEst = 1000000;
98060       pTab->tabFlags |= TF_Ephemeral;
98061 #endif
98062     }else{
98063       /* An ordinary table or view name in the FROM clause */
98064       assert( pFrom->pTab==0 );
98065       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
98066       if( pTab==0 ) return WRC_Abort;
98067       if( pTab->nRef==0xffff ){
98068         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
98069            pTab->zName);
98070         pFrom->pTab = 0;
98071         return WRC_Abort;
98072       }
98073       pTab->nRef++;
98074 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
98075       if( pTab->pSelect || IsVirtual(pTab) ){
98076         /* We reach here if the named table is a really a view */
98077         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
98078         assert( pFrom->pSelect==0 );
98079         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
98080         sqlite3WalkSelect(pWalker, pFrom->pSelect);
98081       }
98082 #endif
98083     }
98084
98085     /* Locate the index named by the INDEXED BY clause, if any. */
98086     if( sqlite3IndexedByLookup(pParse, pFrom) ){
98087       return WRC_Abort;
98088     }
98089   }
98090
98091   /* Process NATURAL keywords, and ON and USING clauses of joins.
98092   */
98093   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
98094     return WRC_Abort;
98095   }
98096
98097   /* For every "*" that occurs in the column list, insert the names of
98098   ** all columns in all tables.  And for every TABLE.* insert the names
98099   ** of all columns in TABLE.  The parser inserted a special expression
98100   ** with the TK_ALL operator for each "*" that it found in the column list.
98101   ** The following code just has to locate the TK_ALL expressions and expand
98102   ** each one to the list of all columns in all tables.
98103   **
98104   ** The first loop just checks to see if there are any "*" operators
98105   ** that need expanding.
98106   */
98107   for(k=0; k<pEList->nExpr; k++){
98108     pE = pEList->a[k].pExpr;
98109     if( pE->op==TK_ALL ) break;
98110     assert( pE->op!=TK_DOT || pE->pRight!=0 );
98111     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
98112     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
98113   }
98114   if( k<pEList->nExpr ){
98115     /*
98116     ** If we get here it means the result set contains one or more "*"
98117     ** operators that need to be expanded.  Loop through each expression
98118     ** in the result set and expand them one by one.
98119     */
98120     struct ExprList_item *a = pEList->a;
98121     ExprList *pNew = 0;
98122     int flags = pParse->db->flags;
98123     int longNames = (flags & SQLITE_FullColNames)!=0
98124                       && (flags & SQLITE_ShortColNames)==0;
98125
98126     /* When processing FROM-clause subqueries, it is always the case
98127     ** that full_column_names=OFF and short_column_names=ON.  The
98128     ** sqlite3ResultSetOfSelect() routine makes it so. */
98129     assert( (p->selFlags & SF_NestedFrom)==0
98130           || ((flags & SQLITE_FullColNames)==0 &&
98131               (flags & SQLITE_ShortColNames)!=0) );
98132
98133     for(k=0; k<pEList->nExpr; k++){
98134       pE = a[k].pExpr;
98135       pRight = pE->pRight;
98136       assert( pE->op!=TK_DOT || pRight!=0 );
98137       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
98138         /* This particular expression does not need to be expanded.
98139         */
98140         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
98141         if( pNew ){
98142           pNew->a[pNew->nExpr-1].zName = a[k].zName;
98143           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
98144           a[k].zName = 0;
98145           a[k].zSpan = 0;
98146         }
98147         a[k].pExpr = 0;
98148       }else{
98149         /* This expression is a "*" or a "TABLE.*" and needs to be
98150         ** expanded. */
98151         int tableSeen = 0;      /* Set to 1 when TABLE matches */
98152         char *zTName = 0;       /* text of name of TABLE */
98153         if( pE->op==TK_DOT ){
98154           assert( pE->pLeft!=0 );
98155           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
98156           zTName = pE->pLeft->u.zToken;
98157         }
98158         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
98159           Table *pTab = pFrom->pTab;
98160           Select *pSub = pFrom->pSelect;
98161           char *zTabName = pFrom->zAlias;
98162           const char *zSchemaName = 0;
98163           int iDb;
98164           if( zTabName==0 ){
98165             zTabName = pTab->zName;
98166           }
98167           if( db->mallocFailed ) break;
98168           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
98169             pSub = 0;
98170             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
98171               continue;
98172             }
98173             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
98174             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
98175           }
98176           for(j=0; j<pTab->nCol; j++){
98177             char *zName = pTab->aCol[j].zName;
98178             char *zColname;  /* The computed column name */
98179             char *zToFree;   /* Malloced string that needs to be freed */
98180             Token sColname;  /* Computed column name as a token */
98181
98182             assert( zName );
98183             if( zTName && pSub
98184              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
98185             ){
98186               continue;
98187             }
98188
98189             /* If a column is marked as 'hidden' (currently only possible
98190             ** for virtual tables), do not include it in the expanded
98191             ** result-set list.
98192             */
98193             if( IsHiddenColumn(&pTab->aCol[j]) ){
98194               assert(IsVirtual(pTab));
98195               continue;
98196             }
98197             tableSeen = 1;
98198
98199             if( i>0 && zTName==0 ){
98200               if( (pFrom->jointype & JT_NATURAL)!=0
98201                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
98202               ){
98203                 /* In a NATURAL join, omit the join columns from the 
98204                 ** table to the right of the join */
98205                 continue;
98206               }
98207               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
98208                 /* In a join with a USING clause, omit columns in the
98209                 ** using clause from the table on the right. */
98210                 continue;
98211               }
98212             }
98213             pRight = sqlite3Expr(db, TK_ID, zName);
98214             zColname = zName;
98215             zToFree = 0;
98216             if( longNames || pTabList->nSrc>1 ){
98217               Expr *pLeft;
98218               pLeft = sqlite3Expr(db, TK_ID, zTabName);
98219               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
98220               if( zSchemaName ){
98221                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
98222                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
98223               }
98224               if( longNames ){
98225                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
98226                 zToFree = zColname;
98227               }
98228             }else{
98229               pExpr = pRight;
98230             }
98231             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
98232             sColname.z = zColname;
98233             sColname.n = sqlite3Strlen30(zColname);
98234             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
98235             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
98236               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
98237               if( pSub ){
98238                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
98239                 testcase( pX->zSpan==0 );
98240               }else{
98241                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
98242                                            zSchemaName, zTabName, zColname);
98243                 testcase( pX->zSpan==0 );
98244               }
98245               pX->bSpanIsTab = 1;
98246             }
98247             sqlite3DbFree(db, zToFree);
98248           }
98249         }
98250         if( !tableSeen ){
98251           if( zTName ){
98252             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
98253           }else{
98254             sqlite3ErrorMsg(pParse, "no tables specified");
98255           }
98256         }
98257       }
98258     }
98259     sqlite3ExprListDelete(db, pEList);
98260     p->pEList = pNew;
98261   }
98262 #if SQLITE_MAX_COLUMN
98263   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
98264     sqlite3ErrorMsg(pParse, "too many columns in result set");
98265   }
98266 #endif
98267   return WRC_Continue;
98268 }
98269
98270 /*
98271 ** No-op routine for the parse-tree walker.
98272 **
98273 ** When this routine is the Walker.xExprCallback then expression trees
98274 ** are walked without any actions being taken at each node.  Presumably,
98275 ** when this routine is used for Walker.xExprCallback then 
98276 ** Walker.xSelectCallback is set to do something useful for every 
98277 ** subquery in the parser tree.
98278 */
98279 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
98280   UNUSED_PARAMETER2(NotUsed, NotUsed2);
98281   return WRC_Continue;
98282 }
98283
98284 /*
98285 ** This routine "expands" a SELECT statement and all of its subqueries.
98286 ** For additional information on what it means to "expand" a SELECT
98287 ** statement, see the comment on the selectExpand worker callback above.
98288 **
98289 ** Expanding a SELECT statement is the first step in processing a
98290 ** SELECT statement.  The SELECT statement must be expanded before
98291 ** name resolution is performed.
98292 **
98293 ** If anything goes wrong, an error message is written into pParse.
98294 ** The calling function can detect the problem by looking at pParse->nErr
98295 ** and/or pParse->db->mallocFailed.
98296 */
98297 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
98298   Walker w;
98299   w.xSelectCallback = selectExpander;
98300   w.xExprCallback = exprWalkNoop;
98301   w.pParse = pParse;
98302   sqlite3WalkSelect(&w, pSelect);
98303 }
98304
98305
98306 #ifndef SQLITE_OMIT_SUBQUERY
98307 /*
98308 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
98309 ** interface.
98310 **
98311 ** For each FROM-clause subquery, add Column.zType and Column.zColl
98312 ** information to the Table structure that represents the result set
98313 ** of that subquery.
98314 **
98315 ** The Table structure that represents the result set was constructed
98316 ** by selectExpander() but the type and collation information was omitted
98317 ** at that point because identifiers had not yet been resolved.  This
98318 ** routine is called after identifier resolution.
98319 */
98320 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
98321   Parse *pParse;
98322   int i;
98323   SrcList *pTabList;
98324   struct SrcList_item *pFrom;
98325
98326   assert( p->selFlags & SF_Resolved );
98327   if( (p->selFlags & SF_HasTypeInfo)==0 ){
98328     p->selFlags |= SF_HasTypeInfo;
98329     pParse = pWalker->pParse;
98330     pTabList = p->pSrc;
98331     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
98332       Table *pTab = pFrom->pTab;
98333       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
98334         /* A sub-query in the FROM clause of a SELECT */
98335         Select *pSel = pFrom->pSelect;
98336         assert( pSel );
98337         while( pSel->pPrior ) pSel = pSel->pPrior;
98338         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
98339       }
98340     }
98341   }
98342   return WRC_Continue;
98343 }
98344 #endif
98345
98346
98347 /*
98348 ** This routine adds datatype and collating sequence information to
98349 ** the Table structures of all FROM-clause subqueries in a
98350 ** SELECT statement.
98351 **
98352 ** Use this routine after name resolution.
98353 */
98354 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
98355 #ifndef SQLITE_OMIT_SUBQUERY
98356   Walker w;
98357   w.xSelectCallback = selectAddSubqueryTypeInfo;
98358   w.xExprCallback = exprWalkNoop;
98359   w.pParse = pParse;
98360   sqlite3WalkSelect(&w, pSelect);
98361 #endif
98362 }
98363
98364
98365 /*
98366 ** This routine sets up a SELECT statement for processing.  The
98367 ** following is accomplished:
98368 **
98369 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
98370 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
98371 **     *  ON and USING clauses are shifted into WHERE statements
98372 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
98373 **     *  Identifiers in expression are matched to tables.
98374 **
98375 ** This routine acts recursively on all subqueries within the SELECT.
98376 */
98377 SQLITE_PRIVATE void sqlite3SelectPrep(
98378   Parse *pParse,         /* The parser context */
98379   Select *p,             /* The SELECT statement being coded. */
98380   NameContext *pOuterNC  /* Name context for container */
98381 ){
98382   sqlite3 *db;
98383   if( NEVER(p==0) ) return;
98384   db = pParse->db;
98385   if( db->mallocFailed ) return;
98386   if( p->selFlags & SF_HasTypeInfo ) return;
98387   sqlite3SelectExpand(pParse, p);
98388   if( pParse->nErr || db->mallocFailed ) return;
98389   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
98390   if( pParse->nErr || db->mallocFailed ) return;
98391   sqlite3SelectAddTypeInfo(pParse, p);
98392 }
98393
98394 /*
98395 ** Reset the aggregate accumulator.
98396 **
98397 ** The aggregate accumulator is a set of memory cells that hold
98398 ** intermediate results while calculating an aggregate.  This
98399 ** routine generates code that stores NULLs in all of those memory
98400 ** cells.
98401 */
98402 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
98403   Vdbe *v = pParse->pVdbe;
98404   int i;
98405   struct AggInfo_func *pFunc;
98406   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
98407     return;
98408   }
98409   for(i=0; i<pAggInfo->nColumn; i++){
98410     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
98411   }
98412   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
98413     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
98414     if( pFunc->iDistinct>=0 ){
98415       Expr *pE = pFunc->pExpr;
98416       assert( !ExprHasProperty(pE, EP_xIsSelect) );
98417       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
98418         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
98419            "argument");
98420         pFunc->iDistinct = -1;
98421       }else{
98422         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
98423         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
98424                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98425       }
98426     }
98427   }
98428 }
98429
98430 /*
98431 ** Invoke the OP_AggFinalize opcode for every aggregate function
98432 ** in the AggInfo structure.
98433 */
98434 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
98435   Vdbe *v = pParse->pVdbe;
98436   int i;
98437   struct AggInfo_func *pF;
98438   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
98439     ExprList *pList = pF->pExpr->x.pList;
98440     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
98441     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
98442                       (void*)pF->pFunc, P4_FUNCDEF);
98443   }
98444 }
98445
98446 /*
98447 ** Update the accumulator memory cells for an aggregate based on
98448 ** the current cursor position.
98449 */
98450 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
98451   Vdbe *v = pParse->pVdbe;
98452   int i;
98453   int regHit = 0;
98454   int addrHitTest = 0;
98455   struct AggInfo_func *pF;
98456   struct AggInfo_col *pC;
98457
98458   pAggInfo->directMode = 1;
98459   sqlite3ExprCacheClear(pParse);
98460   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
98461     int nArg;
98462     int addrNext = 0;
98463     int regAgg;
98464     ExprList *pList = pF->pExpr->x.pList;
98465     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
98466     if( pList ){
98467       nArg = pList->nExpr;
98468       regAgg = sqlite3GetTempRange(pParse, nArg);
98469       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
98470     }else{
98471       nArg = 0;
98472       regAgg = 0;
98473     }
98474     if( pF->iDistinct>=0 ){
98475       addrNext = sqlite3VdbeMakeLabel(v);
98476       assert( nArg==1 );
98477       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
98478     }
98479     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
98480       CollSeq *pColl = 0;
98481       struct ExprList_item *pItem;
98482       int j;
98483       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
98484       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
98485         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
98486       }
98487       if( !pColl ){
98488         pColl = pParse->db->pDfltColl;
98489       }
98490       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
98491       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
98492     }
98493     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
98494                       (void*)pF->pFunc, P4_FUNCDEF);
98495     sqlite3VdbeChangeP5(v, (u8)nArg);
98496     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
98497     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
98498     if( addrNext ){
98499       sqlite3VdbeResolveLabel(v, addrNext);
98500       sqlite3ExprCacheClear(pParse);
98501     }
98502   }
98503
98504   /* Before populating the accumulator registers, clear the column cache.
98505   ** Otherwise, if any of the required column values are already present 
98506   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
98507   ** to pC->iMem. But by the time the value is used, the original register
98508   ** may have been used, invalidating the underlying buffer holding the
98509   ** text or blob value. See ticket [883034dcb5].
98510   **
98511   ** Another solution would be to change the OP_SCopy used to copy cached
98512   ** values to an OP_Copy.
98513   */
98514   if( regHit ){
98515     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
98516   }
98517   sqlite3ExprCacheClear(pParse);
98518   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
98519     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
98520   }
98521   pAggInfo->directMode = 0;
98522   sqlite3ExprCacheClear(pParse);
98523   if( addrHitTest ){
98524     sqlite3VdbeJumpHere(v, addrHitTest);
98525   }
98526 }
98527
98528 /*
98529 ** Add a single OP_Explain instruction to the VDBE to explain a simple
98530 ** count(*) query ("SELECT count(*) FROM pTab").
98531 */
98532 #ifndef SQLITE_OMIT_EXPLAIN
98533 static void explainSimpleCount(
98534   Parse *pParse,                  /* Parse context */
98535   Table *pTab,                    /* Table being queried */
98536   Index *pIdx                     /* Index used to optimize scan, or NULL */
98537 ){
98538   if( pParse->explain==2 ){
98539     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
98540         pTab->zName, 
98541         pIdx ? "USING COVERING INDEX " : "",
98542         pIdx ? pIdx->zName : "",
98543         pTab->nRowEst
98544     );
98545     sqlite3VdbeAddOp4(
98546         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
98547     );
98548   }
98549 }
98550 #else
98551 # define explainSimpleCount(a,b,c)
98552 #endif
98553
98554 /*
98555 ** Generate code for the SELECT statement given in the p argument.  
98556 **
98557 ** The results are distributed in various ways depending on the
98558 ** contents of the SelectDest structure pointed to by argument pDest
98559 ** as follows:
98560 **
98561 **     pDest->eDest    Result
98562 **     ------------    -------------------------------------------
98563 **     SRT_Output      Generate a row of output (using the OP_ResultRow
98564 **                     opcode) for each row in the result set.
98565 **
98566 **     SRT_Mem         Only valid if the result is a single column.
98567 **                     Store the first column of the first result row
98568 **                     in register pDest->iSDParm then abandon the rest
98569 **                     of the query.  This destination implies "LIMIT 1".
98570 **
98571 **     SRT_Set         The result must be a single column.  Store each
98572 **                     row of result as the key in table pDest->iSDParm. 
98573 **                     Apply the affinity pDest->affSdst before storing
98574 **                     results.  Used to implement "IN (SELECT ...)".
98575 **
98576 **     SRT_Union       Store results as a key in a temporary table 
98577 **                     identified by pDest->iSDParm.
98578 **
98579 **     SRT_Except      Remove results from the temporary table pDest->iSDParm.
98580 **
98581 **     SRT_Table       Store results in temporary table pDest->iSDParm.
98582 **                     This is like SRT_EphemTab except that the table
98583 **                     is assumed to already be open.
98584 **
98585 **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
98586 **                     the result there. The cursor is left open after
98587 **                     returning.  This is like SRT_Table except that
98588 **                     this destination uses OP_OpenEphemeral to create
98589 **                     the table first.
98590 **
98591 **     SRT_Coroutine   Generate a co-routine that returns a new row of
98592 **                     results each time it is invoked.  The entry point
98593 **                     of the co-routine is stored in register pDest->iSDParm.
98594 **
98595 **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
98596 **                     set is not empty.
98597 **
98598 **     SRT_Discard     Throw the results away.  This is used by SELECT
98599 **                     statements within triggers whose only purpose is
98600 **                     the side-effects of functions.
98601 **
98602 ** This routine returns the number of errors.  If any errors are
98603 ** encountered, then an appropriate error message is left in
98604 ** pParse->zErrMsg.
98605 **
98606 ** This routine does NOT free the Select structure passed in.  The
98607 ** calling function needs to do that.
98608 */
98609 SQLITE_PRIVATE int sqlite3Select(
98610   Parse *pParse,         /* The parser context */
98611   Select *p,             /* The SELECT statement being coded. */
98612   SelectDest *pDest      /* What to do with the query results */
98613 ){
98614   int i, j;              /* Loop counters */
98615   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
98616   Vdbe *v;               /* The virtual machine under construction */
98617   int isAgg;             /* True for select lists like "count(*)" */
98618   ExprList *pEList;      /* List of columns to extract. */
98619   SrcList *pTabList;     /* List of tables to select from */
98620   Expr *pWhere;          /* The WHERE clause.  May be NULL */
98621   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
98622   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
98623   Expr *pHaving;         /* The HAVING clause.  May be NULL */
98624   int rc = 1;            /* Value to return from this function */
98625   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
98626   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
98627   AggInfo sAggInfo;      /* Information used by aggregate queries */
98628   int iEnd;              /* Address of the end of the query */
98629   sqlite3 *db;           /* The database connection */
98630
98631 #ifndef SQLITE_OMIT_EXPLAIN
98632   int iRestoreSelectId = pParse->iSelectId;
98633   pParse->iSelectId = pParse->iNextSelectId++;
98634 #endif
98635
98636   db = pParse->db;
98637   if( p==0 || db->mallocFailed || pParse->nErr ){
98638     return 1;
98639   }
98640   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
98641   memset(&sAggInfo, 0, sizeof(sAggInfo));
98642
98643   if( IgnorableOrderby(pDest) ){
98644     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
98645            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
98646     /* If ORDER BY makes no difference in the output then neither does
98647     ** DISTINCT so it can be removed too. */
98648     sqlite3ExprListDelete(db, p->pOrderBy);
98649     p->pOrderBy = 0;
98650     p->selFlags &= ~SF_Distinct;
98651   }
98652   sqlite3SelectPrep(pParse, p, 0);
98653   pOrderBy = p->pOrderBy;
98654   pTabList = p->pSrc;
98655   pEList = p->pEList;
98656   if( pParse->nErr || db->mallocFailed ){
98657     goto select_end;
98658   }
98659   isAgg = (p->selFlags & SF_Aggregate)!=0;
98660   assert( pEList!=0 );
98661
98662   /* Begin generating code.
98663   */
98664   v = sqlite3GetVdbe(pParse);
98665   if( v==0 ) goto select_end;
98666
98667   /* If writing to memory or generating a set
98668   ** only a single column may be output.
98669   */
98670 #ifndef SQLITE_OMIT_SUBQUERY
98671   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
98672     goto select_end;
98673   }
98674 #endif
98675
98676   /* Generate code for all sub-queries in the FROM clause
98677   */
98678 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98679   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
98680     struct SrcList_item *pItem = &pTabList->a[i];
98681     SelectDest dest;
98682     Select *pSub = pItem->pSelect;
98683     int isAggSub;
98684
98685     if( pSub==0 ) continue;
98686
98687     /* Sometimes the code for a subquery will be generated more than
98688     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
98689     ** for example.  In that case, do not regenerate the code to manifest
98690     ** a view or the co-routine to implement a view.  The first instance
98691     ** is sufficient, though the subroutine to manifest the view does need
98692     ** to be invoked again. */
98693     if( pItem->addrFillSub ){
98694       if( pItem->viaCoroutine==0 ){
98695         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
98696       }
98697       continue;
98698     }
98699
98700     /* Increment Parse.nHeight by the height of the largest expression
98701     ** tree refered to by this, the parent select. The child select
98702     ** may contain expression trees of at most
98703     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
98704     ** more conservative than necessary, but much easier than enforcing
98705     ** an exact limit.
98706     */
98707     pParse->nHeight += sqlite3SelectExprHeight(p);
98708
98709     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
98710     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
98711       /* This subquery can be absorbed into its parent. */
98712       if( isAggSub ){
98713         isAgg = 1;
98714         p->selFlags |= SF_Aggregate;
98715       }
98716       i = -1;
98717     }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
98718       && OptimizationEnabled(db, SQLITE_SubqCoroutine)
98719     ){
98720       /* Implement a co-routine that will return a single row of the result
98721       ** set on each invocation.
98722       */
98723       int addrTop;
98724       int addrEof;
98725       pItem->regReturn = ++pParse->nMem;
98726       addrEof = ++pParse->nMem;
98727       /* Before coding the OP_Goto to jump to the start of the main routine,
98728       ** ensure that the jump to the verify-schema routine has already
98729       ** been coded. Otherwise, the verify-schema would likely be coded as 
98730       ** part of the co-routine. If the main routine then accessed the 
98731       ** database before invoking the co-routine for the first time (for 
98732       ** example to initialize a LIMIT register from a sub-select), it would 
98733       ** be doing so without having verified the schema version and obtained 
98734       ** the required db locks. See ticket d6b36be38.  */
98735       sqlite3CodeVerifySchema(pParse, -1);
98736       sqlite3VdbeAddOp0(v, OP_Goto);
98737       addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
98738       sqlite3VdbeChangeP5(v, 1);
98739       VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
98740       pItem->addrFillSub = addrTop;
98741       sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
98742       sqlite3VdbeChangeP5(v, 1);
98743       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
98744       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
98745       sqlite3Select(pParse, pSub, &dest);
98746       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
98747       pItem->viaCoroutine = 1;
98748       sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
98749       sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
98750       sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
98751       sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
98752       VdbeComment((v, "end %s", pItem->pTab->zName));
98753       sqlite3VdbeJumpHere(v, addrTop-1);
98754       sqlite3ClearTempRegCache(pParse);
98755     }else{
98756       /* Generate a subroutine that will fill an ephemeral table with
98757       ** the content of this subquery.  pItem->addrFillSub will point
98758       ** to the address of the generated subroutine.  pItem->regReturn
98759       ** is a register allocated to hold the subroutine return address
98760       */
98761       int topAddr;
98762       int onceAddr = 0;
98763       int retAddr;
98764       assert( pItem->addrFillSub==0 );
98765       pItem->regReturn = ++pParse->nMem;
98766       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
98767       pItem->addrFillSub = topAddr+1;
98768       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
98769       if( pItem->isCorrelated==0 ){
98770         /* If the subquery is no correlated and if we are not inside of
98771         ** a trigger, then we only need to compute the value of the subquery
98772         ** once. */
98773         onceAddr = sqlite3CodeOnce(pParse);
98774       }
98775       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
98776       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
98777       sqlite3Select(pParse, pSub, &dest);
98778       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
98779       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
98780       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
98781       VdbeComment((v, "end %s", pItem->pTab->zName));
98782       sqlite3VdbeChangeP1(v, topAddr, retAddr);
98783       sqlite3ClearTempRegCache(pParse);
98784     }
98785     if( /*pParse->nErr ||*/ db->mallocFailed ){
98786       goto select_end;
98787     }
98788     pParse->nHeight -= sqlite3SelectExprHeight(p);
98789     pTabList = p->pSrc;
98790     if( !IgnorableOrderby(pDest) ){
98791       pOrderBy = p->pOrderBy;
98792     }
98793   }
98794   pEList = p->pEList;
98795 #endif
98796   pWhere = p->pWhere;
98797   pGroupBy = p->pGroupBy;
98798   pHaving = p->pHaving;
98799   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
98800
98801 #ifndef SQLITE_OMIT_COMPOUND_SELECT
98802   /* If there is are a sequence of queries, do the earlier ones first.
98803   */
98804   if( p->pPrior ){
98805     if( p->pRightmost==0 ){
98806       Select *pLoop, *pRight = 0;
98807       int cnt = 0;
98808       int mxSelect;
98809       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
98810         pLoop->pRightmost = p;
98811         pLoop->pNext = pRight;
98812         pRight = pLoop;
98813       }
98814       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
98815       if( mxSelect && cnt>mxSelect ){
98816         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
98817         goto select_end;
98818       }
98819     }
98820     rc = multiSelect(pParse, p, pDest);
98821     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
98822     return rc;
98823   }
98824 #endif
98825
98826   /* If there is both a GROUP BY and an ORDER BY clause and they are
98827   ** identical, then disable the ORDER BY clause since the GROUP BY
98828   ** will cause elements to come out in the correct order.  This is
98829   ** an optimization - the correct answer should result regardless.
98830   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
98831   ** to disable this optimization for testing purposes.
98832   */
98833   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
98834          && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
98835     pOrderBy = 0;
98836   }
98837
98838   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
98839   ** if the select-list is the same as the ORDER BY list, then this query
98840   ** can be rewritten as a GROUP BY. In other words, this:
98841   **
98842   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
98843   **
98844   ** is transformed to:
98845   **
98846   **     SELECT xyz FROM ... GROUP BY xyz
98847   **
98848   ** The second form is preferred as a single index (or temp-table) may be 
98849   ** used for both the ORDER BY and DISTINCT processing. As originally 
98850   ** written the query must use a temp-table for at least one of the ORDER 
98851   ** BY and DISTINCT, and an index or separate temp-table for the other.
98852   */
98853   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
98854    && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
98855   ){
98856     p->selFlags &= ~SF_Distinct;
98857     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
98858     pGroupBy = p->pGroupBy;
98859     pOrderBy = 0;
98860     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
98861     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
98862     ** original setting of the SF_Distinct flag, not the current setting */
98863     assert( sDistinct.isTnct );
98864   }
98865
98866   /* If there is an ORDER BY clause, then this sorting
98867   ** index might end up being unused if the data can be 
98868   ** extracted in pre-sorted order.  If that is the case, then the
98869   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
98870   ** we figure out that the sorting index is not needed.  The addrSortIndex
98871   ** variable is used to facilitate that change.
98872   */
98873   if( pOrderBy ){
98874     KeyInfo *pKeyInfo;
98875     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
98876     pOrderBy->iECursor = pParse->nTab++;
98877     p->addrOpenEphm[2] = addrSortIndex =
98878       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
98879                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
98880                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98881   }else{
98882     addrSortIndex = -1;
98883   }
98884
98885   /* If the output is destined for a temporary table, open that table.
98886   */
98887   if( pDest->eDest==SRT_EphemTab ){
98888     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
98889   }
98890
98891   /* Set the limiter.
98892   */
98893   iEnd = sqlite3VdbeMakeLabel(v);
98894   p->nSelectRow = (double)LARGEST_INT64;
98895   computeLimitRegisters(pParse, p, iEnd);
98896   if( p->iLimit==0 && addrSortIndex>=0 ){
98897     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
98898     p->selFlags |= SF_UseSorter;
98899   }
98900
98901   /* Open a virtual index to use for the distinct set.
98902   */
98903   if( p->selFlags & SF_Distinct ){
98904     sDistinct.tabTnct = pParse->nTab++;
98905     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
98906                                 sDistinct.tabTnct, 0, 0,
98907                                 (char*)keyInfoFromExprList(pParse, p->pEList),
98908                                 P4_KEYINFO_HANDOFF);
98909     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
98910     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
98911   }else{
98912     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
98913   }
98914
98915   if( !isAgg && pGroupBy==0 ){
98916     /* No aggregate functions and no GROUP BY clause */
98917     ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
98918
98919     /* Begin the database scan. */
98920     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
98921     if( pWInfo==0 ) goto select_end;
98922     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
98923     if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct;
98924     if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0;
98925
98926     /* If sorting index that was created by a prior OP_OpenEphemeral 
98927     ** instruction ended up not being needed, then change the OP_OpenEphemeral
98928     ** into an OP_Noop.
98929     */
98930     if( addrSortIndex>=0 && pOrderBy==0 ){
98931       sqlite3VdbeChangeToNoop(v, addrSortIndex);
98932       p->addrOpenEphm[2] = -1;
98933     }
98934
98935     /* Use the standard inner loop. */
98936     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
98937                     pWInfo->iContinue, pWInfo->iBreak);
98938
98939     /* End the database scan loop.
98940     */
98941     sqlite3WhereEnd(pWInfo);
98942   }else{
98943     /* This case when there exist aggregate functions or a GROUP BY clause
98944     ** or both */
98945     NameContext sNC;    /* Name context for processing aggregate information */
98946     int iAMem;          /* First Mem address for storing current GROUP BY */
98947     int iBMem;          /* First Mem address for previous GROUP BY */
98948     int iUseFlag;       /* Mem address holding flag indicating that at least
98949                         ** one row of the input to the aggregator has been
98950                         ** processed */
98951     int iAbortFlag;     /* Mem address which causes query abort if positive */
98952     int groupBySort;    /* Rows come from source in GROUP BY order */
98953     int addrEnd;        /* End of processing for this SELECT */
98954     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
98955     int sortOut = 0;    /* Output register from the sorter */
98956
98957     /* Remove any and all aliases between the result set and the
98958     ** GROUP BY clause.
98959     */
98960     if( pGroupBy ){
98961       int k;                        /* Loop counter */
98962       struct ExprList_item *pItem;  /* For looping over expression in a list */
98963
98964       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
98965         pItem->iAlias = 0;
98966       }
98967       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
98968         pItem->iAlias = 0;
98969       }
98970       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
98971     }else{
98972       p->nSelectRow = (double)1;
98973     }
98974
98975  
98976     /* Create a label to jump to when we want to abort the query */
98977     addrEnd = sqlite3VdbeMakeLabel(v);
98978
98979     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
98980     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
98981     ** SELECT statement.
98982     */
98983     memset(&sNC, 0, sizeof(sNC));
98984     sNC.pParse = pParse;
98985     sNC.pSrcList = pTabList;
98986     sNC.pAggInfo = &sAggInfo;
98987     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
98988     sAggInfo.pGroupBy = pGroupBy;
98989     sqlite3ExprAnalyzeAggList(&sNC, pEList);
98990     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
98991     if( pHaving ){
98992       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
98993     }
98994     sAggInfo.nAccumulator = sAggInfo.nColumn;
98995     for(i=0; i<sAggInfo.nFunc; i++){
98996       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
98997       sNC.ncFlags |= NC_InAggFunc;
98998       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
98999       sNC.ncFlags &= ~NC_InAggFunc;
99000     }
99001     if( db->mallocFailed ) goto select_end;
99002
99003     /* Processing for aggregates with GROUP BY is very different and
99004     ** much more complex than aggregates without a GROUP BY.
99005     */
99006     if( pGroupBy ){
99007       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
99008       int j1;             /* A-vs-B comparision jump */
99009       int addrOutputRow;  /* Start of subroutine that outputs a result row */
99010       int regOutputRow;   /* Return address register for output subroutine */
99011       int addrSetAbort;   /* Set the abort flag and return */
99012       int addrTopOfLoop;  /* Top of the input loop */
99013       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
99014       int addrReset;      /* Subroutine for resetting the accumulator */
99015       int regReset;       /* Return address register for reset subroutine */
99016
99017       /* If there is a GROUP BY clause we might need a sorting index to
99018       ** implement it.  Allocate that sorting index now.  If it turns out
99019       ** that we do not need it after all, the OP_SorterOpen instruction
99020       ** will be converted into a Noop.  
99021       */
99022       sAggInfo.sortingIdx = pParse->nTab++;
99023       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
99024       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 
99025           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
99026           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
99027
99028       /* Initialize memory locations used by GROUP BY aggregate processing
99029       */
99030       iUseFlag = ++pParse->nMem;
99031       iAbortFlag = ++pParse->nMem;
99032       regOutputRow = ++pParse->nMem;
99033       addrOutputRow = sqlite3VdbeMakeLabel(v);
99034       regReset = ++pParse->nMem;
99035       addrReset = sqlite3VdbeMakeLabel(v);
99036       iAMem = pParse->nMem + 1;
99037       pParse->nMem += pGroupBy->nExpr;
99038       iBMem = pParse->nMem + 1;
99039       pParse->nMem += pGroupBy->nExpr;
99040       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
99041       VdbeComment((v, "clear abort flag"));
99042       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
99043       VdbeComment((v, "indicate accumulator empty"));
99044       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
99045
99046       /* Begin a loop that will extract all source rows in GROUP BY order.
99047       ** This might involve two separate loops with an OP_Sort in between, or
99048       ** it might be a single loop that uses an index to extract information
99049       ** in the right order to begin with.
99050       */
99051       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
99052       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
99053       if( pWInfo==0 ) goto select_end;
99054       if( pWInfo->nOBSat==pGroupBy->nExpr ){
99055         /* The optimizer is able to deliver rows in group by order so
99056         ** we do not have to sort.  The OP_OpenEphemeral table will be
99057         ** cancelled later because we still need to use the pKeyInfo
99058         */
99059         groupBySort = 0;
99060       }else{
99061         /* Rows are coming out in undetermined order.  We have to push
99062         ** each row into a sorting index, terminate the first loop,
99063         ** then loop over the sorting index in order to get the output
99064         ** in sorted order
99065         */
99066         int regBase;
99067         int regRecord;
99068         int nCol;
99069         int nGroupBy;
99070
99071         explainTempTable(pParse, 
99072             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
99073                     "DISTINCT" : "GROUP BY");
99074
99075         groupBySort = 1;
99076         nGroupBy = pGroupBy->nExpr;
99077         nCol = nGroupBy + 1;
99078         j = nGroupBy+1;
99079         for(i=0; i<sAggInfo.nColumn; i++){
99080           if( sAggInfo.aCol[i].iSorterColumn>=j ){
99081             nCol++;
99082             j++;
99083           }
99084         }
99085         regBase = sqlite3GetTempRange(pParse, nCol);
99086         sqlite3ExprCacheClear(pParse);
99087         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
99088         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
99089         j = nGroupBy+1;
99090         for(i=0; i<sAggInfo.nColumn; i++){
99091           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
99092           if( pCol->iSorterColumn>=j ){
99093             int r1 = j + regBase;
99094             int r2;
99095
99096             r2 = sqlite3ExprCodeGetColumn(pParse, 
99097                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
99098             if( r1!=r2 ){
99099               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
99100             }
99101             j++;
99102           }
99103         }
99104         regRecord = sqlite3GetTempReg(pParse);
99105         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
99106         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
99107         sqlite3ReleaseTempReg(pParse, regRecord);
99108         sqlite3ReleaseTempRange(pParse, regBase, nCol);
99109         sqlite3WhereEnd(pWInfo);
99110         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
99111         sortOut = sqlite3GetTempReg(pParse);
99112         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
99113         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
99114         VdbeComment((v, "GROUP BY sort"));
99115         sAggInfo.useSortingIdx = 1;
99116         sqlite3ExprCacheClear(pParse);
99117       }
99118
99119       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
99120       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
99121       ** Then compare the current GROUP BY terms against the GROUP BY terms
99122       ** from the previous row currently stored in a0, a1, a2...
99123       */
99124       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
99125       sqlite3ExprCacheClear(pParse);
99126       if( groupBySort ){
99127         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
99128       }
99129       for(j=0; j<pGroupBy->nExpr; j++){
99130         if( groupBySort ){
99131           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
99132           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
99133         }else{
99134           sAggInfo.directMode = 1;
99135           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
99136         }
99137       }
99138       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
99139                           (char*)pKeyInfo, P4_KEYINFO);
99140       j1 = sqlite3VdbeCurrentAddr(v);
99141       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
99142
99143       /* Generate code that runs whenever the GROUP BY changes.
99144       ** Changes in the GROUP BY are detected by the previous code
99145       ** block.  If there were no changes, this block is skipped.
99146       **
99147       ** This code copies current group by terms in b0,b1,b2,...
99148       ** over to a0,a1,a2.  It then calls the output subroutine
99149       ** and resets the aggregate accumulator registers in preparation
99150       ** for the next GROUP BY batch.
99151       */
99152       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
99153       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
99154       VdbeComment((v, "output one row"));
99155       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
99156       VdbeComment((v, "check abort flag"));
99157       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
99158       VdbeComment((v, "reset accumulator"));
99159
99160       /* Update the aggregate accumulators based on the content of
99161       ** the current row
99162       */
99163       sqlite3VdbeJumpHere(v, j1);
99164       updateAccumulator(pParse, &sAggInfo);
99165       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
99166       VdbeComment((v, "indicate data in accumulator"));
99167
99168       /* End of the loop
99169       */
99170       if( groupBySort ){
99171         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
99172       }else{
99173         sqlite3WhereEnd(pWInfo);
99174         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
99175       }
99176
99177       /* Output the final row of result
99178       */
99179       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
99180       VdbeComment((v, "output final row"));
99181
99182       /* Jump over the subroutines
99183       */
99184       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
99185
99186       /* Generate a subroutine that outputs a single row of the result
99187       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
99188       ** is less than or equal to zero, the subroutine is a no-op.  If
99189       ** the processing calls for the query to abort, this subroutine
99190       ** increments the iAbortFlag memory location before returning in
99191       ** order to signal the caller to abort.
99192       */
99193       addrSetAbort = sqlite3VdbeCurrentAddr(v);
99194       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
99195       VdbeComment((v, "set abort flag"));
99196       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
99197       sqlite3VdbeResolveLabel(v, addrOutputRow);
99198       addrOutputRow = sqlite3VdbeCurrentAddr(v);
99199       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
99200       VdbeComment((v, "Groupby result generator entry point"));
99201       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
99202       finalizeAggFunctions(pParse, &sAggInfo);
99203       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
99204       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
99205                       &sDistinct, pDest,
99206                       addrOutputRow+1, addrSetAbort);
99207       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
99208       VdbeComment((v, "end groupby result generator"));
99209
99210       /* Generate a subroutine that will reset the group-by accumulator
99211       */
99212       sqlite3VdbeResolveLabel(v, addrReset);
99213       resetAccumulator(pParse, &sAggInfo);
99214       sqlite3VdbeAddOp1(v, OP_Return, regReset);
99215      
99216     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
99217     else {
99218       ExprList *pDel = 0;
99219 #ifndef SQLITE_OMIT_BTREECOUNT
99220       Table *pTab;
99221       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
99222         /* If isSimpleCount() returns a pointer to a Table structure, then
99223         ** the SQL statement is of the form:
99224         **
99225         **   SELECT count(*) FROM <tbl>
99226         **
99227         ** where the Table structure returned represents table <tbl>.
99228         **
99229         ** This statement is so common that it is optimized specially. The
99230         ** OP_Count instruction is executed either on the intkey table that
99231         ** contains the data for table <tbl> or on one of its indexes. It
99232         ** is better to execute the op on an index, as indexes are almost
99233         ** always spread across less pages than their corresponding tables.
99234         */
99235         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99236         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
99237         Index *pIdx;                         /* Iterator variable */
99238         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
99239         Index *pBest = 0;                    /* Best index found so far */
99240         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
99241
99242         sqlite3CodeVerifySchema(pParse, iDb);
99243         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
99244
99245         /* Search for the index that has the least amount of columns. If
99246         ** there is such an index, and it has less columns than the table
99247         ** does, then we can assume that it consumes less space on disk and
99248         ** will therefore be cheaper to scan to determine the query result.
99249         ** In this case set iRoot to the root page number of the index b-tree
99250         ** and pKeyInfo to the KeyInfo structure required to navigate the
99251         ** index.
99252         **
99253         ** (2011-04-15) Do not do a full scan of an unordered index.
99254         **
99255         ** In practice the KeyInfo structure will not be used. It is only 
99256         ** passed to keep OP_OpenRead happy.
99257         */
99258         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99259           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
99260             pBest = pIdx;
99261           }
99262         }
99263         if( pBest && pBest->nColumn<pTab->nCol ){
99264           iRoot = pBest->tnum;
99265           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
99266         }
99267
99268         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
99269         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
99270         if( pKeyInfo ){
99271           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
99272         }
99273         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
99274         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
99275         explainSimpleCount(pParse, pTab, pBest);
99276       }else
99277 #endif /* SQLITE_OMIT_BTREECOUNT */
99278       {
99279         /* Check if the query is of one of the following forms:
99280         **
99281         **   SELECT min(x) FROM ...
99282         **   SELECT max(x) FROM ...
99283         **
99284         ** If it is, then ask the code in where.c to attempt to sort results
99285         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
99286         ** If where.c is able to produce results sorted in this order, then
99287         ** add vdbe code to break out of the processing loop after the 
99288         ** first iteration (since the first iteration of the loop is 
99289         ** guaranteed to operate on the row with the minimum or maximum 
99290         ** value of x, the only row required).
99291         **
99292         ** A special flag must be passed to sqlite3WhereBegin() to slightly
99293         ** modify behavior as follows:
99294         **
99295         **   + If the query is a "SELECT min(x)", then the loop coded by
99296         **     where.c should not iterate over any values with a NULL value
99297         **     for x.
99298         **
99299         **   + The optimizer code in where.c (the thing that decides which
99300         **     index or indices to use) should place a different priority on 
99301         **     satisfying the 'ORDER BY' clause than it does in other cases.
99302         **     Refer to code and comments in where.c for details.
99303         */
99304         ExprList *pMinMax = 0;
99305         u8 flag = WHERE_ORDERBY_NORMAL;
99306         
99307         assert( p->pGroupBy==0 );
99308         assert( flag==0 );
99309         if( p->pHaving==0 ){
99310           flag = minMaxQuery(&sAggInfo, &pMinMax);
99311         }
99312         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
99313
99314         if( flag ){
99315           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
99316           pDel = pMinMax;
99317           if( pMinMax && !db->mallocFailed ){
99318             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
99319             pMinMax->a[0].pExpr->op = TK_COLUMN;
99320           }
99321         }
99322   
99323         /* This case runs if the aggregate has no GROUP BY clause.  The
99324         ** processing is much simpler since there is only a single row
99325         ** of output.
99326         */
99327         resetAccumulator(pParse, &sAggInfo);
99328         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
99329         if( pWInfo==0 ){
99330           sqlite3ExprListDelete(db, pDel);
99331           goto select_end;
99332         }
99333         updateAccumulator(pParse, &sAggInfo);
99334         assert( pMinMax==0 || pMinMax->nExpr==1 );
99335         if( pWInfo->nOBSat>0 ){
99336           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
99337           VdbeComment((v, "%s() by index",
99338                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
99339         }
99340         sqlite3WhereEnd(pWInfo);
99341         finalizeAggFunctions(pParse, &sAggInfo);
99342       }
99343
99344       pOrderBy = 0;
99345       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
99346       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0, 
99347                       pDest, addrEnd, addrEnd);
99348       sqlite3ExprListDelete(db, pDel);
99349     }
99350     sqlite3VdbeResolveLabel(v, addrEnd);
99351     
99352   } /* endif aggregate query */
99353
99354   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
99355     explainTempTable(pParse, "DISTINCT");
99356   }
99357
99358   /* If there is an ORDER BY clause, then we need to sort the results
99359   ** and send them to the callback one by one.
99360   */
99361   if( pOrderBy ){
99362     explainTempTable(pParse, "ORDER BY");
99363     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
99364   }
99365
99366   /* Jump here to skip this query
99367   */
99368   sqlite3VdbeResolveLabel(v, iEnd);
99369
99370   /* The SELECT was successfully coded.   Set the return code to 0
99371   ** to indicate no errors.
99372   */
99373   rc = 0;
99374
99375   /* Control jumps to here if an error is encountered above, or upon
99376   ** successful coding of the SELECT.
99377   */
99378 select_end:
99379   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
99380
99381   /* Identify column names if results of the SELECT are to be output.
99382   */
99383   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
99384     generateColumnNames(pParse, pTabList, pEList);
99385   }
99386
99387   sqlite3DbFree(db, sAggInfo.aCol);
99388   sqlite3DbFree(db, sAggInfo.aFunc);
99389   return rc;
99390 }
99391
99392 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
99393 /*
99394 ** Generate a human-readable description of a the Select object.
99395 */
99396 static void explainOneSelect(Vdbe *pVdbe, Select *p){
99397   sqlite3ExplainPrintf(pVdbe, "SELECT ");
99398   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
99399     if( p->selFlags & SF_Distinct ){
99400       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
99401     }
99402     if( p->selFlags & SF_Aggregate ){
99403       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
99404     }
99405     sqlite3ExplainNL(pVdbe);
99406     sqlite3ExplainPrintf(pVdbe, "   ");
99407   }
99408   sqlite3ExplainExprList(pVdbe, p->pEList);
99409   sqlite3ExplainNL(pVdbe);
99410   if( p->pSrc && p->pSrc->nSrc ){
99411     int i;
99412     sqlite3ExplainPrintf(pVdbe, "FROM ");
99413     sqlite3ExplainPush(pVdbe);
99414     for(i=0; i<p->pSrc->nSrc; i++){
99415       struct SrcList_item *pItem = &p->pSrc->a[i];
99416       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
99417       if( pItem->pSelect ){
99418         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
99419         if( pItem->pTab ){
99420           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
99421         }
99422       }else if( pItem->zName ){
99423         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
99424       }
99425       if( pItem->zAlias ){
99426         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
99427       }
99428       if( pItem->jointype & JT_LEFT ){
99429         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
99430       }
99431       sqlite3ExplainNL(pVdbe);
99432     }
99433     sqlite3ExplainPop(pVdbe);
99434   }
99435   if( p->pWhere ){
99436     sqlite3ExplainPrintf(pVdbe, "WHERE ");
99437     sqlite3ExplainExpr(pVdbe, p->pWhere);
99438     sqlite3ExplainNL(pVdbe);
99439   }
99440   if( p->pGroupBy ){
99441     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
99442     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
99443     sqlite3ExplainNL(pVdbe);
99444   }
99445   if( p->pHaving ){
99446     sqlite3ExplainPrintf(pVdbe, "HAVING ");
99447     sqlite3ExplainExpr(pVdbe, p->pHaving);
99448     sqlite3ExplainNL(pVdbe);
99449   }
99450   if( p->pOrderBy ){
99451     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
99452     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
99453     sqlite3ExplainNL(pVdbe);
99454   }
99455   if( p->pLimit ){
99456     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
99457     sqlite3ExplainExpr(pVdbe, p->pLimit);
99458     sqlite3ExplainNL(pVdbe);
99459   }
99460   if( p->pOffset ){
99461     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
99462     sqlite3ExplainExpr(pVdbe, p->pOffset);
99463     sqlite3ExplainNL(pVdbe);
99464   }
99465 }
99466 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
99467   if( p==0 ){
99468     sqlite3ExplainPrintf(pVdbe, "(null-select)");
99469     return;
99470   }
99471   while( p->pPrior ){
99472     p->pPrior->pNext = p;
99473     p = p->pPrior;
99474   }
99475   sqlite3ExplainPush(pVdbe);
99476   while( p ){
99477     explainOneSelect(pVdbe, p);
99478     p = p->pNext;
99479     if( p==0 ) break;
99480     sqlite3ExplainNL(pVdbe);
99481     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
99482   }
99483   sqlite3ExplainPrintf(pVdbe, "END");
99484   sqlite3ExplainPop(pVdbe);
99485 }
99486
99487 /* End of the structure debug printing code
99488 *****************************************************************************/
99489 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
99490
99491 /************** End of select.c **********************************************/
99492 /************** Begin file table.c *******************************************/
99493 /*
99494 ** 2001 September 15
99495 **
99496 ** The author disclaims copyright to this source code.  In place of
99497 ** a legal notice, here is a blessing:
99498 **
99499 **    May you do good and not evil.
99500 **    May you find forgiveness for yourself and forgive others.
99501 **    May you share freely, never taking more than you give.
99502 **
99503 *************************************************************************
99504 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
99505 ** interface routines.  These are just wrappers around the main
99506 ** interface routine of sqlite3_exec().
99507 **
99508 ** These routines are in a separate files so that they will not be linked
99509 ** if they are not used.
99510 */
99511 /* #include <stdlib.h> */
99512 /* #include <string.h> */
99513
99514 #ifndef SQLITE_OMIT_GET_TABLE
99515
99516 /*
99517 ** This structure is used to pass data from sqlite3_get_table() through
99518 ** to the callback function is uses to build the result.
99519 */
99520 typedef struct TabResult {
99521   char **azResult;   /* Accumulated output */
99522   char *zErrMsg;     /* Error message text, if an error occurs */
99523   int nAlloc;        /* Slots allocated for azResult[] */
99524   int nRow;          /* Number of rows in the result */
99525   int nColumn;       /* Number of columns in the result */
99526   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
99527   int rc;            /* Return code from sqlite3_exec() */
99528 } TabResult;
99529
99530 /*
99531 ** This routine is called once for each row in the result table.  Its job
99532 ** is to fill in the TabResult structure appropriately, allocating new
99533 ** memory as necessary.
99534 */
99535 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
99536   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
99537   int need;                         /* Slots needed in p->azResult[] */
99538   int i;                            /* Loop counter */
99539   char *z;                          /* A single column of result */
99540
99541   /* Make sure there is enough space in p->azResult to hold everything
99542   ** we need to remember from this invocation of the callback.
99543   */
99544   if( p->nRow==0 && argv!=0 ){
99545     need = nCol*2;
99546   }else{
99547     need = nCol;
99548   }
99549   if( p->nData + need > p->nAlloc ){
99550     char **azNew;
99551     p->nAlloc = p->nAlloc*2 + need;
99552     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
99553     if( azNew==0 ) goto malloc_failed;
99554     p->azResult = azNew;
99555   }
99556
99557   /* If this is the first row, then generate an extra row containing
99558   ** the names of all columns.
99559   */
99560   if( p->nRow==0 ){
99561     p->nColumn = nCol;
99562     for(i=0; i<nCol; i++){
99563       z = sqlite3_mprintf("%s", colv[i]);
99564       if( z==0 ) goto malloc_failed;
99565       p->azResult[p->nData++] = z;
99566     }
99567   }else if( p->nColumn!=nCol ){
99568     sqlite3_free(p->zErrMsg);
99569     p->zErrMsg = sqlite3_mprintf(
99570        "sqlite3_get_table() called with two or more incompatible queries"
99571     );
99572     p->rc = SQLITE_ERROR;
99573     return 1;
99574   }
99575
99576   /* Copy over the row data
99577   */
99578   if( argv!=0 ){
99579     for(i=0; i<nCol; i++){
99580       if( argv[i]==0 ){
99581         z = 0;
99582       }else{
99583         int n = sqlite3Strlen30(argv[i])+1;
99584         z = sqlite3_malloc( n );
99585         if( z==0 ) goto malloc_failed;
99586         memcpy(z, argv[i], n);
99587       }
99588       p->azResult[p->nData++] = z;
99589     }
99590     p->nRow++;
99591   }
99592   return 0;
99593
99594 malloc_failed:
99595   p->rc = SQLITE_NOMEM;
99596   return 1;
99597 }
99598
99599 /*
99600 ** Query the database.  But instead of invoking a callback for each row,
99601 ** malloc() for space to hold the result and return the entire results
99602 ** at the conclusion of the call.
99603 **
99604 ** The result that is written to ***pazResult is held in memory obtained
99605 ** from malloc().  But the caller cannot free this memory directly.  
99606 ** Instead, the entire table should be passed to sqlite3_free_table() when
99607 ** the calling procedure is finished using it.
99608 */
99609 SQLITE_API int sqlite3_get_table(
99610   sqlite3 *db,                /* The database on which the SQL executes */
99611   const char *zSql,           /* The SQL to be executed */
99612   char ***pazResult,          /* Write the result table here */
99613   int *pnRow,                 /* Write the number of rows in the result here */
99614   int *pnColumn,              /* Write the number of columns of result here */
99615   char **pzErrMsg             /* Write error messages here */
99616 ){
99617   int rc;
99618   TabResult res;
99619
99620   *pazResult = 0;
99621   if( pnColumn ) *pnColumn = 0;
99622   if( pnRow ) *pnRow = 0;
99623   if( pzErrMsg ) *pzErrMsg = 0;
99624   res.zErrMsg = 0;
99625   res.nRow = 0;
99626   res.nColumn = 0;
99627   res.nData = 1;
99628   res.nAlloc = 20;
99629   res.rc = SQLITE_OK;
99630   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
99631   if( res.azResult==0 ){
99632      db->errCode = SQLITE_NOMEM;
99633      return SQLITE_NOMEM;
99634   }
99635   res.azResult[0] = 0;
99636   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
99637   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
99638   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
99639   if( (rc&0xff)==SQLITE_ABORT ){
99640     sqlite3_free_table(&res.azResult[1]);
99641     if( res.zErrMsg ){
99642       if( pzErrMsg ){
99643         sqlite3_free(*pzErrMsg);
99644         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
99645       }
99646       sqlite3_free(res.zErrMsg);
99647     }
99648     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
99649     return res.rc;
99650   }
99651   sqlite3_free(res.zErrMsg);
99652   if( rc!=SQLITE_OK ){
99653     sqlite3_free_table(&res.azResult[1]);
99654     return rc;
99655   }
99656   if( res.nAlloc>res.nData ){
99657     char **azNew;
99658     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
99659     if( azNew==0 ){
99660       sqlite3_free_table(&res.azResult[1]);
99661       db->errCode = SQLITE_NOMEM;
99662       return SQLITE_NOMEM;
99663     }
99664     res.azResult = azNew;
99665   }
99666   *pazResult = &res.azResult[1];
99667   if( pnColumn ) *pnColumn = res.nColumn;
99668   if( pnRow ) *pnRow = res.nRow;
99669   return rc;
99670 }
99671
99672 /*
99673 ** This routine frees the space the sqlite3_get_table() malloced.
99674 */
99675 SQLITE_API void sqlite3_free_table(
99676   char **azResult            /* Result returned from from sqlite3_get_table() */
99677 ){
99678   if( azResult ){
99679     int i, n;
99680     azResult--;
99681     assert( azResult!=0 );
99682     n = SQLITE_PTR_TO_INT(azResult[0]);
99683     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
99684     sqlite3_free(azResult);
99685   }
99686 }
99687
99688 #endif /* SQLITE_OMIT_GET_TABLE */
99689
99690 /************** End of table.c ***********************************************/
99691 /************** Begin file trigger.c *****************************************/
99692 /*
99693 **
99694 ** The author disclaims copyright to this source code.  In place of
99695 ** a legal notice, here is a blessing:
99696 **
99697 **    May you do good and not evil.
99698 **    May you find forgiveness for yourself and forgive others.
99699 **    May you share freely, never taking more than you give.
99700 **
99701 *************************************************************************
99702 ** This file contains the implementation for TRIGGERs
99703 */
99704
99705 #ifndef SQLITE_OMIT_TRIGGER
99706 /*
99707 ** Delete a linked list of TriggerStep structures.
99708 */
99709 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
99710   while( pTriggerStep ){
99711     TriggerStep * pTmp = pTriggerStep;
99712     pTriggerStep = pTriggerStep->pNext;
99713
99714     sqlite3ExprDelete(db, pTmp->pWhere);
99715     sqlite3ExprListDelete(db, pTmp->pExprList);
99716     sqlite3SelectDelete(db, pTmp->pSelect);
99717     sqlite3IdListDelete(db, pTmp->pIdList);
99718
99719     sqlite3DbFree(db, pTmp);
99720   }
99721 }
99722
99723 /*
99724 ** Given table pTab, return a list of all the triggers attached to 
99725 ** the table. The list is connected by Trigger.pNext pointers.
99726 **
99727 ** All of the triggers on pTab that are in the same database as pTab
99728 ** are already attached to pTab->pTrigger.  But there might be additional
99729 ** triggers on pTab in the TEMP schema.  This routine prepends all
99730 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
99731 ** and returns the combined list.
99732 **
99733 ** To state it another way:  This routine returns a list of all triggers
99734 ** that fire off of pTab.  The list will include any TEMP triggers on
99735 ** pTab as well as the triggers lised in pTab->pTrigger.
99736 */
99737 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
99738   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
99739   Trigger *pList = 0;                  /* List of triggers to return */
99740
99741   if( pParse->disableTriggers ){
99742     return 0;
99743   }
99744
99745   if( pTmpSchema!=pTab->pSchema ){
99746     HashElem *p;
99747     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
99748     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
99749       Trigger *pTrig = (Trigger *)sqliteHashData(p);
99750       if( pTrig->pTabSchema==pTab->pSchema
99751        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
99752       ){
99753         pTrig->pNext = (pList ? pList : pTab->pTrigger);
99754         pList = pTrig;
99755       }
99756     }
99757   }
99758
99759   return (pList ? pList : pTab->pTrigger);
99760 }
99761
99762 /*
99763 ** This is called by the parser when it sees a CREATE TRIGGER statement
99764 ** up to the point of the BEGIN before the trigger actions.  A Trigger
99765 ** structure is generated based on the information available and stored
99766 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
99767 ** sqlite3FinishTrigger() function is called to complete the trigger
99768 ** construction process.
99769 */
99770 SQLITE_PRIVATE void sqlite3BeginTrigger(
99771   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
99772   Token *pName1,      /* The name of the trigger */
99773   Token *pName2,      /* The name of the trigger */
99774   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
99775   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
99776   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
99777   SrcList *pTableName,/* The name of the table/view the trigger applies to */
99778   Expr *pWhen,        /* WHEN clause */
99779   int isTemp,         /* True if the TEMPORARY keyword is present */
99780   int noErr           /* Suppress errors if the trigger already exists */
99781 ){
99782   Trigger *pTrigger = 0;  /* The new trigger */
99783   Table *pTab;            /* Table that the trigger fires off of */
99784   char *zName = 0;        /* Name of the trigger */
99785   sqlite3 *db = pParse->db;  /* The database connection */
99786   int iDb;                /* The database to store the trigger in */
99787   Token *pName;           /* The unqualified db name */
99788   DbFixer sFix;           /* State vector for the DB fixer */
99789   int iTabDb;             /* Index of the database holding pTab */
99790
99791   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
99792   assert( pName2!=0 );
99793   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
99794   assert( op>0 && op<0xff );
99795   if( isTemp ){
99796     /* If TEMP was specified, then the trigger name may not be qualified. */
99797     if( pName2->n>0 ){
99798       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
99799       goto trigger_cleanup;
99800     }
99801     iDb = 1;
99802     pName = pName1;
99803   }else{
99804     /* Figure out the db that the trigger will be created in */
99805     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
99806     if( iDb<0 ){
99807       goto trigger_cleanup;
99808     }
99809   }
99810   if( !pTableName || db->mallocFailed ){
99811     goto trigger_cleanup;
99812   }
99813
99814   /* A long-standing parser bug is that this syntax was allowed:
99815   **
99816   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
99817   **                                                 ^^^^^^^^
99818   **
99819   ** To maintain backwards compatibility, ignore the database
99820   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
99821   */
99822   if( db->init.busy && iDb!=1 ){
99823     sqlite3DbFree(db, pTableName->a[0].zDatabase);
99824     pTableName->a[0].zDatabase = 0;
99825   }
99826
99827   /* If the trigger name was unqualified, and the table is a temp table,
99828   ** then set iDb to 1 to create the trigger in the temporary database.
99829   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
99830   ** exist, the error is caught by the block below.
99831   */
99832   pTab = sqlite3SrcListLookup(pParse, pTableName);
99833   if( db->init.busy==0 && pName2->n==0 && pTab
99834         && pTab->pSchema==db->aDb[1].pSchema ){
99835     iDb = 1;
99836   }
99837
99838   /* Ensure the table name matches database name and that the table exists */
99839   if( db->mallocFailed ) goto trigger_cleanup;
99840   assert( pTableName->nSrc==1 );
99841   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
99842       sqlite3FixSrcList(&sFix, pTableName) ){
99843     goto trigger_cleanup;
99844   }
99845   pTab = sqlite3SrcListLookup(pParse, pTableName);
99846   if( !pTab ){
99847     /* The table does not exist. */
99848     if( db->init.iDb==1 ){
99849       /* Ticket #3810.
99850       ** Normally, whenever a table is dropped, all associated triggers are
99851       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
99852       ** and the table is dropped by a different database connection, the
99853       ** trigger is not visible to the database connection that does the
99854       ** drop so the trigger cannot be dropped.  This results in an
99855       ** "orphaned trigger" - a trigger whose associated table is missing.
99856       */
99857       db->init.orphanTrigger = 1;
99858     }
99859     goto trigger_cleanup;
99860   }
99861   if( IsVirtual(pTab) ){
99862     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
99863     goto trigger_cleanup;
99864   }
99865
99866   /* Check that the trigger name is not reserved and that no trigger of the
99867   ** specified name exists */
99868   zName = sqlite3NameFromToken(db, pName);
99869   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
99870     goto trigger_cleanup;
99871   }
99872   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99873   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
99874                       zName, sqlite3Strlen30(zName)) ){
99875     if( !noErr ){
99876       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
99877     }else{
99878       assert( !db->init.busy );
99879       sqlite3CodeVerifySchema(pParse, iDb);
99880     }
99881     goto trigger_cleanup;
99882   }
99883
99884   /* Do not create a trigger on a system table */
99885   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
99886     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
99887     pParse->nErr++;
99888     goto trigger_cleanup;
99889   }
99890
99891   /* INSTEAD of triggers are only for views and views only support INSTEAD
99892   ** of triggers.
99893   */
99894   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
99895     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
99896         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
99897     goto trigger_cleanup;
99898   }
99899   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
99900     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
99901         " trigger on table: %S", pTableName, 0);
99902     goto trigger_cleanup;
99903   }
99904   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99905
99906 #ifndef SQLITE_OMIT_AUTHORIZATION
99907   {
99908     int code = SQLITE_CREATE_TRIGGER;
99909     const char *zDb = db->aDb[iTabDb].zName;
99910     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
99911     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
99912     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
99913       goto trigger_cleanup;
99914     }
99915     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
99916       goto trigger_cleanup;
99917     }
99918   }
99919 #endif
99920
99921   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
99922   ** cannot appear on views.  So we might as well translate every
99923   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
99924   ** elsewhere.
99925   */
99926   if (tr_tm == TK_INSTEAD){
99927     tr_tm = TK_BEFORE;
99928   }
99929
99930   /* Build the Trigger object */
99931   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
99932   if( pTrigger==0 ) goto trigger_cleanup;
99933   pTrigger->zName = zName;
99934   zName = 0;
99935   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
99936   pTrigger->pSchema = db->aDb[iDb].pSchema;
99937   pTrigger->pTabSchema = pTab->pSchema;
99938   pTrigger->op = (u8)op;
99939   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
99940   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
99941   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
99942   assert( pParse->pNewTrigger==0 );
99943   pParse->pNewTrigger = pTrigger;
99944
99945 trigger_cleanup:
99946   sqlite3DbFree(db, zName);
99947   sqlite3SrcListDelete(db, pTableName);
99948   sqlite3IdListDelete(db, pColumns);
99949   sqlite3ExprDelete(db, pWhen);
99950   if( !pParse->pNewTrigger ){
99951     sqlite3DeleteTrigger(db, pTrigger);
99952   }else{
99953     assert( pParse->pNewTrigger==pTrigger );
99954   }
99955 }
99956
99957 /*
99958 ** This routine is called after all of the trigger actions have been parsed
99959 ** in order to complete the process of building the trigger.
99960 */
99961 SQLITE_PRIVATE void sqlite3FinishTrigger(
99962   Parse *pParse,          /* Parser context */
99963   TriggerStep *pStepList, /* The triggered program */
99964   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
99965 ){
99966   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
99967   char *zName;                            /* Name of trigger */
99968   sqlite3 *db = pParse->db;               /* The database */
99969   DbFixer sFix;                           /* Fixer object */
99970   int iDb;                                /* Database containing the trigger */
99971   Token nameToken;                        /* Trigger name for error reporting */
99972
99973   pParse->pNewTrigger = 0;
99974   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
99975   zName = pTrig->zName;
99976   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
99977   pTrig->step_list = pStepList;
99978   while( pStepList ){
99979     pStepList->pTrig = pTrig;
99980     pStepList = pStepList->pNext;
99981   }
99982   nameToken.z = pTrig->zName;
99983   nameToken.n = sqlite3Strlen30(nameToken.z);
99984   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
99985           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
99986     goto triggerfinish_cleanup;
99987   }
99988
99989   /* if we are not initializing,
99990   ** build the sqlite_master entry
99991   */
99992   if( !db->init.busy ){
99993     Vdbe *v;
99994     char *z;
99995
99996     /* Make an entry in the sqlite_master table */
99997     v = sqlite3GetVdbe(pParse);
99998     if( v==0 ) goto triggerfinish_cleanup;
99999     sqlite3BeginWriteOperation(pParse, 0, iDb);
100000     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
100001     sqlite3NestedParse(pParse,
100002        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
100003        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
100004        pTrig->table, z);
100005     sqlite3DbFree(db, z);
100006     sqlite3ChangeCookie(pParse, iDb);
100007     sqlite3VdbeAddParseSchemaOp(v, iDb,
100008         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
100009   }
100010
100011   if( db->init.busy ){
100012     Trigger *pLink = pTrig;
100013     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
100014     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100015     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
100016     if( pTrig ){
100017       db->mallocFailed = 1;
100018     }else if( pLink->pSchema==pLink->pTabSchema ){
100019       Table *pTab;
100020       int n = sqlite3Strlen30(pLink->table);
100021       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
100022       assert( pTab!=0 );
100023       pLink->pNext = pTab->pTrigger;
100024       pTab->pTrigger = pLink;
100025     }
100026   }
100027
100028 triggerfinish_cleanup:
100029   sqlite3DeleteTrigger(db, pTrig);
100030   assert( !pParse->pNewTrigger );
100031   sqlite3DeleteTriggerStep(db, pStepList);
100032 }
100033
100034 /*
100035 ** Turn a SELECT statement (that the pSelect parameter points to) into
100036 ** a trigger step.  Return a pointer to a TriggerStep structure.
100037 **
100038 ** The parser calls this routine when it finds a SELECT statement in
100039 ** body of a TRIGGER.  
100040 */
100041 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
100042   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
100043   if( pTriggerStep==0 ) {
100044     sqlite3SelectDelete(db, pSelect);
100045     return 0;
100046   }
100047   pTriggerStep->op = TK_SELECT;
100048   pTriggerStep->pSelect = pSelect;
100049   pTriggerStep->orconf = OE_Default;
100050   return pTriggerStep;
100051 }
100052
100053 /*
100054 ** Allocate space to hold a new trigger step.  The allocated space
100055 ** holds both the TriggerStep object and the TriggerStep.target.z string.
100056 **
100057 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
100058 */
100059 static TriggerStep *triggerStepAllocate(
100060   sqlite3 *db,                /* Database connection */
100061   u8 op,                      /* Trigger opcode */
100062   Token *pName                /* The target name */
100063 ){
100064   TriggerStep *pTriggerStep;
100065
100066   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
100067   if( pTriggerStep ){
100068     char *z = (char*)&pTriggerStep[1];
100069     memcpy(z, pName->z, pName->n);
100070     pTriggerStep->target.z = z;
100071     pTriggerStep->target.n = pName->n;
100072     pTriggerStep->op = op;
100073   }
100074   return pTriggerStep;
100075 }
100076
100077 /*
100078 ** Build a trigger step out of an INSERT statement.  Return a pointer
100079 ** to the new trigger step.
100080 **
100081 ** The parser calls this routine when it sees an INSERT inside the
100082 ** body of a trigger.
100083 */
100084 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
100085   sqlite3 *db,        /* The database connection */
100086   Token *pTableName,  /* Name of the table into which we insert */
100087   IdList *pColumn,    /* List of columns in pTableName to insert into */
100088   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
100089   Select *pSelect,    /* A SELECT statement that supplies values */
100090   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
100091 ){
100092   TriggerStep *pTriggerStep;
100093
100094   assert(pEList == 0 || pSelect == 0);
100095   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
100096
100097   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
100098   if( pTriggerStep ){
100099     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
100100     pTriggerStep->pIdList = pColumn;
100101     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
100102     pTriggerStep->orconf = orconf;
100103   }else{
100104     sqlite3IdListDelete(db, pColumn);
100105   }
100106   sqlite3ExprListDelete(db, pEList);
100107   sqlite3SelectDelete(db, pSelect);
100108
100109   return pTriggerStep;
100110 }
100111
100112 /*
100113 ** Construct a trigger step that implements an UPDATE statement and return
100114 ** a pointer to that trigger step.  The parser calls this routine when it
100115 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
100116 */
100117 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
100118   sqlite3 *db,         /* The database connection */
100119   Token *pTableName,   /* Name of the table to be updated */
100120   ExprList *pEList,    /* The SET clause: list of column and new values */
100121   Expr *pWhere,        /* The WHERE clause */
100122   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
100123 ){
100124   TriggerStep *pTriggerStep;
100125
100126   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
100127   if( pTriggerStep ){
100128     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
100129     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
100130     pTriggerStep->orconf = orconf;
100131   }
100132   sqlite3ExprListDelete(db, pEList);
100133   sqlite3ExprDelete(db, pWhere);
100134   return pTriggerStep;
100135 }
100136
100137 /*
100138 ** Construct a trigger step that implements a DELETE statement and return
100139 ** a pointer to that trigger step.  The parser calls this routine when it
100140 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
100141 */
100142 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
100143   sqlite3 *db,            /* Database connection */
100144   Token *pTableName,      /* The table from which rows are deleted */
100145   Expr *pWhere            /* The WHERE clause */
100146 ){
100147   TriggerStep *pTriggerStep;
100148
100149   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
100150   if( pTriggerStep ){
100151     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
100152     pTriggerStep->orconf = OE_Default;
100153   }
100154   sqlite3ExprDelete(db, pWhere);
100155   return pTriggerStep;
100156 }
100157
100158 /* 
100159 ** Recursively delete a Trigger structure
100160 */
100161 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
100162   if( pTrigger==0 ) return;
100163   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
100164   sqlite3DbFree(db, pTrigger->zName);
100165   sqlite3DbFree(db, pTrigger->table);
100166   sqlite3ExprDelete(db, pTrigger->pWhen);
100167   sqlite3IdListDelete(db, pTrigger->pColumns);
100168   sqlite3DbFree(db, pTrigger);
100169 }
100170
100171 /*
100172 ** This function is called to drop a trigger from the database schema. 
100173 **
100174 ** This may be called directly from the parser and therefore identifies
100175 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
100176 ** same job as this routine except it takes a pointer to the trigger
100177 ** instead of the trigger name.
100178 **/
100179 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
100180   Trigger *pTrigger = 0;
100181   int i;
100182   const char *zDb;
100183   const char *zName;
100184   int nName;
100185   sqlite3 *db = pParse->db;
100186
100187   if( db->mallocFailed ) goto drop_trigger_cleanup;
100188   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
100189     goto drop_trigger_cleanup;
100190   }
100191
100192   assert( pName->nSrc==1 );
100193   zDb = pName->a[0].zDatabase;
100194   zName = pName->a[0].zName;
100195   nName = sqlite3Strlen30(zName);
100196   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
100197   for(i=OMIT_TEMPDB; i<db->nDb; i++){
100198     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
100199     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
100200     assert( sqlite3SchemaMutexHeld(db, j, 0) );
100201     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
100202     if( pTrigger ) break;
100203   }
100204   if( !pTrigger ){
100205     if( !noErr ){
100206       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
100207     }else{
100208       sqlite3CodeVerifyNamedSchema(pParse, zDb);
100209     }
100210     pParse->checkSchema = 1;
100211     goto drop_trigger_cleanup;
100212   }
100213   sqlite3DropTriggerPtr(pParse, pTrigger);
100214
100215 drop_trigger_cleanup:
100216   sqlite3SrcListDelete(db, pName);
100217 }
100218
100219 /*
100220 ** Return a pointer to the Table structure for the table that a trigger
100221 ** is set on.
100222 */
100223 static Table *tableOfTrigger(Trigger *pTrigger){
100224   int n = sqlite3Strlen30(pTrigger->table);
100225   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
100226 }
100227
100228
100229 /*
100230 ** Drop a trigger given a pointer to that trigger. 
100231 */
100232 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
100233   Table   *pTable;
100234   Vdbe *v;
100235   sqlite3 *db = pParse->db;
100236   int iDb;
100237
100238   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
100239   assert( iDb>=0 && iDb<db->nDb );
100240   pTable = tableOfTrigger(pTrigger);
100241   assert( pTable );
100242   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
100243 #ifndef SQLITE_OMIT_AUTHORIZATION
100244   {
100245     int code = SQLITE_DROP_TRIGGER;
100246     const char *zDb = db->aDb[iDb].zName;
100247     const char *zTab = SCHEMA_TABLE(iDb);
100248     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
100249     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
100250       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
100251       return;
100252     }
100253   }
100254 #endif
100255
100256   /* Generate code to destroy the database record of the trigger.
100257   */
100258   assert( pTable!=0 );
100259   if( (v = sqlite3GetVdbe(pParse))!=0 ){
100260     int base;
100261     static const VdbeOpList dropTrigger[] = {
100262       { OP_Rewind,     0, ADDR(9),  0},
100263       { OP_String8,    0, 1,        0}, /* 1 */
100264       { OP_Column,     0, 1,        2},
100265       { OP_Ne,         2, ADDR(8),  1},
100266       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
100267       { OP_Column,     0, 0,        2},
100268       { OP_Ne,         2, ADDR(8),  1},
100269       { OP_Delete,     0, 0,        0},
100270       { OP_Next,       0, ADDR(1),  0}, /* 8 */
100271     };
100272
100273     sqlite3BeginWriteOperation(pParse, 0, iDb);
100274     sqlite3OpenMasterTable(pParse, iDb);
100275     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
100276     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
100277     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
100278     sqlite3ChangeCookie(pParse, iDb);
100279     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
100280     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
100281     if( pParse->nMem<3 ){
100282       pParse->nMem = 3;
100283     }
100284   }
100285 }
100286
100287 /*
100288 ** Remove a trigger from the hash tables of the sqlite* pointer.
100289 */
100290 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
100291   Trigger *pTrigger;
100292   Hash *pHash;
100293
100294   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100295   pHash = &(db->aDb[iDb].pSchema->trigHash);
100296   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
100297   if( ALWAYS(pTrigger) ){
100298     if( pTrigger->pSchema==pTrigger->pTabSchema ){
100299       Table *pTab = tableOfTrigger(pTrigger);
100300       Trigger **pp;
100301       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
100302       *pp = (*pp)->pNext;
100303     }
100304     sqlite3DeleteTrigger(db, pTrigger);
100305     db->flags |= SQLITE_InternChanges;
100306   }
100307 }
100308
100309 /*
100310 ** pEList is the SET clause of an UPDATE statement.  Each entry
100311 ** in pEList is of the format <id>=<expr>.  If any of the entries
100312 ** in pEList have an <id> which matches an identifier in pIdList,
100313 ** then return TRUE.  If pIdList==NULL, then it is considered a
100314 ** wildcard that matches anything.  Likewise if pEList==NULL then
100315 ** it matches anything so always return true.  Return false only
100316 ** if there is no match.
100317 */
100318 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
100319   int e;
100320   if( pIdList==0 || NEVER(pEList==0) ) return 1;
100321   for(e=0; e<pEList->nExpr; e++){
100322     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
100323   }
100324   return 0; 
100325 }
100326
100327 /*
100328 ** Return a list of all triggers on table pTab if there exists at least
100329 ** one trigger that must be fired when an operation of type 'op' is 
100330 ** performed on the table, and, if that operation is an UPDATE, if at
100331 ** least one of the columns in pChanges is being modified.
100332 */
100333 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
100334   Parse *pParse,          /* Parse context */
100335   Table *pTab,            /* The table the contains the triggers */
100336   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
100337   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
100338   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100339 ){
100340   int mask = 0;
100341   Trigger *pList = 0;
100342   Trigger *p;
100343
100344   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
100345     pList = sqlite3TriggerList(pParse, pTab);
100346   }
100347   assert( pList==0 || IsVirtual(pTab)==0 );
100348   for(p=pList; p; p=p->pNext){
100349     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
100350       mask |= p->tr_tm;
100351     }
100352   }
100353   if( pMask ){
100354     *pMask = mask;
100355   }
100356   return (mask ? pList : 0);
100357 }
100358
100359 /*
100360 ** Convert the pStep->target token into a SrcList and return a pointer
100361 ** to that SrcList.
100362 **
100363 ** This routine adds a specific database name, if needed, to the target when
100364 ** forming the SrcList.  This prevents a trigger in one database from
100365 ** referring to a target in another database.  An exception is when the
100366 ** trigger is in TEMP in which case it can refer to any other database it
100367 ** wants.
100368 */
100369 static SrcList *targetSrcList(
100370   Parse *pParse,       /* The parsing context */
100371   TriggerStep *pStep   /* The trigger containing the target token */
100372 ){
100373   int iDb;             /* Index of the database to use */
100374   SrcList *pSrc;       /* SrcList to be returned */
100375
100376   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
100377   if( pSrc ){
100378     assert( pSrc->nSrc>0 );
100379     assert( pSrc->a!=0 );
100380     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
100381     if( iDb==0 || iDb>=2 ){
100382       sqlite3 *db = pParse->db;
100383       assert( iDb<pParse->db->nDb );
100384       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
100385     }
100386   }
100387   return pSrc;
100388 }
100389
100390 /*
100391 ** Generate VDBE code for the statements inside the body of a single 
100392 ** trigger.
100393 */
100394 static int codeTriggerProgram(
100395   Parse *pParse,            /* The parser context */
100396   TriggerStep *pStepList,   /* List of statements inside the trigger body */
100397   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
100398 ){
100399   TriggerStep *pStep;
100400   Vdbe *v = pParse->pVdbe;
100401   sqlite3 *db = pParse->db;
100402
100403   assert( pParse->pTriggerTab && pParse->pToplevel );
100404   assert( pStepList );
100405   assert( v!=0 );
100406   for(pStep=pStepList; pStep; pStep=pStep->pNext){
100407     /* Figure out the ON CONFLICT policy that will be used for this step
100408     ** of the trigger program. If the statement that caused this trigger
100409     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
100410     ** the ON CONFLICT policy that was specified as part of the trigger
100411     ** step statement. Example:
100412     **
100413     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
100414     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
100415     **   END;
100416     **
100417     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
100418     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
100419     */
100420     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
100421
100422     /* Clear the cookieGoto flag. When coding triggers, the cookieGoto 
100423     ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
100424     ** that it is not safe to refactor constants (this happens after the
100425     ** start of the first loop in the SQL statement is coded - at that 
100426     ** point code may be conditionally executed, so it is no longer safe to 
100427     ** initialize constant register values).  */
100428     assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
100429     pParse->cookieGoto = 0;
100430
100431     switch( pStep->op ){
100432       case TK_UPDATE: {
100433         sqlite3Update(pParse, 
100434           targetSrcList(pParse, pStep),
100435           sqlite3ExprListDup(db, pStep->pExprList, 0), 
100436           sqlite3ExprDup(db, pStep->pWhere, 0), 
100437           pParse->eOrconf
100438         );
100439         break;
100440       }
100441       case TK_INSERT: {
100442         sqlite3Insert(pParse, 
100443           targetSrcList(pParse, pStep),
100444           sqlite3ExprListDup(db, pStep->pExprList, 0), 
100445           sqlite3SelectDup(db, pStep->pSelect, 0), 
100446           sqlite3IdListDup(db, pStep->pIdList), 
100447           pParse->eOrconf
100448         );
100449         break;
100450       }
100451       case TK_DELETE: {
100452         sqlite3DeleteFrom(pParse, 
100453           targetSrcList(pParse, pStep),
100454           sqlite3ExprDup(db, pStep->pWhere, 0)
100455         );
100456         break;
100457       }
100458       default: assert( pStep->op==TK_SELECT ); {
100459         SelectDest sDest;
100460         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
100461         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
100462         sqlite3Select(pParse, pSelect, &sDest);
100463         sqlite3SelectDelete(db, pSelect);
100464         break;
100465       }
100466     } 
100467     if( pStep->op!=TK_SELECT ){
100468       sqlite3VdbeAddOp0(v, OP_ResetCount);
100469     }
100470   }
100471
100472   return 0;
100473 }
100474
100475 #ifdef SQLITE_DEBUG
100476 /*
100477 ** This function is used to add VdbeComment() annotations to a VDBE
100478 ** program. It is not used in production code, only for debugging.
100479 */
100480 static const char *onErrorText(int onError){
100481   switch( onError ){
100482     case OE_Abort:    return "abort";
100483     case OE_Rollback: return "rollback";
100484     case OE_Fail:     return "fail";
100485     case OE_Replace:  return "replace";
100486     case OE_Ignore:   return "ignore";
100487     case OE_Default:  return "default";
100488   }
100489   return "n/a";
100490 }
100491 #endif
100492
100493 /*
100494 ** Parse context structure pFrom has just been used to create a sub-vdbe
100495 ** (trigger program). If an error has occurred, transfer error information
100496 ** from pFrom to pTo.
100497 */
100498 static void transferParseError(Parse *pTo, Parse *pFrom){
100499   assert( pFrom->zErrMsg==0 || pFrom->nErr );
100500   assert( pTo->zErrMsg==0 || pTo->nErr );
100501   if( pTo->nErr==0 ){
100502     pTo->zErrMsg = pFrom->zErrMsg;
100503     pTo->nErr = pFrom->nErr;
100504   }else{
100505     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
100506   }
100507 }
100508
100509 /*
100510 ** Create and populate a new TriggerPrg object with a sub-program 
100511 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
100512 */
100513 static TriggerPrg *codeRowTrigger(
100514   Parse *pParse,       /* Current parse context */
100515   Trigger *pTrigger,   /* Trigger to code */
100516   Table *pTab,         /* The table pTrigger is attached to */
100517   int orconf           /* ON CONFLICT policy to code trigger program with */
100518 ){
100519   Parse *pTop = sqlite3ParseToplevel(pParse);
100520   sqlite3 *db = pParse->db;   /* Database handle */
100521   TriggerPrg *pPrg;           /* Value to return */
100522   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
100523   Vdbe *v;                    /* Temporary VM */
100524   NameContext sNC;            /* Name context for sub-vdbe */
100525   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
100526   Parse *pSubParse;           /* Parse context for sub-vdbe */
100527   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
100528
100529   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
100530   assert( pTop->pVdbe );
100531
100532   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
100533   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
100534   ** list of the top-level Parse object sooner rather than later.  */
100535   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
100536   if( !pPrg ) return 0;
100537   pPrg->pNext = pTop->pTriggerPrg;
100538   pTop->pTriggerPrg = pPrg;
100539   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
100540   if( !pProgram ) return 0;
100541   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
100542   pPrg->pTrigger = pTrigger;
100543   pPrg->orconf = orconf;
100544   pPrg->aColmask[0] = 0xffffffff;
100545   pPrg->aColmask[1] = 0xffffffff;
100546
100547   /* Allocate and populate a new Parse context to use for coding the 
100548   ** trigger sub-program.  */
100549   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
100550   if( !pSubParse ) return 0;
100551   memset(&sNC, 0, sizeof(sNC));
100552   sNC.pParse = pSubParse;
100553   pSubParse->db = db;
100554   pSubParse->pTriggerTab = pTab;
100555   pSubParse->pToplevel = pTop;
100556   pSubParse->zAuthContext = pTrigger->zName;
100557   pSubParse->eTriggerOp = pTrigger->op;
100558   pSubParse->nQueryLoop = pParse->nQueryLoop;
100559
100560   v = sqlite3GetVdbe(pSubParse);
100561   if( v ){
100562     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
100563       pTrigger->zName, onErrorText(orconf),
100564       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
100565         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
100566         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
100567         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
100568       pTab->zName
100569     ));
100570 #ifndef SQLITE_OMIT_TRACE
100571     sqlite3VdbeChangeP4(v, -1, 
100572       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
100573     );
100574 #endif
100575
100576     /* If one was specified, code the WHEN clause. If it evaluates to false
100577     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
100578     ** OP_Halt inserted at the end of the program.  */
100579     if( pTrigger->pWhen ){
100580       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
100581       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
100582        && db->mallocFailed==0 
100583       ){
100584         iEndTrigger = sqlite3VdbeMakeLabel(v);
100585         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
100586       }
100587       sqlite3ExprDelete(db, pWhen);
100588     }
100589
100590     /* Code the trigger program into the sub-vdbe. */
100591     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
100592
100593     /* Insert an OP_Halt at the end of the sub-program. */
100594     if( iEndTrigger ){
100595       sqlite3VdbeResolveLabel(v, iEndTrigger);
100596     }
100597     sqlite3VdbeAddOp0(v, OP_Halt);
100598     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
100599
100600     transferParseError(pParse, pSubParse);
100601     if( db->mallocFailed==0 ){
100602       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
100603     }
100604     pProgram->nMem = pSubParse->nMem;
100605     pProgram->nCsr = pSubParse->nTab;
100606     pProgram->nOnce = pSubParse->nOnce;
100607     pProgram->token = (void *)pTrigger;
100608     pPrg->aColmask[0] = pSubParse->oldmask;
100609     pPrg->aColmask[1] = pSubParse->newmask;
100610     sqlite3VdbeDelete(v);
100611   }
100612
100613   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
100614   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
100615   sqlite3StackFree(db, pSubParse);
100616
100617   return pPrg;
100618 }
100619     
100620 /*
100621 ** Return a pointer to a TriggerPrg object containing the sub-program for
100622 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
100623 ** TriggerPrg object exists, a new object is allocated and populated before
100624 ** being returned.
100625 */
100626 static TriggerPrg *getRowTrigger(
100627   Parse *pParse,       /* Current parse context */
100628   Trigger *pTrigger,   /* Trigger to code */
100629   Table *pTab,         /* The table trigger pTrigger is attached to */
100630   int orconf           /* ON CONFLICT algorithm. */
100631 ){
100632   Parse *pRoot = sqlite3ParseToplevel(pParse);
100633   TriggerPrg *pPrg;
100634
100635   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
100636
100637   /* It may be that this trigger has already been coded (or is in the
100638   ** process of being coded). If this is the case, then an entry with
100639   ** a matching TriggerPrg.pTrigger field will be present somewhere
100640   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
100641   for(pPrg=pRoot->pTriggerPrg; 
100642       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
100643       pPrg=pPrg->pNext
100644   );
100645
100646   /* If an existing TriggerPrg could not be located, create a new one. */
100647   if( !pPrg ){
100648     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
100649   }
100650
100651   return pPrg;
100652 }
100653
100654 /*
100655 ** Generate code for the trigger program associated with trigger p on 
100656 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
100657 ** function are the same as those described in the header function for
100658 ** sqlite3CodeRowTrigger()
100659 */
100660 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
100661   Parse *pParse,       /* Parse context */
100662   Trigger *p,          /* Trigger to code */
100663   Table *pTab,         /* The table to code triggers from */
100664   int reg,             /* Reg array containing OLD.* and NEW.* values */
100665   int orconf,          /* ON CONFLICT policy */
100666   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
100667 ){
100668   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
100669   TriggerPrg *pPrg;
100670   pPrg = getRowTrigger(pParse, p, pTab, orconf);
100671   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
100672
100673   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
100674   ** is a pointer to the sub-vdbe containing the trigger program.  */
100675   if( pPrg ){
100676     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
100677
100678     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
100679     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
100680     VdbeComment(
100681         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
100682
100683     /* Set the P5 operand of the OP_Program instruction to non-zero if
100684     ** recursive invocation of this trigger program is disallowed. Recursive
100685     ** invocation is disallowed if (a) the sub-program is really a trigger,
100686     ** not a foreign key action, and (b) the flag to enable recursive triggers
100687     ** is clear.  */
100688     sqlite3VdbeChangeP5(v, (u8)bRecursive);
100689   }
100690 }
100691
100692 /*
100693 ** This is called to code the required FOR EACH ROW triggers for an operation
100694 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
100695 ** is given by the op paramater. The tr_tm parameter determines whether the
100696 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
100697 ** parameter pChanges is passed the list of columns being modified.
100698 **
100699 ** If there are no triggers that fire at the specified time for the specified
100700 ** operation on pTab, this function is a no-op.
100701 **
100702 ** The reg argument is the address of the first in an array of registers 
100703 ** that contain the values substituted for the new.* and old.* references
100704 ** in the trigger program. If N is the number of columns in table pTab
100705 ** (a copy of pTab->nCol), then registers are populated as follows:
100706 **
100707 **   Register       Contains
100708 **   ------------------------------------------------------
100709 **   reg+0          OLD.rowid
100710 **   reg+1          OLD.* value of left-most column of pTab
100711 **   ...            ...
100712 **   reg+N          OLD.* value of right-most column of pTab
100713 **   reg+N+1        NEW.rowid
100714 **   reg+N+2        OLD.* value of left-most column of pTab
100715 **   ...            ...
100716 **   reg+N+N+1      NEW.* value of right-most column of pTab
100717 **
100718 ** For ON DELETE triggers, the registers containing the NEW.* values will
100719 ** never be accessed by the trigger program, so they are not allocated or 
100720 ** populated by the caller (there is no data to populate them with anyway). 
100721 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
100722 ** are never accessed, and so are not allocated by the caller. So, for an
100723 ** ON INSERT trigger, the value passed to this function as parameter reg
100724 ** is not a readable register, although registers (reg+N) through 
100725 ** (reg+N+N+1) are.
100726 **
100727 ** Parameter orconf is the default conflict resolution algorithm for the
100728 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
100729 ** is the instruction that control should jump to if a trigger program
100730 ** raises an IGNORE exception.
100731 */
100732 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
100733   Parse *pParse,       /* Parse context */
100734   Trigger *pTrigger,   /* List of triggers on table pTab */
100735   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
100736   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100737   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
100738   Table *pTab,         /* The table to code triggers from */
100739   int reg,             /* The first in an array of registers (see above) */
100740   int orconf,          /* ON CONFLICT policy */
100741   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
100742 ){
100743   Trigger *p;          /* Used to iterate through pTrigger list */
100744
100745   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
100746   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
100747   assert( (op==TK_UPDATE)==(pChanges!=0) );
100748
100749   for(p=pTrigger; p; p=p->pNext){
100750
100751     /* Sanity checking:  The schema for the trigger and for the table are
100752     ** always defined.  The trigger must be in the same schema as the table
100753     ** or else it must be a TEMP trigger. */
100754     assert( p->pSchema!=0 );
100755     assert( p->pTabSchema!=0 );
100756     assert( p->pSchema==p->pTabSchema 
100757          || p->pSchema==pParse->db->aDb[1].pSchema );
100758
100759     /* Determine whether we should code this trigger */
100760     if( p->op==op 
100761      && p->tr_tm==tr_tm 
100762      && checkColumnOverlap(p->pColumns, pChanges)
100763     ){
100764       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
100765     }
100766   }
100767 }
100768
100769 /*
100770 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
100771 ** This function returns a 32-bit bitmask indicating which columns of the 
100772 ** old.* or new.* tables actually are used by triggers. This information 
100773 ** may be used by the caller, for example, to avoid having to load the entire
100774 ** old.* record into memory when executing an UPDATE or DELETE command.
100775 **
100776 ** Bit 0 of the returned mask is set if the left-most column of the
100777 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
100778 ** the second leftmost column value is required, and so on. If there
100779 ** are more than 32 columns in the table, and at least one of the columns
100780 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
100781 **
100782 ** It is not possible to determine if the old.rowid or new.rowid column is 
100783 ** accessed by triggers. The caller must always assume that it is.
100784 **
100785 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
100786 ** applies to the old.* table. If 1, the new.* table.
100787 **
100788 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
100789 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
100790 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
100791 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
100792 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
100793 */
100794 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
100795   Parse *pParse,       /* Parse context */
100796   Trigger *pTrigger,   /* List of triggers on table pTab */
100797   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100798   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
100799   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100800   Table *pTab,         /* The table to code triggers from */
100801   int orconf           /* Default ON CONFLICT policy for trigger steps */
100802 ){
100803   const int op = pChanges ? TK_UPDATE : TK_DELETE;
100804   u32 mask = 0;
100805   Trigger *p;
100806
100807   assert( isNew==1 || isNew==0 );
100808   for(p=pTrigger; p; p=p->pNext){
100809     if( p->op==op && (tr_tm&p->tr_tm)
100810      && checkColumnOverlap(p->pColumns,pChanges)
100811     ){
100812       TriggerPrg *pPrg;
100813       pPrg = getRowTrigger(pParse, p, pTab, orconf);
100814       if( pPrg ){
100815         mask |= pPrg->aColmask[isNew];
100816       }
100817     }
100818   }
100819
100820   return mask;
100821 }
100822
100823 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
100824
100825 /************** End of trigger.c *********************************************/
100826 /************** Begin file update.c ******************************************/
100827 /*
100828 ** 2001 September 15
100829 **
100830 ** The author disclaims copyright to this source code.  In place of
100831 ** a legal notice, here is a blessing:
100832 **
100833 **    May you do good and not evil.
100834 **    May you find forgiveness for yourself and forgive others.
100835 **    May you share freely, never taking more than you give.
100836 **
100837 *************************************************************************
100838 ** This file contains C code routines that are called by the parser
100839 ** to handle UPDATE statements.
100840 */
100841
100842 #ifndef SQLITE_OMIT_VIRTUALTABLE
100843 /* Forward declaration */
100844 static void updateVirtualTable(
100845   Parse *pParse,       /* The parsing context */
100846   SrcList *pSrc,       /* The virtual table to be modified */
100847   Table *pTab,         /* The virtual table */
100848   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
100849   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
100850   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
100851   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
100852   int onError          /* ON CONFLICT strategy */
100853 );
100854 #endif /* SQLITE_OMIT_VIRTUALTABLE */
100855
100856 /*
100857 ** The most recently coded instruction was an OP_Column to retrieve the
100858 ** i-th column of table pTab. This routine sets the P4 parameter of the 
100859 ** OP_Column to the default value, if any.
100860 **
100861 ** The default value of a column is specified by a DEFAULT clause in the 
100862 ** column definition. This was either supplied by the user when the table
100863 ** was created, or added later to the table definition by an ALTER TABLE
100864 ** command. If the latter, then the row-records in the table btree on disk
100865 ** may not contain a value for the column and the default value, taken
100866 ** from the P4 parameter of the OP_Column instruction, is returned instead.
100867 ** If the former, then all row-records are guaranteed to include a value
100868 ** for the column and the P4 value is not required.
100869 **
100870 ** Column definitions created by an ALTER TABLE command may only have 
100871 ** literal default values specified: a number, null or a string. (If a more
100872 ** complicated default expression value was provided, it is evaluated 
100873 ** when the ALTER TABLE is executed and one of the literal values written
100874 ** into the sqlite_master table.)
100875 **
100876 ** Therefore, the P4 parameter is only required if the default value for
100877 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
100878 ** function is capable of transforming these types of expressions into
100879 ** sqlite3_value objects.
100880 **
100881 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
100882 ** on register iReg. This is used when an equivalent integer value is 
100883 ** stored in place of an 8-byte floating point value in order to save 
100884 ** space.
100885 */
100886 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
100887   assert( pTab!=0 );
100888   if( !pTab->pSelect ){
100889     sqlite3_value *pValue;
100890     u8 enc = ENC(sqlite3VdbeDb(v));
100891     Column *pCol = &pTab->aCol[i];
100892     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
100893     assert( i<pTab->nCol );
100894     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
100895                          pCol->affinity, &pValue);
100896     if( pValue ){
100897       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
100898     }
100899 #ifndef SQLITE_OMIT_FLOATING_POINT
100900     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
100901       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
100902     }
100903 #endif
100904   }
100905 }
100906
100907 /*
100908 ** Process an UPDATE statement.
100909 **
100910 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
100911 **          \_______/ \________/     \______/       \________________/
100912 *            onError   pTabList      pChanges             pWhere
100913 */
100914 SQLITE_PRIVATE void sqlite3Update(
100915   Parse *pParse,         /* The parser context */
100916   SrcList *pTabList,     /* The table in which we should change things */
100917   ExprList *pChanges,    /* Things to be changed */
100918   Expr *pWhere,          /* The WHERE clause.  May be null */
100919   int onError            /* How to handle constraint errors */
100920 ){
100921   int i, j;              /* Loop counters */
100922   Table *pTab;           /* The table to be updated */
100923   int addr = 0;          /* VDBE instruction address of the start of the loop */
100924   WhereInfo *pWInfo;     /* Information about the WHERE clause */
100925   Vdbe *v;               /* The virtual database engine */
100926   Index *pIdx;           /* For looping over indices */
100927   int nIdx;              /* Number of indices that need updating */
100928   int iCur;              /* VDBE Cursor number of pTab */
100929   sqlite3 *db;           /* The database structure */
100930   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
100931   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
100932                          ** an expression for the i-th column of the table.
100933                          ** aXRef[i]==-1 if the i-th column is not changed. */
100934   int chngRowid;         /* True if the record number is being changed */
100935   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
100936   int openAll = 0;       /* True if all indices need to be opened */
100937   AuthContext sContext;  /* The authorization context */
100938   NameContext sNC;       /* The name-context to resolve expressions in */
100939   int iDb;               /* Database containing the table being updated */
100940   int okOnePass;         /* True for one-pass algorithm without the FIFO */
100941   int hasFK;             /* True if foreign key processing is required */
100942
100943 #ifndef SQLITE_OMIT_TRIGGER
100944   int isView;            /* True when updating a view (INSTEAD OF trigger) */
100945   Trigger *pTrigger;     /* List of triggers on pTab, if required */
100946   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100947 #endif
100948   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
100949
100950   /* Register Allocations */
100951   int regRowCount = 0;   /* A count of rows changed */
100952   int regOldRowid;       /* The old rowid */
100953   int regNewRowid;       /* The new rowid */
100954   int regNew;            /* Content of the NEW.* table in triggers */
100955   int regOld = 0;        /* Content of OLD.* table in triggers */
100956   int regRowSet = 0;     /* Rowset of rows to be updated */
100957
100958   memset(&sContext, 0, sizeof(sContext));
100959   db = pParse->db;
100960   if( pParse->nErr || db->mallocFailed ){
100961     goto update_cleanup;
100962   }
100963   assert( pTabList->nSrc==1 );
100964
100965   /* Locate the table which we want to update. 
100966   */
100967   pTab = sqlite3SrcListLookup(pParse, pTabList);
100968   if( pTab==0 ) goto update_cleanup;
100969   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100970
100971   /* Figure out if we have any triggers and if the table being
100972   ** updated is a view.
100973   */
100974 #ifndef SQLITE_OMIT_TRIGGER
100975   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
100976   isView = pTab->pSelect!=0;
100977   assert( pTrigger || tmask==0 );
100978 #else
100979 # define pTrigger 0
100980 # define isView 0
100981 # define tmask 0
100982 #endif
100983 #ifdef SQLITE_OMIT_VIEW
100984 # undef isView
100985 # define isView 0
100986 #endif
100987
100988   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
100989     goto update_cleanup;
100990   }
100991   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
100992     goto update_cleanup;
100993   }
100994   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
100995   if( aXRef==0 ) goto update_cleanup;
100996   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
100997
100998   /* Allocate a cursors for the main database table and for all indices.
100999   ** The index cursors might not be used, but if they are used they
101000   ** need to occur right after the database cursor.  So go ahead and
101001   ** allocate enough space, just in case.
101002   */
101003   pTabList->a[0].iCursor = iCur = pParse->nTab++;
101004   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101005     pParse->nTab++;
101006   }
101007
101008   /* Initialize the name-context */
101009   memset(&sNC, 0, sizeof(sNC));
101010   sNC.pParse = pParse;
101011   sNC.pSrcList = pTabList;
101012
101013   /* Resolve the column names in all the expressions of the
101014   ** of the UPDATE statement.  Also find the column index
101015   ** for each column to be updated in the pChanges array.  For each
101016   ** column to be updated, make sure we have authorization to change
101017   ** that column.
101018   */
101019   chngRowid = 0;
101020   for(i=0; i<pChanges->nExpr; i++){
101021     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
101022       goto update_cleanup;
101023     }
101024     for(j=0; j<pTab->nCol; j++){
101025       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
101026         if( j==pTab->iPKey ){
101027           chngRowid = 1;
101028           pRowidExpr = pChanges->a[i].pExpr;
101029         }
101030         aXRef[j] = i;
101031         break;
101032       }
101033     }
101034     if( j>=pTab->nCol ){
101035       if( sqlite3IsRowid(pChanges->a[i].zName) ){
101036         chngRowid = 1;
101037         pRowidExpr = pChanges->a[i].pExpr;
101038       }else{
101039         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
101040         pParse->checkSchema = 1;
101041         goto update_cleanup;
101042       }
101043     }
101044 #ifndef SQLITE_OMIT_AUTHORIZATION
101045     {
101046       int rc;
101047       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
101048                            pTab->aCol[j].zName, db->aDb[iDb].zName);
101049       if( rc==SQLITE_DENY ){
101050         goto update_cleanup;
101051       }else if( rc==SQLITE_IGNORE ){
101052         aXRef[j] = -1;
101053       }
101054     }
101055 #endif
101056   }
101057
101058   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
101059
101060   /* Allocate memory for the array aRegIdx[].  There is one entry in the
101061   ** array for each index associated with table being updated.  Fill in
101062   ** the value with a register number for indices that are to be used
101063   ** and with zero for unused indices.
101064   */
101065   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
101066   if( nIdx>0 ){
101067     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
101068     if( aRegIdx==0 ) goto update_cleanup;
101069   }
101070   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
101071     int reg;
101072     if( hasFK || chngRowid ){
101073       reg = ++pParse->nMem;
101074     }else{
101075       reg = 0;
101076       for(i=0; i<pIdx->nColumn; i++){
101077         if( aXRef[pIdx->aiColumn[i]]>=0 ){
101078           reg = ++pParse->nMem;
101079           break;
101080         }
101081       }
101082     }
101083     aRegIdx[j] = reg;
101084   }
101085
101086   /* Begin generating code. */
101087   v = sqlite3GetVdbe(pParse);
101088   if( v==0 ) goto update_cleanup;
101089   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
101090   sqlite3BeginWriteOperation(pParse, 1, iDb);
101091
101092 #ifndef SQLITE_OMIT_VIRTUALTABLE
101093   /* Virtual tables must be handled separately */
101094   if( IsVirtual(pTab) ){
101095     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
101096                        pWhere, onError);
101097     pWhere = 0;
101098     pTabList = 0;
101099     goto update_cleanup;
101100   }
101101 #endif
101102
101103   /* Allocate required registers. */
101104   regRowSet = ++pParse->nMem;
101105   regOldRowid = regNewRowid = ++pParse->nMem;
101106   if( pTrigger || hasFK ){
101107     regOld = pParse->nMem + 1;
101108     pParse->nMem += pTab->nCol;
101109   }
101110   if( chngRowid || pTrigger || hasFK ){
101111     regNewRowid = ++pParse->nMem;
101112   }
101113   regNew = pParse->nMem + 1;
101114   pParse->nMem += pTab->nCol;
101115
101116   /* Start the view context. */
101117   if( isView ){
101118     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
101119   }
101120
101121   /* If we are trying to update a view, realize that view into
101122   ** a ephemeral table.
101123   */
101124 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
101125   if( isView ){
101126     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
101127   }
101128 #endif
101129
101130   /* Resolve the column names in all the expressions in the
101131   ** WHERE clause.
101132   */
101133   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
101134     goto update_cleanup;
101135   }
101136
101137   /* Begin the database scan
101138   */
101139   sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
101140   pWInfo = sqlite3WhereBegin(
101141       pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
101142   );
101143   if( pWInfo==0 ) goto update_cleanup;
101144   okOnePass = pWInfo->okOnePass;
101145
101146   /* Remember the rowid of every item to be updated.
101147   */
101148   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
101149   if( !okOnePass ){
101150     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
101151   }
101152
101153   /* End the database scan loop.
101154   */
101155   sqlite3WhereEnd(pWInfo);
101156
101157   /* Initialize the count of updated rows
101158   */
101159   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
101160     regRowCount = ++pParse->nMem;
101161     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
101162   }
101163
101164   if( !isView ){
101165     /* 
101166     ** Open every index that needs updating.  Note that if any
101167     ** index could potentially invoke a REPLACE conflict resolution 
101168     ** action, then we need to open all indices because we might need
101169     ** to be deleting some records.
101170     */
101171     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
101172     if( onError==OE_Replace ){
101173       openAll = 1;
101174     }else{
101175       openAll = 0;
101176       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101177         if( pIdx->onError==OE_Replace ){
101178           openAll = 1;
101179           break;
101180         }
101181       }
101182     }
101183     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
101184       assert( aRegIdx );
101185       if( openAll || aRegIdx[i]>0 ){
101186         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
101187         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
101188                        (char*)pKey, P4_KEYINFO_HANDOFF);
101189         assert( pParse->nTab>iCur+i+1 );
101190       }
101191     }
101192   }
101193
101194   /* Top of the update loop */
101195   if( okOnePass ){
101196     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
101197     addr = sqlite3VdbeAddOp0(v, OP_Goto);
101198     sqlite3VdbeJumpHere(v, a1);
101199   }else{
101200     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
101201   }
101202
101203   /* Make cursor iCur point to the record that is being updated. If
101204   ** this record does not exist for some reason (deleted by a trigger,
101205   ** for example, then jump to the next iteration of the RowSet loop.  */
101206   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
101207
101208   /* If the record number will change, set register regNewRowid to
101209   ** contain the new value. If the record number is not being modified,
101210   ** then regNewRowid is the same register as regOldRowid, which is
101211   ** already populated.  */
101212   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
101213   if( chngRowid ){
101214     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
101215     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
101216   }
101217
101218   /* If there are triggers on this table, populate an array of registers 
101219   ** with the required old.* column data.  */
101220   if( hasFK || pTrigger ){
101221     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
101222     oldmask |= sqlite3TriggerColmask(pParse, 
101223         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
101224     );
101225     for(i=0; i<pTab->nCol; i++){
101226       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
101227         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
101228       }else{
101229         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
101230       }
101231     }
101232     if( chngRowid==0 ){
101233       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
101234     }
101235   }
101236
101237   /* Populate the array of registers beginning at regNew with the new
101238   ** row data. This array is used to check constaints, create the new
101239   ** table and index records, and as the values for any new.* references
101240   ** made by triggers.
101241   **
101242   ** If there are one or more BEFORE triggers, then do not populate the
101243   ** registers associated with columns that are (a) not modified by
101244   ** this UPDATE statement and (b) not accessed by new.* references. The
101245   ** values for registers not modified by the UPDATE must be reloaded from 
101246   ** the database after the BEFORE triggers are fired anyway (as the trigger 
101247   ** may have modified them). So not loading those that are not going to
101248   ** be used eliminates some redundant opcodes.
101249   */
101250   newmask = sqlite3TriggerColmask(
101251       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
101252   );
101253   sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
101254   for(i=0; i<pTab->nCol; i++){
101255     if( i==pTab->iPKey ){
101256       /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
101257     }else{
101258       j = aXRef[i];
101259       if( j>=0 ){
101260         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
101261       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
101262         /* This branch loads the value of a column that will not be changed 
101263         ** into a register. This is done if there are no BEFORE triggers, or
101264         ** if there are one or more BEFORE triggers that use this value via
101265         ** a new.* reference in a trigger program.
101266         */
101267         testcase( i==31 );
101268         testcase( i==32 );
101269         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
101270         sqlite3ColumnDefault(v, pTab, i, regNew+i);
101271       }
101272     }
101273   }
101274
101275   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
101276   ** verified. One could argue that this is wrong.
101277   */
101278   if( tmask&TRIGGER_BEFORE ){
101279     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
101280     sqlite3TableAffinityStr(v, pTab);
101281     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
101282         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
101283
101284     /* The row-trigger may have deleted the row being updated. In this
101285     ** case, jump to the next row. No updates or AFTER triggers are 
101286     ** required. This behavior - what happens when the row being updated
101287     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
101288     ** documentation.
101289     */
101290     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
101291
101292     /* If it did not delete it, the row-trigger may still have modified 
101293     ** some of the columns of the row being updated. Load the values for 
101294     ** all columns not modified by the update statement into their 
101295     ** registers in case this has happened.
101296     */
101297     for(i=0; i<pTab->nCol; i++){
101298       if( aXRef[i]<0 && i!=pTab->iPKey ){
101299         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
101300         sqlite3ColumnDefault(v, pTab, i, regNew+i);
101301       }
101302     }
101303   }
101304
101305   if( !isView ){
101306     int j1;                       /* Address of jump instruction */
101307
101308     /* Do constraint checks. */
101309     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
101310         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
101311
101312     /* Do FK constraint checks. */
101313     if( hasFK ){
101314       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
101315     }
101316
101317     /* Delete the index entries associated with the current record.  */
101318     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
101319     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
101320   
101321     /* If changing the record number, delete the old record.  */
101322     if( hasFK || chngRowid ){
101323       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
101324     }
101325     sqlite3VdbeJumpHere(v, j1);
101326
101327     if( hasFK ){
101328       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
101329     }
101330   
101331     /* Insert the new index entries and the new record. */
101332     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
101333
101334     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
101335     ** handle rows (possibly in other tables) that refer via a foreign key
101336     ** to the row just updated. */ 
101337     if( hasFK ){
101338       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
101339     }
101340   }
101341
101342   /* Increment the row counter 
101343   */
101344   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
101345     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
101346   }
101347
101348   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
101349       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
101350
101351   /* Repeat the above with the next record to be updated, until
101352   ** all record selected by the WHERE clause have been updated.
101353   */
101354   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
101355   sqlite3VdbeJumpHere(v, addr);
101356
101357   /* Close all tables */
101358   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
101359     assert( aRegIdx );
101360     if( openAll || aRegIdx[i]>0 ){
101361       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
101362     }
101363   }
101364   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
101365
101366   /* Update the sqlite_sequence table by storing the content of the
101367   ** maximum rowid counter values recorded while inserting into
101368   ** autoincrement tables.
101369   */
101370   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
101371     sqlite3AutoincrementEnd(pParse);
101372   }
101373
101374   /*
101375   ** Return the number of rows that were changed. If this routine is 
101376   ** generating code because of a call to sqlite3NestedParse(), do not
101377   ** invoke the callback function.
101378   */
101379   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
101380     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
101381     sqlite3VdbeSetNumCols(v, 1);
101382     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
101383   }
101384
101385 update_cleanup:
101386   sqlite3AuthContextPop(&sContext);
101387   sqlite3DbFree(db, aRegIdx);
101388   sqlite3DbFree(db, aXRef);
101389   sqlite3SrcListDelete(db, pTabList);
101390   sqlite3ExprListDelete(db, pChanges);
101391   sqlite3ExprDelete(db, pWhere);
101392   return;
101393 }
101394 /* Make sure "isView" and other macros defined above are undefined. Otherwise
101395 ** thely may interfere with compilation of other functions in this file
101396 ** (or in another file, if this file becomes part of the amalgamation).  */
101397 #ifdef isView
101398  #undef isView
101399 #endif
101400 #ifdef pTrigger
101401  #undef pTrigger
101402 #endif
101403
101404 #ifndef SQLITE_OMIT_VIRTUALTABLE
101405 /*
101406 ** Generate code for an UPDATE of a virtual table.
101407 **
101408 ** The strategy is that we create an ephemerial table that contains
101409 ** for each row to be changed:
101410 **
101411 **   (A)  The original rowid of that row.
101412 **   (B)  The revised rowid for the row. (note1)
101413 **   (C)  The content of every column in the row.
101414 **
101415 ** Then we loop over this ephemeral table and for each row in
101416 ** the ephermeral table call VUpdate.
101417 **
101418 ** When finished, drop the ephemeral table.
101419 **
101420 ** (note1) Actually, if we know in advance that (A) is always the same
101421 ** as (B) we only store (A), then duplicate (A) when pulling
101422 ** it out of the ephemeral table before calling VUpdate.
101423 */
101424 static void updateVirtualTable(
101425   Parse *pParse,       /* The parsing context */
101426   SrcList *pSrc,       /* The virtual table to be modified */
101427   Table *pTab,         /* The virtual table */
101428   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
101429   Expr *pRowid,        /* Expression used to recompute the rowid */
101430   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
101431   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
101432   int onError          /* ON CONFLICT strategy */
101433 ){
101434   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
101435   ExprList *pEList = 0;     /* The result set of the SELECT statement */
101436   Select *pSelect = 0;      /* The SELECT statement */
101437   Expr *pExpr;              /* Temporary expression */
101438   int ephemTab;             /* Table holding the result of the SELECT */
101439   int i;                    /* Loop counter */
101440   int addr;                 /* Address of top of loop */
101441   int iReg;                 /* First register in set passed to OP_VUpdate */
101442   sqlite3 *db = pParse->db; /* Database connection */
101443   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
101444   SelectDest dest;
101445
101446   /* Construct the SELECT statement that will find the new values for
101447   ** all updated rows. 
101448   */
101449   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
101450   if( pRowid ){
101451     pEList = sqlite3ExprListAppend(pParse, pEList,
101452                                    sqlite3ExprDup(db, pRowid, 0));
101453   }
101454   assert( pTab->iPKey<0 );
101455   for(i=0; i<pTab->nCol; i++){
101456     if( aXRef[i]>=0 ){
101457       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
101458     }else{
101459       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
101460     }
101461     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
101462   }
101463   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
101464   
101465   /* Create the ephemeral table into which the update results will
101466   ** be stored.
101467   */
101468   assert( v );
101469   ephemTab = pParse->nTab++;
101470   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
101471   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
101472
101473   /* fill the ephemeral table 
101474   */
101475   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
101476   sqlite3Select(pParse, pSelect, &dest);
101477
101478   /* Generate code to scan the ephemeral table and call VUpdate. */
101479   iReg = ++pParse->nMem;
101480   pParse->nMem += pTab->nCol+1;
101481   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
101482   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
101483   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
101484   for(i=0; i<pTab->nCol; i++){
101485     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
101486   }
101487   sqlite3VtabMakeWritable(pParse, pTab);
101488   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
101489   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
101490   sqlite3MayAbort(pParse);
101491   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
101492   sqlite3VdbeJumpHere(v, addr);
101493   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
101494
101495   /* Cleanup */
101496   sqlite3SelectDelete(db, pSelect);  
101497 }
101498 #endif /* SQLITE_OMIT_VIRTUALTABLE */
101499
101500 /************** End of update.c **********************************************/
101501 /************** Begin file vacuum.c ******************************************/
101502 /*
101503 ** 2003 April 6
101504 **
101505 ** The author disclaims copyright to this source code.  In place of
101506 ** a legal notice, here is a blessing:
101507 **
101508 **    May you do good and not evil.
101509 **    May you find forgiveness for yourself and forgive others.
101510 **    May you share freely, never taking more than you give.
101511 **
101512 *************************************************************************
101513 ** This file contains code used to implement the VACUUM command.
101514 **
101515 ** Most of the code in this file may be omitted by defining the
101516 ** SQLITE_OMIT_VACUUM macro.
101517 */
101518
101519 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
101520 /*
101521 ** Finalize a prepared statement.  If there was an error, store the
101522 ** text of the error message in *pzErrMsg.  Return the result code.
101523 */
101524 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
101525   int rc;
101526   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
101527   if( rc ){
101528     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
101529   }
101530   return rc;
101531 }
101532
101533 /*
101534 ** Execute zSql on database db. Return an error code.
101535 */
101536 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
101537   sqlite3_stmt *pStmt;
101538   VVA_ONLY( int rc; )
101539   if( !zSql ){
101540     return SQLITE_NOMEM;
101541   }
101542   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
101543     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
101544     return sqlite3_errcode(db);
101545   }
101546   VVA_ONLY( rc = ) sqlite3_step(pStmt);
101547   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
101548   return vacuumFinalize(db, pStmt, pzErrMsg);
101549 }
101550
101551 /*
101552 ** Execute zSql on database db. The statement returns exactly
101553 ** one column. Execute this as SQL on the same database.
101554 */
101555 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
101556   sqlite3_stmt *pStmt;
101557   int rc;
101558
101559   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
101560   if( rc!=SQLITE_OK ) return rc;
101561
101562   while( SQLITE_ROW==sqlite3_step(pStmt) ){
101563     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
101564     if( rc!=SQLITE_OK ){
101565       vacuumFinalize(db, pStmt, pzErrMsg);
101566       return rc;
101567     }
101568   }
101569
101570   return vacuumFinalize(db, pStmt, pzErrMsg);
101571 }
101572
101573 /*
101574 ** The non-standard VACUUM command is used to clean up the database,
101575 ** collapse free space, etc.  It is modelled after the VACUUM command
101576 ** in PostgreSQL.
101577 **
101578 ** In version 1.0.x of SQLite, the VACUUM command would call
101579 ** gdbm_reorganize() on all the database tables.  But beginning
101580 ** with 2.0.0, SQLite no longer uses GDBM so this command has
101581 ** become a no-op.
101582 */
101583 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
101584   Vdbe *v = sqlite3GetVdbe(pParse);
101585   if( v ){
101586     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
101587     sqlite3VdbeUsesBtree(v, 0);
101588   }
101589   return;
101590 }
101591
101592 /*
101593 ** This routine implements the OP_Vacuum opcode of the VDBE.
101594 */
101595 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
101596   int rc = SQLITE_OK;     /* Return code from service routines */
101597   Btree *pMain;           /* The database being vacuumed */
101598   Btree *pTemp;           /* The temporary database we vacuum into */
101599   char *zSql = 0;         /* SQL statements */
101600   int saved_flags;        /* Saved value of the db->flags */
101601   int saved_nChange;      /* Saved value of db->nChange */
101602   int saved_nTotalChange; /* Saved value of db->nTotalChange */
101603   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
101604   Db *pDb = 0;            /* Database to detach at end of vacuum */
101605   int isMemDb;            /* True if vacuuming a :memory: database */
101606   int nRes;               /* Bytes of reserved space at the end of each page */
101607   int nDb;                /* Number of attached databases */
101608
101609   if( !db->autoCommit ){
101610     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
101611     return SQLITE_ERROR;
101612   }
101613   if( db->activeVdbeCnt>1 ){
101614     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
101615     return SQLITE_ERROR;
101616   }
101617
101618   /* Save the current value of the database flags so that it can be 
101619   ** restored before returning. Then set the writable-schema flag, and
101620   ** disable CHECK and foreign key constraints.  */
101621   saved_flags = db->flags;
101622   saved_nChange = db->nChange;
101623   saved_nTotalChange = db->nTotalChange;
101624   saved_xTrace = db->xTrace;
101625   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
101626   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
101627   db->xTrace = 0;
101628
101629   pMain = db->aDb[0].pBt;
101630   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
101631
101632   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
101633   ** can be set to 'off' for this file, as it is not recovered if a crash
101634   ** occurs anyway. The integrity of the database is maintained by a
101635   ** (possibly synchronous) transaction opened on the main database before
101636   ** sqlite3BtreeCopyFile() is called.
101637   **
101638   ** An optimisation would be to use a non-journaled pager.
101639   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
101640   ** that actually made the VACUUM run slower.  Very little journalling
101641   ** actually occurs when doing a vacuum since the vacuum_db is initially
101642   ** empty.  Only the journal header is written.  Apparently it takes more
101643   ** time to parse and run the PRAGMA to turn journalling off than it does
101644   ** to write the journal header file.
101645   */
101646   nDb = db->nDb;
101647   if( sqlite3TempInMemory(db) ){
101648     zSql = "ATTACH ':memory:' AS vacuum_db;";
101649   }else{
101650     zSql = "ATTACH '' AS vacuum_db;";
101651   }
101652   rc = execSql(db, pzErrMsg, zSql);
101653   if( db->nDb>nDb ){
101654     pDb = &db->aDb[db->nDb-1];
101655     assert( strcmp(pDb->zName,"vacuum_db")==0 );
101656   }
101657   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101658   pTemp = db->aDb[db->nDb-1].pBt;
101659
101660   /* The call to execSql() to attach the temp database has left the file
101661   ** locked (as there was more than one active statement when the transaction
101662   ** to read the schema was concluded. Unlock it here so that this doesn't
101663   ** cause problems for the call to BtreeSetPageSize() below.  */
101664   sqlite3BtreeCommit(pTemp);
101665
101666   nRes = sqlite3BtreeGetReserve(pMain);
101667
101668   /* A VACUUM cannot change the pagesize of an encrypted database. */
101669 #ifdef SQLITE_HAS_CODEC
101670   if( db->nextPagesize ){
101671     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
101672     int nKey;
101673     char *zKey;
101674     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
101675     if( nKey ) db->nextPagesize = 0;
101676   }
101677 #endif
101678
101679   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
101680   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101681
101682   /* Begin a transaction and take an exclusive lock on the main database
101683   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
101684   ** to ensure that we do not try to change the page-size on a WAL database.
101685   */
101686   rc = execSql(db, pzErrMsg, "BEGIN;");
101687   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101688   rc = sqlite3BtreeBeginTrans(pMain, 2);
101689   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101690
101691   /* Do not attempt to change the page size for a WAL database */
101692   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
101693                                                ==PAGER_JOURNALMODE_WAL ){
101694     db->nextPagesize = 0;
101695   }
101696
101697   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
101698    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
101699    || NEVER(db->mallocFailed)
101700   ){
101701     rc = SQLITE_NOMEM;
101702     goto end_of_vacuum;
101703   }
101704
101705 #ifndef SQLITE_OMIT_AUTOVACUUM
101706   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
101707                                            sqlite3BtreeGetAutoVacuum(pMain));
101708 #endif
101709
101710   /* Query the schema of the main database. Create a mirror schema
101711   ** in the temporary database.
101712   */
101713   rc = execExecSql(db, pzErrMsg,
101714       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
101715       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
101716       "   AND rootpage>0"
101717   );
101718   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101719   rc = execExecSql(db, pzErrMsg,
101720       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
101721       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
101722   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101723   rc = execExecSql(db, pzErrMsg,
101724       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
101725       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
101726   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101727
101728   /* Loop through the tables in the main database. For each, do
101729   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
101730   ** the contents to the temporary database.
101731   */
101732   rc = execExecSql(db, pzErrMsg,
101733       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
101734       "|| ' SELECT * FROM main.' || quote(name) || ';'"
101735       "FROM main.sqlite_master "
101736       "WHERE type = 'table' AND name!='sqlite_sequence' "
101737       "  AND rootpage>0"
101738   );
101739   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101740
101741   /* Copy over the sequence table
101742   */
101743   rc = execExecSql(db, pzErrMsg,
101744       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
101745       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
101746   );
101747   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101748   rc = execExecSql(db, pzErrMsg,
101749       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
101750       "|| ' SELECT * FROM main.' || quote(name) || ';' "
101751       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
101752   );
101753   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101754
101755
101756   /* Copy the triggers, views, and virtual tables from the main database
101757   ** over to the temporary database.  None of these objects has any
101758   ** associated storage, so all we have to do is copy their entries
101759   ** from the SQLITE_MASTER table.
101760   */
101761   rc = execSql(db, pzErrMsg,
101762       "INSERT INTO vacuum_db.sqlite_master "
101763       "  SELECT type, name, tbl_name, rootpage, sql"
101764       "    FROM main.sqlite_master"
101765       "   WHERE type='view' OR type='trigger'"
101766       "      OR (type='table' AND rootpage=0)"
101767   );
101768   if( rc ) goto end_of_vacuum;
101769
101770   /* At this point, there is a write transaction open on both the 
101771   ** vacuum database and the main database. Assuming no error occurs,
101772   ** both transactions are closed by this block - the main database
101773   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
101774   ** call to sqlite3BtreeCommit().
101775   */
101776   {
101777     u32 meta;
101778     int i;
101779
101780     /* This array determines which meta meta values are preserved in the
101781     ** vacuum.  Even entries are the meta value number and odd entries
101782     ** are an increment to apply to the meta value after the vacuum.
101783     ** The increment is used to increase the schema cookie so that other
101784     ** connections to the same database will know to reread the schema.
101785     */
101786     static const unsigned char aCopy[] = {
101787        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
101788        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
101789        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
101790        BTREE_USER_VERSION,       0,  /* Preserve the user version */
101791     };
101792
101793     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
101794     assert( 1==sqlite3BtreeIsInTrans(pMain) );
101795
101796     /* Copy Btree meta values */
101797     for(i=0; i<ArraySize(aCopy); i+=2){
101798       /* GetMeta() and UpdateMeta() cannot fail in this context because
101799       ** we already have page 1 loaded into cache and marked dirty. */
101800       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
101801       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
101802       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
101803     }
101804
101805     rc = sqlite3BtreeCopyFile(pMain, pTemp);
101806     if( rc!=SQLITE_OK ) goto end_of_vacuum;
101807     rc = sqlite3BtreeCommit(pTemp);
101808     if( rc!=SQLITE_OK ) goto end_of_vacuum;
101809 #ifndef SQLITE_OMIT_AUTOVACUUM
101810     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
101811 #endif
101812   }
101813
101814   assert( rc==SQLITE_OK );
101815   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
101816
101817 end_of_vacuum:
101818   /* Restore the original value of db->flags */
101819   db->flags = saved_flags;
101820   db->nChange = saved_nChange;
101821   db->nTotalChange = saved_nTotalChange;
101822   db->xTrace = saved_xTrace;
101823   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
101824
101825   /* Currently there is an SQL level transaction open on the vacuum
101826   ** database. No locks are held on any other files (since the main file
101827   ** was committed at the btree level). So it safe to end the transaction
101828   ** by manually setting the autoCommit flag to true and detaching the
101829   ** vacuum database. The vacuum_db journal file is deleted when the pager
101830   ** is closed by the DETACH.
101831   */
101832   db->autoCommit = 1;
101833
101834   if( pDb ){
101835     sqlite3BtreeClose(pDb->pBt);
101836     pDb->pBt = 0;
101837     pDb->pSchema = 0;
101838   }
101839
101840   /* This both clears the schemas and reduces the size of the db->aDb[]
101841   ** array. */ 
101842   sqlite3ResetAllSchemasOfConnection(db);
101843
101844   return rc;
101845 }
101846
101847 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
101848
101849 /************** End of vacuum.c **********************************************/
101850 /************** Begin file vtab.c ********************************************/
101851 /*
101852 ** 2006 June 10
101853 **
101854 ** The author disclaims copyright to this source code.  In place of
101855 ** a legal notice, here is a blessing:
101856 **
101857 **    May you do good and not evil.
101858 **    May you find forgiveness for yourself and forgive others.
101859 **    May you share freely, never taking more than you give.
101860 **
101861 *************************************************************************
101862 ** This file contains code used to help implement virtual tables.
101863 */
101864 #ifndef SQLITE_OMIT_VIRTUALTABLE
101865
101866 /*
101867 ** Before a virtual table xCreate() or xConnect() method is invoked, the
101868 ** sqlite3.pVtabCtx member variable is set to point to an instance of
101869 ** this struct allocated on the stack. It is used by the implementation of 
101870 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
101871 ** are invoked only from within xCreate and xConnect methods.
101872 */
101873 struct VtabCtx {
101874   VTable *pVTable;    /* The virtual table being constructed */
101875   Table *pTab;        /* The Table object to which the virtual table belongs */
101876 };
101877
101878 /*
101879 ** The actual function that does the work of creating a new module.
101880 ** This function implements the sqlite3_create_module() and
101881 ** sqlite3_create_module_v2() interfaces.
101882 */
101883 static int createModule(
101884   sqlite3 *db,                    /* Database in which module is registered */
101885   const char *zName,              /* Name assigned to this module */
101886   const sqlite3_module *pModule,  /* The definition of the module */
101887   void *pAux,                     /* Context pointer for xCreate/xConnect */
101888   void (*xDestroy)(void *)        /* Module destructor function */
101889 ){
101890   int rc = SQLITE_OK;
101891   int nName;
101892
101893   sqlite3_mutex_enter(db->mutex);
101894   nName = sqlite3Strlen30(zName);
101895   if( sqlite3HashFind(&db->aModule, zName, nName) ){
101896     rc = SQLITE_MISUSE_BKPT;
101897   }else{
101898     Module *pMod;
101899     pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
101900     if( pMod ){
101901       Module *pDel;
101902       char *zCopy = (char *)(&pMod[1]);
101903       memcpy(zCopy, zName, nName+1);
101904       pMod->zName = zCopy;
101905       pMod->pModule = pModule;
101906       pMod->pAux = pAux;
101907       pMod->xDestroy = xDestroy;
101908       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
101909       assert( pDel==0 || pDel==pMod );
101910       if( pDel ){
101911         db->mallocFailed = 1;
101912         sqlite3DbFree(db, pDel);
101913       }
101914     }
101915   }
101916   rc = sqlite3ApiExit(db, rc);
101917   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
101918
101919   sqlite3_mutex_leave(db->mutex);
101920   return rc;
101921 }
101922
101923
101924 /*
101925 ** External API function used to create a new virtual-table module.
101926 */
101927 SQLITE_API int sqlite3_create_module(
101928   sqlite3 *db,                    /* Database in which module is registered */
101929   const char *zName,              /* Name assigned to this module */
101930   const sqlite3_module *pModule,  /* The definition of the module */
101931   void *pAux                      /* Context pointer for xCreate/xConnect */
101932 ){
101933   return createModule(db, zName, pModule, pAux, 0);
101934 }
101935
101936 /*
101937 ** External API function used to create a new virtual-table module.
101938 */
101939 SQLITE_API int sqlite3_create_module_v2(
101940   sqlite3 *db,                    /* Database in which module is registered */
101941   const char *zName,              /* Name assigned to this module */
101942   const sqlite3_module *pModule,  /* The definition of the module */
101943   void *pAux,                     /* Context pointer for xCreate/xConnect */
101944   void (*xDestroy)(void *)        /* Module destructor function */
101945 ){
101946   return createModule(db, zName, pModule, pAux, xDestroy);
101947 }
101948
101949 /*
101950 ** Lock the virtual table so that it cannot be disconnected.
101951 ** Locks nest.  Every lock should have a corresponding unlock.
101952 ** If an unlock is omitted, resources leaks will occur.  
101953 **
101954 ** If a disconnect is attempted while a virtual table is locked,
101955 ** the disconnect is deferred until all locks have been removed.
101956 */
101957 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
101958   pVTab->nRef++;
101959 }
101960
101961
101962 /*
101963 ** pTab is a pointer to a Table structure representing a virtual-table.
101964 ** Return a pointer to the VTable object used by connection db to access 
101965 ** this virtual-table, if one has been created, or NULL otherwise.
101966 */
101967 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
101968   VTable *pVtab;
101969   assert( IsVirtual(pTab) );
101970   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
101971   return pVtab;
101972 }
101973
101974 /*
101975 ** Decrement the ref-count on a virtual table object. When the ref-count
101976 ** reaches zero, call the xDisconnect() method to delete the object.
101977 */
101978 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
101979   sqlite3 *db = pVTab->db;
101980
101981   assert( db );
101982   assert( pVTab->nRef>0 );
101983   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
101984
101985   pVTab->nRef--;
101986   if( pVTab->nRef==0 ){
101987     sqlite3_vtab *p = pVTab->pVtab;
101988     if( p ){
101989       p->pModule->xDisconnect(p);
101990     }
101991     sqlite3DbFree(db, pVTab);
101992   }
101993 }
101994
101995 /*
101996 ** Table p is a virtual table. This function moves all elements in the
101997 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
101998 ** database connections to be disconnected at the next opportunity. 
101999 ** Except, if argument db is not NULL, then the entry associated with
102000 ** connection db is left in the p->pVTable list.
102001 */
102002 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
102003   VTable *pRet = 0;
102004   VTable *pVTable = p->pVTable;
102005   p->pVTable = 0;
102006
102007   /* Assert that the mutex (if any) associated with the BtShared database 
102008   ** that contains table p is held by the caller. See header comments 
102009   ** above function sqlite3VtabUnlockList() for an explanation of why
102010   ** this makes it safe to access the sqlite3.pDisconnect list of any
102011   ** database connection that may have an entry in the p->pVTable list.
102012   */
102013   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
102014
102015   while( pVTable ){
102016     sqlite3 *db2 = pVTable->db;
102017     VTable *pNext = pVTable->pNext;
102018     assert( db2 );
102019     if( db2==db ){
102020       pRet = pVTable;
102021       p->pVTable = pRet;
102022       pRet->pNext = 0;
102023     }else{
102024       pVTable->pNext = db2->pDisconnect;
102025       db2->pDisconnect = pVTable;
102026     }
102027     pVTable = pNext;
102028   }
102029
102030   assert( !db || pRet );
102031   return pRet;
102032 }
102033
102034 /*
102035 ** Table *p is a virtual table. This function removes the VTable object
102036 ** for table *p associated with database connection db from the linked
102037 ** list in p->pVTab. It also decrements the VTable ref count. This is
102038 ** used when closing database connection db to free all of its VTable
102039 ** objects without disturbing the rest of the Schema object (which may
102040 ** be being used by other shared-cache connections).
102041 */
102042 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
102043   VTable **ppVTab;
102044
102045   assert( IsVirtual(p) );
102046   assert( sqlite3BtreeHoldsAllMutexes(db) );
102047   assert( sqlite3_mutex_held(db->mutex) );
102048
102049   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
102050     if( (*ppVTab)->db==db  ){
102051       VTable *pVTab = *ppVTab;
102052       *ppVTab = pVTab->pNext;
102053       sqlite3VtabUnlock(pVTab);
102054       break;
102055     }
102056   }
102057 }
102058
102059
102060 /*
102061 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
102062 **
102063 ** This function may only be called when the mutexes associated with all
102064 ** shared b-tree databases opened using connection db are held by the 
102065 ** caller. This is done to protect the sqlite3.pDisconnect list. The
102066 ** sqlite3.pDisconnect list is accessed only as follows:
102067 **
102068 **   1) By this function. In this case, all BtShared mutexes and the mutex
102069 **      associated with the database handle itself must be held.
102070 **
102071 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
102072 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
102073 **      associated with the database the virtual table is stored in is held
102074 **      or, if the virtual table is stored in a non-sharable database, then
102075 **      the database handle mutex is held.
102076 **
102077 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
102078 ** by multiple threads. It is thread-safe.
102079 */
102080 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
102081   VTable *p = db->pDisconnect;
102082   db->pDisconnect = 0;
102083
102084   assert( sqlite3BtreeHoldsAllMutexes(db) );
102085   assert( sqlite3_mutex_held(db->mutex) );
102086
102087   if( p ){
102088     sqlite3ExpirePreparedStatements(db);
102089     do {
102090       VTable *pNext = p->pNext;
102091       sqlite3VtabUnlock(p);
102092       p = pNext;
102093     }while( p );
102094   }
102095 }
102096
102097 /*
102098 ** Clear any and all virtual-table information from the Table record.
102099 ** This routine is called, for example, just before deleting the Table
102100 ** record.
102101 **
102102 ** Since it is a virtual-table, the Table structure contains a pointer
102103 ** to the head of a linked list of VTable structures. Each VTable 
102104 ** structure is associated with a single sqlite3* user of the schema.
102105 ** The reference count of the VTable structure associated with database 
102106 ** connection db is decremented immediately (which may lead to the 
102107 ** structure being xDisconnected and free). Any other VTable structures
102108 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
102109 ** database connection.
102110 */
102111 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
102112   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
102113   if( p->azModuleArg ){
102114     int i;
102115     for(i=0; i<p->nModuleArg; i++){
102116       if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
102117     }
102118     sqlite3DbFree(db, p->azModuleArg);
102119   }
102120 }
102121
102122 /*
102123 ** Add a new module argument to pTable->azModuleArg[].
102124 ** The string is not copied - the pointer is stored.  The
102125 ** string will be freed automatically when the table is
102126 ** deleted.
102127 */
102128 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
102129   int i = pTable->nModuleArg++;
102130   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
102131   char **azModuleArg;
102132   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
102133   if( azModuleArg==0 ){
102134     int j;
102135     for(j=0; j<i; j++){
102136       sqlite3DbFree(db, pTable->azModuleArg[j]);
102137     }
102138     sqlite3DbFree(db, zArg);
102139     sqlite3DbFree(db, pTable->azModuleArg);
102140     pTable->nModuleArg = 0;
102141   }else{
102142     azModuleArg[i] = zArg;
102143     azModuleArg[i+1] = 0;
102144   }
102145   pTable->azModuleArg = azModuleArg;
102146 }
102147
102148 /*
102149 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
102150 ** statement.  The module name has been parsed, but the optional list
102151 ** of parameters that follow the module name are still pending.
102152 */
102153 SQLITE_PRIVATE void sqlite3VtabBeginParse(
102154   Parse *pParse,        /* Parsing context */
102155   Token *pName1,        /* Name of new table, or database name */
102156   Token *pName2,        /* Name of new table or NULL */
102157   Token *pModuleName,   /* Name of the module for the virtual table */
102158   int ifNotExists       /* No error if the table already exists */
102159 ){
102160   int iDb;              /* The database the table is being created in */
102161   Table *pTable;        /* The new virtual table */
102162   sqlite3 *db;          /* Database connection */
102163
102164   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
102165   pTable = pParse->pNewTable;
102166   if( pTable==0 ) return;
102167   assert( 0==pTable->pIndex );
102168
102169   db = pParse->db;
102170   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
102171   assert( iDb>=0 );
102172
102173   pTable->tabFlags |= TF_Virtual;
102174   pTable->nModuleArg = 0;
102175   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
102176   addModuleArgument(db, pTable, 0);
102177   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
102178   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
102179
102180 #ifndef SQLITE_OMIT_AUTHORIZATION
102181   /* Creating a virtual table invokes the authorization callback twice.
102182   ** The first invocation, to obtain permission to INSERT a row into the
102183   ** sqlite_master table, has already been made by sqlite3StartTable().
102184   ** The second call, to obtain permission to create the table, is made now.
102185   */
102186   if( pTable->azModuleArg ){
102187     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
102188             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
102189   }
102190 #endif
102191 }
102192
102193 /*
102194 ** This routine takes the module argument that has been accumulating
102195 ** in pParse->zArg[] and appends it to the list of arguments on the
102196 ** virtual table currently under construction in pParse->pTable.
102197 */
102198 static void addArgumentToVtab(Parse *pParse){
102199   if( pParse->sArg.z && pParse->pNewTable ){
102200     const char *z = (const char*)pParse->sArg.z;
102201     int n = pParse->sArg.n;
102202     sqlite3 *db = pParse->db;
102203     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
102204   }
102205 }
102206
102207 /*
102208 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
102209 ** has been completely parsed.
102210 */
102211 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
102212   Table *pTab = pParse->pNewTable;  /* The table being constructed */
102213   sqlite3 *db = pParse->db;         /* The database connection */
102214
102215   if( pTab==0 ) return;
102216   addArgumentToVtab(pParse);
102217   pParse->sArg.z = 0;
102218   if( pTab->nModuleArg<1 ) return;
102219   
102220   /* If the CREATE VIRTUAL TABLE statement is being entered for the
102221   ** first time (in other words if the virtual table is actually being
102222   ** created now instead of just being read out of sqlite_master) then
102223   ** do additional initialization work and store the statement text
102224   ** in the sqlite_master table.
102225   */
102226   if( !db->init.busy ){
102227     char *zStmt;
102228     char *zWhere;
102229     int iDb;
102230     Vdbe *v;
102231
102232     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
102233     if( pEnd ){
102234       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
102235     }
102236     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
102237
102238     /* A slot for the record has already been allocated in the 
102239     ** SQLITE_MASTER table.  We just need to update that slot with all
102240     ** the information we've collected.  
102241     **
102242     ** The VM register number pParse->regRowid holds the rowid of an
102243     ** entry in the sqlite_master table tht was created for this vtab
102244     ** by sqlite3StartTable().
102245     */
102246     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102247     sqlite3NestedParse(pParse,
102248       "UPDATE %Q.%s "
102249          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
102250        "WHERE rowid=#%d",
102251       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
102252       pTab->zName,
102253       pTab->zName,
102254       zStmt,
102255       pParse->regRowid
102256     );
102257     sqlite3DbFree(db, zStmt);
102258     v = sqlite3GetVdbe(pParse);
102259     sqlite3ChangeCookie(pParse, iDb);
102260
102261     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
102262     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
102263     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
102264     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
102265                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
102266   }
102267
102268   /* If we are rereading the sqlite_master table create the in-memory
102269   ** record of the table. The xConnect() method is not called until
102270   ** the first time the virtual table is used in an SQL statement. This
102271   ** allows a schema that contains virtual tables to be loaded before
102272   ** the required virtual table implementations are registered.  */
102273   else {
102274     Table *pOld;
102275     Schema *pSchema = pTab->pSchema;
102276     const char *zName = pTab->zName;
102277     int nName = sqlite3Strlen30(zName);
102278     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
102279     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
102280     if( pOld ){
102281       db->mallocFailed = 1;
102282       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
102283       return;
102284     }
102285     pParse->pNewTable = 0;
102286   }
102287 }
102288
102289 /*
102290 ** The parser calls this routine when it sees the first token
102291 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
102292 */
102293 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
102294   addArgumentToVtab(pParse);
102295   pParse->sArg.z = 0;
102296   pParse->sArg.n = 0;
102297 }
102298
102299 /*
102300 ** The parser calls this routine for each token after the first token
102301 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
102302 */
102303 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
102304   Token *pArg = &pParse->sArg;
102305   if( pArg->z==0 ){
102306     pArg->z = p->z;
102307     pArg->n = p->n;
102308   }else{
102309     assert(pArg->z < p->z);
102310     pArg->n = (int)(&p->z[p->n] - pArg->z);
102311   }
102312 }
102313
102314 /*
102315 ** Invoke a virtual table constructor (either xCreate or xConnect). The
102316 ** pointer to the function to invoke is passed as the fourth parameter
102317 ** to this procedure.
102318 */
102319 static int vtabCallConstructor(
102320   sqlite3 *db, 
102321   Table *pTab,
102322   Module *pMod,
102323   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
102324   char **pzErr
102325 ){
102326   VtabCtx sCtx, *pPriorCtx;
102327   VTable *pVTable;
102328   int rc;
102329   const char *const*azArg = (const char *const*)pTab->azModuleArg;
102330   int nArg = pTab->nModuleArg;
102331   char *zErr = 0;
102332   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
102333   int iDb;
102334
102335   if( !zModuleName ){
102336     return SQLITE_NOMEM;
102337   }
102338
102339   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
102340   if( !pVTable ){
102341     sqlite3DbFree(db, zModuleName);
102342     return SQLITE_NOMEM;
102343   }
102344   pVTable->db = db;
102345   pVTable->pMod = pMod;
102346
102347   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102348   pTab->azModuleArg[1] = db->aDb[iDb].zName;
102349
102350   /* Invoke the virtual table constructor */
102351   assert( &db->pVtabCtx );
102352   assert( xConstruct );
102353   sCtx.pTab = pTab;
102354   sCtx.pVTable = pVTable;
102355   pPriorCtx = db->pVtabCtx;
102356   db->pVtabCtx = &sCtx;
102357   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
102358   db->pVtabCtx = pPriorCtx;
102359   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
102360
102361   if( SQLITE_OK!=rc ){
102362     if( zErr==0 ){
102363       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
102364     }else {
102365       *pzErr = sqlite3MPrintf(db, "%s", zErr);
102366       sqlite3_free(zErr);
102367     }
102368     sqlite3DbFree(db, pVTable);
102369   }else if( ALWAYS(pVTable->pVtab) ){
102370     /* Justification of ALWAYS():  A correct vtab constructor must allocate
102371     ** the sqlite3_vtab object if successful.  */
102372     pVTable->pVtab->pModule = pMod->pModule;
102373     pVTable->nRef = 1;
102374     if( sCtx.pTab ){
102375       const char *zFormat = "vtable constructor did not declare schema: %s";
102376       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
102377       sqlite3VtabUnlock(pVTable);
102378       rc = SQLITE_ERROR;
102379     }else{
102380       int iCol;
102381       /* If everything went according to plan, link the new VTable structure
102382       ** into the linked list headed by pTab->pVTable. Then loop through the 
102383       ** columns of the table to see if any of them contain the token "hidden".
102384       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
102385       ** the type string.  */
102386       pVTable->pNext = pTab->pVTable;
102387       pTab->pVTable = pVTable;
102388
102389       for(iCol=0; iCol<pTab->nCol; iCol++){
102390         char *zType = pTab->aCol[iCol].zType;
102391         int nType;
102392         int i = 0;
102393         if( !zType ) continue;
102394         nType = sqlite3Strlen30(zType);
102395         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
102396           for(i=0; i<nType; i++){
102397             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
102398              && (zType[i+7]=='\0' || zType[i+7]==' ')
102399             ){
102400               i++;
102401               break;
102402             }
102403           }
102404         }
102405         if( i<nType ){
102406           int j;
102407           int nDel = 6 + (zType[i+6] ? 1 : 0);
102408           for(j=i; (j+nDel)<=nType; j++){
102409             zType[j] = zType[j+nDel];
102410           }
102411           if( zType[i]=='\0' && i>0 ){
102412             assert(zType[i-1]==' ');
102413             zType[i-1] = '\0';
102414           }
102415           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
102416         }
102417       }
102418     }
102419   }
102420
102421   sqlite3DbFree(db, zModuleName);
102422   return rc;
102423 }
102424
102425 /*
102426 ** This function is invoked by the parser to call the xConnect() method
102427 ** of the virtual table pTab. If an error occurs, an error code is returned 
102428 ** and an error left in pParse.
102429 **
102430 ** This call is a no-op if table pTab is not a virtual table.
102431 */
102432 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
102433   sqlite3 *db = pParse->db;
102434   const char *zMod;
102435   Module *pMod;
102436   int rc;
102437
102438   assert( pTab );
102439   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
102440     return SQLITE_OK;
102441   }
102442
102443   /* Locate the required virtual table module */
102444   zMod = pTab->azModuleArg[0];
102445   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
102446
102447   if( !pMod ){
102448     const char *zModule = pTab->azModuleArg[0];
102449     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
102450     rc = SQLITE_ERROR;
102451   }else{
102452     char *zErr = 0;
102453     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
102454     if( rc!=SQLITE_OK ){
102455       sqlite3ErrorMsg(pParse, "%s", zErr);
102456     }
102457     sqlite3DbFree(db, zErr);
102458   }
102459
102460   return rc;
102461 }
102462 /*
102463 ** Grow the db->aVTrans[] array so that there is room for at least one
102464 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
102465 */
102466 static int growVTrans(sqlite3 *db){
102467   const int ARRAY_INCR = 5;
102468
102469   /* Grow the sqlite3.aVTrans array if required */
102470   if( (db->nVTrans%ARRAY_INCR)==0 ){
102471     VTable **aVTrans;
102472     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
102473     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
102474     if( !aVTrans ){
102475       return SQLITE_NOMEM;
102476     }
102477     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
102478     db->aVTrans = aVTrans;
102479   }
102480
102481   return SQLITE_OK;
102482 }
102483
102484 /*
102485 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
102486 ** have already been reserved using growVTrans().
102487 */
102488 static void addToVTrans(sqlite3 *db, VTable *pVTab){
102489   /* Add pVtab to the end of sqlite3.aVTrans */
102490   db->aVTrans[db->nVTrans++] = pVTab;
102491   sqlite3VtabLock(pVTab);
102492 }
102493
102494 /*
102495 ** This function is invoked by the vdbe to call the xCreate method
102496 ** of the virtual table named zTab in database iDb. 
102497 **
102498 ** If an error occurs, *pzErr is set to point an an English language
102499 ** description of the error and an SQLITE_XXX error code is returned.
102500 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
102501 */
102502 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
102503   int rc = SQLITE_OK;
102504   Table *pTab;
102505   Module *pMod;
102506   const char *zMod;
102507
102508   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
102509   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
102510
102511   /* Locate the required virtual table module */
102512   zMod = pTab->azModuleArg[0];
102513   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
102514
102515   /* If the module has been registered and includes a Create method, 
102516   ** invoke it now. If the module has not been registered, return an 
102517   ** error. Otherwise, do nothing.
102518   */
102519   if( !pMod ){
102520     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
102521     rc = SQLITE_ERROR;
102522   }else{
102523     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
102524   }
102525
102526   /* Justification of ALWAYS():  The xConstructor method is required to
102527   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
102528   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
102529     rc = growVTrans(db);
102530     if( rc==SQLITE_OK ){
102531       addToVTrans(db, sqlite3GetVTable(db, pTab));
102532     }
102533   }
102534
102535   return rc;
102536 }
102537
102538 /*
102539 ** This function is used to set the schema of a virtual table.  It is only
102540 ** valid to call this function from within the xCreate() or xConnect() of a
102541 ** virtual table module.
102542 */
102543 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
102544   Parse *pParse;
102545
102546   int rc = SQLITE_OK;
102547   Table *pTab;
102548   char *zErr = 0;
102549
102550   sqlite3_mutex_enter(db->mutex);
102551   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
102552     sqlite3Error(db, SQLITE_MISUSE, 0);
102553     sqlite3_mutex_leave(db->mutex);
102554     return SQLITE_MISUSE_BKPT;
102555   }
102556   assert( (pTab->tabFlags & TF_Virtual)!=0 );
102557
102558   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
102559   if( pParse==0 ){
102560     rc = SQLITE_NOMEM;
102561   }else{
102562     pParse->declareVtab = 1;
102563     pParse->db = db;
102564     pParse->nQueryLoop = 1;
102565   
102566     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
102567      && pParse->pNewTable
102568      && !db->mallocFailed
102569      && !pParse->pNewTable->pSelect
102570      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
102571     ){
102572       if( !pTab->aCol ){
102573         pTab->aCol = pParse->pNewTable->aCol;
102574         pTab->nCol = pParse->pNewTable->nCol;
102575         pParse->pNewTable->nCol = 0;
102576         pParse->pNewTable->aCol = 0;
102577       }
102578       db->pVtabCtx->pTab = 0;
102579     }else{
102580       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
102581       sqlite3DbFree(db, zErr);
102582       rc = SQLITE_ERROR;
102583     }
102584     pParse->declareVtab = 0;
102585   
102586     if( pParse->pVdbe ){
102587       sqlite3VdbeFinalize(pParse->pVdbe);
102588     }
102589     sqlite3DeleteTable(db, pParse->pNewTable);
102590     sqlite3StackFree(db, pParse);
102591   }
102592
102593   assert( (rc&0xff)==rc );
102594   rc = sqlite3ApiExit(db, rc);
102595   sqlite3_mutex_leave(db->mutex);
102596   return rc;
102597 }
102598
102599 /*
102600 ** This function is invoked by the vdbe to call the xDestroy method
102601 ** of the virtual table named zTab in database iDb. This occurs
102602 ** when a DROP TABLE is mentioned.
102603 **
102604 ** This call is a no-op if zTab is not a virtual table.
102605 */
102606 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
102607   int rc = SQLITE_OK;
102608   Table *pTab;
102609
102610   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
102611   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
102612     VTable *p = vtabDisconnectAll(db, pTab);
102613
102614     assert( rc==SQLITE_OK );
102615     rc = p->pMod->pModule->xDestroy(p->pVtab);
102616
102617     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
102618     if( rc==SQLITE_OK ){
102619       assert( pTab->pVTable==p && p->pNext==0 );
102620       p->pVtab = 0;
102621       pTab->pVTable = 0;
102622       sqlite3VtabUnlock(p);
102623     }
102624   }
102625
102626   return rc;
102627 }
102628
102629 /*
102630 ** This function invokes either the xRollback or xCommit method
102631 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
102632 ** called is identified by the second argument, "offset", which is
102633 ** the offset of the method to call in the sqlite3_module structure.
102634 **
102635 ** The array is cleared after invoking the callbacks. 
102636 */
102637 static void callFinaliser(sqlite3 *db, int offset){
102638   int i;
102639   if( db->aVTrans ){
102640     for(i=0; i<db->nVTrans; i++){
102641       VTable *pVTab = db->aVTrans[i];
102642       sqlite3_vtab *p = pVTab->pVtab;
102643       if( p ){
102644         int (*x)(sqlite3_vtab *);
102645         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
102646         if( x ) x(p);
102647       }
102648       pVTab->iSavepoint = 0;
102649       sqlite3VtabUnlock(pVTab);
102650     }
102651     sqlite3DbFree(db, db->aVTrans);
102652     db->nVTrans = 0;
102653     db->aVTrans = 0;
102654   }
102655 }
102656
102657 /*
102658 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
102659 ** array. Return the error code for the first error that occurs, or
102660 ** SQLITE_OK if all xSync operations are successful.
102661 **
102662 ** Set *pzErrmsg to point to a buffer that should be released using 
102663 ** sqlite3DbFree() containing an error message, if one is available.
102664 */
102665 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
102666   int i;
102667   int rc = SQLITE_OK;
102668   VTable **aVTrans = db->aVTrans;
102669
102670   db->aVTrans = 0;
102671   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
102672     int (*x)(sqlite3_vtab *);
102673     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
102674     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
102675       rc = x(pVtab);
102676       sqlite3DbFree(db, *pzErrmsg);
102677       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
102678       sqlite3_free(pVtab->zErrMsg);
102679     }
102680   }
102681   db->aVTrans = aVTrans;
102682   return rc;
102683 }
102684
102685 /*
102686 ** Invoke the xRollback method of all virtual tables in the 
102687 ** sqlite3.aVTrans array. Then clear the array itself.
102688 */
102689 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
102690   callFinaliser(db, offsetof(sqlite3_module,xRollback));
102691   return SQLITE_OK;
102692 }
102693
102694 /*
102695 ** Invoke the xCommit method of all virtual tables in the 
102696 ** sqlite3.aVTrans array. Then clear the array itself.
102697 */
102698 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
102699   callFinaliser(db, offsetof(sqlite3_module,xCommit));
102700   return SQLITE_OK;
102701 }
102702
102703 /*
102704 ** If the virtual table pVtab supports the transaction interface
102705 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
102706 ** not currently open, invoke the xBegin method now.
102707 **
102708 ** If the xBegin call is successful, place the sqlite3_vtab pointer
102709 ** in the sqlite3.aVTrans array.
102710 */
102711 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
102712   int rc = SQLITE_OK;
102713   const sqlite3_module *pModule;
102714
102715   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
102716   ** than zero, then this function is being called from within a
102717   ** virtual module xSync() callback. It is illegal to write to 
102718   ** virtual module tables in this case, so return SQLITE_LOCKED.
102719   */
102720   if( sqlite3VtabInSync(db) ){
102721     return SQLITE_LOCKED;
102722   }
102723   if( !pVTab ){
102724     return SQLITE_OK;
102725   } 
102726   pModule = pVTab->pVtab->pModule;
102727
102728   if( pModule->xBegin ){
102729     int i;
102730
102731     /* If pVtab is already in the aVTrans array, return early */
102732     for(i=0; i<db->nVTrans; i++){
102733       if( db->aVTrans[i]==pVTab ){
102734         return SQLITE_OK;
102735       }
102736     }
102737
102738     /* Invoke the xBegin method. If successful, add the vtab to the 
102739     ** sqlite3.aVTrans[] array. */
102740     rc = growVTrans(db);
102741     if( rc==SQLITE_OK ){
102742       rc = pModule->xBegin(pVTab->pVtab);
102743       if( rc==SQLITE_OK ){
102744         addToVTrans(db, pVTab);
102745       }
102746     }
102747   }
102748   return rc;
102749 }
102750
102751 /*
102752 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
102753 ** virtual tables that currently have an open transaction. Pass iSavepoint
102754 ** as the second argument to the virtual table method invoked.
102755 **
102756 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
102757 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
102758 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
102759 ** an open transaction is invoked.
102760 **
102761 ** If any virtual table method returns an error code other than SQLITE_OK, 
102762 ** processing is abandoned and the error returned to the caller of this
102763 ** function immediately. If all calls to virtual table methods are successful,
102764 ** SQLITE_OK is returned.
102765 */
102766 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
102767   int rc = SQLITE_OK;
102768
102769   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
102770   assert( iSavepoint>=0 );
102771   if( db->aVTrans ){
102772     int i;
102773     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
102774       VTable *pVTab = db->aVTrans[i];
102775       const sqlite3_module *pMod = pVTab->pMod->pModule;
102776       if( pVTab->pVtab && pMod->iVersion>=2 ){
102777         int (*xMethod)(sqlite3_vtab *, int);
102778         switch( op ){
102779           case SAVEPOINT_BEGIN:
102780             xMethod = pMod->xSavepoint;
102781             pVTab->iSavepoint = iSavepoint+1;
102782             break;
102783           case SAVEPOINT_ROLLBACK:
102784             xMethod = pMod->xRollbackTo;
102785             break;
102786           default:
102787             xMethod = pMod->xRelease;
102788             break;
102789         }
102790         if( xMethod && pVTab->iSavepoint>iSavepoint ){
102791           rc = xMethod(pVTab->pVtab, iSavepoint);
102792         }
102793       }
102794     }
102795   }
102796   return rc;
102797 }
102798
102799 /*
102800 ** The first parameter (pDef) is a function implementation.  The
102801 ** second parameter (pExpr) is the first argument to this function.
102802 ** If pExpr is a column in a virtual table, then let the virtual
102803 ** table implementation have an opportunity to overload the function.
102804 **
102805 ** This routine is used to allow virtual table implementations to
102806 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
102807 **
102808 ** Return either the pDef argument (indicating no change) or a 
102809 ** new FuncDef structure that is marked as ephemeral using the
102810 ** SQLITE_FUNC_EPHEM flag.
102811 */
102812 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
102813   sqlite3 *db,    /* Database connection for reporting malloc problems */
102814   FuncDef *pDef,  /* Function to possibly overload */
102815   int nArg,       /* Number of arguments to the function */
102816   Expr *pExpr     /* First argument to the function */
102817 ){
102818   Table *pTab;
102819   sqlite3_vtab *pVtab;
102820   sqlite3_module *pMod;
102821   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
102822   void *pArg = 0;
102823   FuncDef *pNew;
102824   int rc = 0;
102825   char *zLowerName;
102826   unsigned char *z;
102827
102828
102829   /* Check to see the left operand is a column in a virtual table */
102830   if( NEVER(pExpr==0) ) return pDef;
102831   if( pExpr->op!=TK_COLUMN ) return pDef;
102832   pTab = pExpr->pTab;
102833   if( NEVER(pTab==0) ) return pDef;
102834   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
102835   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
102836   assert( pVtab!=0 );
102837   assert( pVtab->pModule!=0 );
102838   pMod = (sqlite3_module *)pVtab->pModule;
102839   if( pMod->xFindFunction==0 ) return pDef;
102840  
102841   /* Call the xFindFunction method on the virtual table implementation
102842   ** to see if the implementation wants to overload this function 
102843   */
102844   zLowerName = sqlite3DbStrDup(db, pDef->zName);
102845   if( zLowerName ){
102846     for(z=(unsigned char*)zLowerName; *z; z++){
102847       *z = sqlite3UpperToLower[*z];
102848     }
102849     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
102850     sqlite3DbFree(db, zLowerName);
102851   }
102852   if( rc==0 ){
102853     return pDef;
102854   }
102855
102856   /* Create a new ephemeral function definition for the overloaded
102857   ** function */
102858   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
102859                              + sqlite3Strlen30(pDef->zName) + 1);
102860   if( pNew==0 ){
102861     return pDef;
102862   }
102863   *pNew = *pDef;
102864   pNew->zName = (char *)&pNew[1];
102865   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
102866   pNew->xFunc = xFunc;
102867   pNew->pUserData = pArg;
102868   pNew->flags |= SQLITE_FUNC_EPHEM;
102869   return pNew;
102870 }
102871
102872 /*
102873 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
102874 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
102875 ** array if it is missing.  If pTab is already in the array, this routine
102876 ** is a no-op.
102877 */
102878 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
102879   Parse *pToplevel = sqlite3ParseToplevel(pParse);
102880   int i, n;
102881   Table **apVtabLock;
102882
102883   assert( IsVirtual(pTab) );
102884   for(i=0; i<pToplevel->nVtabLock; i++){
102885     if( pTab==pToplevel->apVtabLock[i] ) return;
102886   }
102887   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
102888   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
102889   if( apVtabLock ){
102890     pToplevel->apVtabLock = apVtabLock;
102891     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
102892   }else{
102893     pToplevel->db->mallocFailed = 1;
102894   }
102895 }
102896
102897 /*
102898 ** Return the ON CONFLICT resolution mode in effect for the virtual
102899 ** table update operation currently in progress.
102900 **
102901 ** The results of this routine are undefined unless it is called from
102902 ** within an xUpdate method.
102903 */
102904 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
102905   static const unsigned char aMap[] = { 
102906     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
102907   };
102908   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
102909   assert( OE_Ignore==4 && OE_Replace==5 );
102910   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
102911   return (int)aMap[db->vtabOnConflict-1];
102912 }
102913
102914 /*
102915 ** Call from within the xCreate() or xConnect() methods to provide 
102916 ** the SQLite core with additional information about the behavior
102917 ** of the virtual table being implemented.
102918 */
102919 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
102920   va_list ap;
102921   int rc = SQLITE_OK;
102922
102923   sqlite3_mutex_enter(db->mutex);
102924
102925   va_start(ap, op);
102926   switch( op ){
102927     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
102928       VtabCtx *p = db->pVtabCtx;
102929       if( !p ){
102930         rc = SQLITE_MISUSE_BKPT;
102931       }else{
102932         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
102933         p->pVTable->bConstraint = (u8)va_arg(ap, int);
102934       }
102935       break;
102936     }
102937     default:
102938       rc = SQLITE_MISUSE_BKPT;
102939       break;
102940   }
102941   va_end(ap);
102942
102943   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
102944   sqlite3_mutex_leave(db->mutex);
102945   return rc;
102946 }
102947
102948 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102949
102950 /************** End of vtab.c ************************************************/
102951 /************** Begin file where.c *******************************************/
102952 /*
102953 ** 2001 September 15
102954 **
102955 ** The author disclaims copyright to this source code.  In place of
102956 ** a legal notice, here is a blessing:
102957 **
102958 **    May you do good and not evil.
102959 **    May you find forgiveness for yourself and forgive others.
102960 **    May you share freely, never taking more than you give.
102961 **
102962 *************************************************************************
102963 ** This module contains C code that generates VDBE code used to process
102964 ** the WHERE clause of SQL statements.  This module is responsible for
102965 ** generating the code that loops through a table looking for applicable
102966 ** rows.  Indices are selected and used to speed the search when doing
102967 ** so is applicable.  Because this module is responsible for selecting
102968 ** indices, you might also think of this module as the "query optimizer".
102969 */
102970
102971
102972 /*
102973 ** Trace output macros
102974 */
102975 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
102976 /***/ int sqlite3WhereTrace = 0;
102977 #endif
102978 #if defined(SQLITE_DEBUG) \
102979     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
102980 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
102981 #else
102982 # define WHERETRACE(X)
102983 #endif
102984
102985 /* Forward reference
102986 */
102987 typedef struct WhereClause WhereClause;
102988 typedef struct WhereMaskSet WhereMaskSet;
102989 typedef struct WhereOrInfo WhereOrInfo;
102990 typedef struct WhereAndInfo WhereAndInfo;
102991 typedef struct WhereCost WhereCost;
102992
102993 /*
102994 ** The query generator uses an array of instances of this structure to
102995 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
102996 ** clause subexpression is separated from the others by AND operators,
102997 ** usually, or sometimes subexpressions separated by OR.
102998 **
102999 ** All WhereTerms are collected into a single WhereClause structure.  
103000 ** The following identity holds:
103001 **
103002 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
103003 **
103004 ** When a term is of the form:
103005 **
103006 **              X <op> <expr>
103007 **
103008 ** where X is a column name and <op> is one of certain operators,
103009 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
103010 ** cursor number and column number for X.  WhereTerm.eOperator records
103011 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
103012 ** use of a bitmask encoding for the operator allows us to search
103013 ** quickly for terms that match any of several different operators.
103014 **
103015 ** A WhereTerm might also be two or more subterms connected by OR:
103016 **
103017 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
103018 **
103019 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
103020 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
103021 ** is collected about the
103022 **
103023 ** If a term in the WHERE clause does not match either of the two previous
103024 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
103025 ** to the original subexpression content and wtFlags is set up appropriately
103026 ** but no other fields in the WhereTerm object are meaningful.
103027 **
103028 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
103029 ** but they do so indirectly.  A single WhereMaskSet structure translates
103030 ** cursor number into bits and the translated bit is stored in the prereq
103031 ** fields.  The translation is used in order to maximize the number of
103032 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
103033 ** spread out over the non-negative integers.  For example, the cursor
103034 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
103035 ** translates these sparse cursor numbers into consecutive integers
103036 ** beginning with 0 in order to make the best possible use of the available
103037 ** bits in the Bitmask.  So, in the example above, the cursor numbers
103038 ** would be mapped into integers 0 through 7.
103039 **
103040 ** The number of terms in a join is limited by the number of bits
103041 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
103042 ** is only able to process joins with 64 or fewer tables.
103043 */
103044 typedef struct WhereTerm WhereTerm;
103045 struct WhereTerm {
103046   Expr *pExpr;            /* Pointer to the subexpression that is this term */
103047   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
103048   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
103049   union {
103050     int leftColumn;         /* Column number of X in "X <op> <expr>" */
103051     WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
103052     WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
103053   } u;
103054   u16 eOperator;          /* A WO_xx value describing <op> */
103055   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
103056   u8 nChild;              /* Number of children that must disable us */
103057   WhereClause *pWC;       /* The clause this term is part of */
103058   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
103059   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
103060 };
103061
103062 /*
103063 ** Allowed values of WhereTerm.wtFlags
103064 */
103065 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
103066 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
103067 #define TERM_CODED      0x04   /* This term is already coded */
103068 #define TERM_COPIED     0x08   /* Has a child */
103069 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
103070 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
103071 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
103072 #ifdef SQLITE_ENABLE_STAT3
103073 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
103074 #else
103075 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
103076 #endif
103077
103078 /*
103079 ** An instance of the following structure holds all information about a
103080 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
103081 **
103082 ** Explanation of pOuter:  For a WHERE clause of the form
103083 **
103084 **           a AND ((b AND c) OR (d AND e)) AND f
103085 **
103086 ** There are separate WhereClause objects for the whole clause and for
103087 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
103088 ** subclauses points to the WhereClause object for the whole clause.
103089 */
103090 struct WhereClause {
103091   Parse *pParse;           /* The parser context */
103092   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
103093   WhereClause *pOuter;     /* Outer conjunction */
103094   u8 op;                   /* Split operator.  TK_AND or TK_OR */
103095   u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
103096   int nTerm;               /* Number of terms */
103097   int nSlot;               /* Number of entries in a[] */
103098   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
103099 #if defined(SQLITE_SMALL_STACK)
103100   WhereTerm aStatic[1];    /* Initial static space for a[] */
103101 #else
103102   WhereTerm aStatic[8];    /* Initial static space for a[] */
103103 #endif
103104 };
103105
103106 /*
103107 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
103108 ** a dynamically allocated instance of the following structure.
103109 */
103110 struct WhereOrInfo {
103111   WhereClause wc;          /* Decomposition into subterms */
103112   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
103113 };
103114
103115 /*
103116 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
103117 ** a dynamically allocated instance of the following structure.
103118 */
103119 struct WhereAndInfo {
103120   WhereClause wc;          /* The subexpression broken out */
103121 };
103122
103123 /*
103124 ** An instance of the following structure keeps track of a mapping
103125 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
103126 **
103127 ** The VDBE cursor numbers are small integers contained in 
103128 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
103129 ** clause, the cursor numbers might not begin with 0 and they might
103130 ** contain gaps in the numbering sequence.  But we want to make maximum
103131 ** use of the bits in our bitmasks.  This structure provides a mapping
103132 ** from the sparse cursor numbers into consecutive integers beginning
103133 ** with 0.
103134 **
103135 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
103136 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
103137 **
103138 ** For example, if the WHERE clause expression used these VDBE
103139 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
103140 ** would map those cursor numbers into bits 0 through 5.
103141 **
103142 ** Note that the mapping is not necessarily ordered.  In the example
103143 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
103144 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
103145 ** does not really matter.  What is important is that sparse cursor
103146 ** numbers all get mapped into bit numbers that begin with 0 and contain
103147 ** no gaps.
103148 */
103149 struct WhereMaskSet {
103150   int n;                        /* Number of assigned cursor values */
103151   int ix[BMS];                  /* Cursor assigned to each bit */
103152 };
103153
103154 /*
103155 ** A WhereCost object records a lookup strategy and the estimated
103156 ** cost of pursuing that strategy.
103157 */
103158 struct WhereCost {
103159   WherePlan plan;    /* The lookup strategy */
103160   double rCost;      /* Overall cost of pursuing this search strategy */
103161   Bitmask used;      /* Bitmask of cursors used by this plan */
103162 };
103163
103164 /*
103165 ** Bitmasks for the operators that indices are able to exploit.  An
103166 ** OR-ed combination of these values can be used when searching for
103167 ** terms in the where clause.
103168 */
103169 #define WO_IN     0x001
103170 #define WO_EQ     0x002
103171 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
103172 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
103173 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
103174 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
103175 #define WO_MATCH  0x040
103176 #define WO_ISNULL 0x080
103177 #define WO_OR     0x100       /* Two or more OR-connected terms */
103178 #define WO_AND    0x200       /* Two or more AND-connected terms */
103179 #define WO_EQUIV  0x400       /* Of the form A==B, both columns */
103180 #define WO_NOOP   0x800       /* This term does not restrict search space */
103181
103182 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
103183 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
103184
103185 /*
103186 ** Value for wsFlags returned by bestIndex() and stored in
103187 ** WhereLevel.wsFlags.  These flags determine which search
103188 ** strategies are appropriate.
103189 **
103190 ** The least significant 12 bits is reserved as a mask for WO_ values above.
103191 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
103192 ** But if the table is the right table of a left join, WhereLevel.wsFlags
103193 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
103194 ** the "op" parameter to findTerm when we are resolving equality constraints.
103195 ** ISNULL constraints will then not be used on the right table of a left
103196 ** join.  Tickets #2177 and #2189.
103197 */
103198 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
103199 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
103200 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
103201 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
103202 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
103203 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
103204 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
103205 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
103206 #define WHERE_IN_ABLE      0x080f1000  /* Able to support an IN operator */
103207 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
103208 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
103209 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
103210 #define WHERE_IDX_ONLY     0x00400000  /* Use index only - omit table */
103211 #define WHERE_ORDERED      0x00800000  /* Output will appear in correct order */
103212 #define WHERE_REVERSE      0x01000000  /* Scan in reverse order */
103213 #define WHERE_UNIQUE       0x02000000  /* Selects no more than one row */
103214 #define WHERE_ALL_UNIQUE   0x04000000  /* This and all prior have one row */
103215 #define WHERE_OB_UNIQUE    0x00004000  /* Values in ORDER BY columns are 
103216                                        ** different for every output row */
103217 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
103218 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
103219 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
103220 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
103221 #define WHERE_COVER_SCAN   0x80000000  /* Full scan of a covering index */
103222
103223 /*
103224 ** This module contains many separate subroutines that work together to
103225 ** find the best indices to use for accessing a particular table in a query.
103226 ** An instance of the following structure holds context information about the
103227 ** index search so that it can be more easily passed between the various
103228 ** routines.
103229 */
103230 typedef struct WhereBestIdx WhereBestIdx;
103231 struct WhereBestIdx {
103232   Parse *pParse;                  /* Parser context */
103233   WhereClause *pWC;               /* The WHERE clause */
103234   struct SrcList_item *pSrc;      /* The FROM clause term to search */
103235   Bitmask notReady;               /* Mask of cursors not available */
103236   Bitmask notValid;               /* Cursors not available for any purpose */
103237   ExprList *pOrderBy;             /* The ORDER BY clause */
103238   ExprList *pDistinct;            /* The select-list if query is DISTINCT */
103239   sqlite3_index_info **ppIdxInfo; /* Index information passed to xBestIndex */
103240   int i, n;                       /* Which loop is being coded; # of loops */
103241   WhereLevel *aLevel;             /* Info about outer loops */
103242   WhereCost cost;                 /* Lowest cost query plan */
103243 };
103244
103245 /*
103246 ** Return TRUE if the probe cost is less than the baseline cost
103247 */
103248 static int compareCost(const WhereCost *pProbe, const WhereCost *pBaseline){
103249   if( pProbe->rCost<pBaseline->rCost ) return 1;
103250   if( pProbe->rCost>pBaseline->rCost ) return 0;
103251   if( pProbe->plan.nOBSat>pBaseline->plan.nOBSat ) return 1;
103252   if( pProbe->plan.nRow<pBaseline->plan.nRow ) return 1;
103253   return 0;
103254 }
103255
103256 /*
103257 ** Initialize a preallocated WhereClause structure.
103258 */
103259 static void whereClauseInit(
103260   WhereClause *pWC,        /* The WhereClause to be initialized */
103261   Parse *pParse,           /* The parsing context */
103262   WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
103263   u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
103264 ){
103265   pWC->pParse = pParse;
103266   pWC->pMaskSet = pMaskSet;
103267   pWC->pOuter = 0;
103268   pWC->nTerm = 0;
103269   pWC->nSlot = ArraySize(pWC->aStatic);
103270   pWC->a = pWC->aStatic;
103271   pWC->wctrlFlags = wctrlFlags;
103272 }
103273
103274 /* Forward reference */
103275 static void whereClauseClear(WhereClause*);
103276
103277 /*
103278 ** Deallocate all memory associated with a WhereOrInfo object.
103279 */
103280 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
103281   whereClauseClear(&p->wc);
103282   sqlite3DbFree(db, p);
103283 }
103284
103285 /*
103286 ** Deallocate all memory associated with a WhereAndInfo object.
103287 */
103288 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
103289   whereClauseClear(&p->wc);
103290   sqlite3DbFree(db, p);
103291 }
103292
103293 /*
103294 ** Deallocate a WhereClause structure.  The WhereClause structure
103295 ** itself is not freed.  This routine is the inverse of whereClauseInit().
103296 */
103297 static void whereClauseClear(WhereClause *pWC){
103298   int i;
103299   WhereTerm *a;
103300   sqlite3 *db = pWC->pParse->db;
103301   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
103302     if( a->wtFlags & TERM_DYNAMIC ){
103303       sqlite3ExprDelete(db, a->pExpr);
103304     }
103305     if( a->wtFlags & TERM_ORINFO ){
103306       whereOrInfoDelete(db, a->u.pOrInfo);
103307     }else if( a->wtFlags & TERM_ANDINFO ){
103308       whereAndInfoDelete(db, a->u.pAndInfo);
103309     }
103310   }
103311   if( pWC->a!=pWC->aStatic ){
103312     sqlite3DbFree(db, pWC->a);
103313   }
103314 }
103315
103316 /*
103317 ** Add a single new WhereTerm entry to the WhereClause object pWC.
103318 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
103319 ** The index in pWC->a[] of the new WhereTerm is returned on success.
103320 ** 0 is returned if the new WhereTerm could not be added due to a memory
103321 ** allocation error.  The memory allocation failure will be recorded in
103322 ** the db->mallocFailed flag so that higher-level functions can detect it.
103323 **
103324 ** This routine will increase the size of the pWC->a[] array as necessary.
103325 **
103326 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
103327 ** for freeing the expression p is assumed by the WhereClause object pWC.
103328 ** This is true even if this routine fails to allocate a new WhereTerm.
103329 **
103330 ** WARNING:  This routine might reallocate the space used to store
103331 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
103332 ** calling this routine.  Such pointers may be reinitialized by referencing
103333 ** the pWC->a[] array.
103334 */
103335 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
103336   WhereTerm *pTerm;
103337   int idx;
103338   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
103339   if( pWC->nTerm>=pWC->nSlot ){
103340     WhereTerm *pOld = pWC->a;
103341     sqlite3 *db = pWC->pParse->db;
103342     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
103343     if( pWC->a==0 ){
103344       if( wtFlags & TERM_DYNAMIC ){
103345         sqlite3ExprDelete(db, p);
103346       }
103347       pWC->a = pOld;
103348       return 0;
103349     }
103350     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
103351     if( pOld!=pWC->aStatic ){
103352       sqlite3DbFree(db, pOld);
103353     }
103354     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
103355   }
103356   pTerm = &pWC->a[idx = pWC->nTerm++];
103357   pTerm->pExpr = sqlite3ExprSkipCollate(p);
103358   pTerm->wtFlags = wtFlags;
103359   pTerm->pWC = pWC;
103360   pTerm->iParent = -1;
103361   return idx;
103362 }
103363
103364 /*
103365 ** This routine identifies subexpressions in the WHERE clause where
103366 ** each subexpression is separated by the AND operator or some other
103367 ** operator specified in the op parameter.  The WhereClause structure
103368 ** is filled with pointers to subexpressions.  For example:
103369 **
103370 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
103371 **           \________/     \_______________/     \________________/
103372 **            slot[0]            slot[1]               slot[2]
103373 **
103374 ** The original WHERE clause in pExpr is unaltered.  All this routine
103375 ** does is make slot[] entries point to substructure within pExpr.
103376 **
103377 ** In the previous sentence and in the diagram, "slot[]" refers to
103378 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
103379 ** all terms of the WHERE clause.
103380 */
103381 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
103382   pWC->op = (u8)op;
103383   if( pExpr==0 ) return;
103384   if( pExpr->op!=op ){
103385     whereClauseInsert(pWC, pExpr, 0);
103386   }else{
103387     whereSplit(pWC, pExpr->pLeft, op);
103388     whereSplit(pWC, pExpr->pRight, op);
103389   }
103390 }
103391
103392 /*
103393 ** Initialize an expression mask set (a WhereMaskSet object)
103394 */
103395 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
103396
103397 /*
103398 ** Return the bitmask for the given cursor number.  Return 0 if
103399 ** iCursor is not in the set.
103400 */
103401 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
103402   int i;
103403   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
103404   for(i=0; i<pMaskSet->n; i++){
103405     if( pMaskSet->ix[i]==iCursor ){
103406       return ((Bitmask)1)<<i;
103407     }
103408   }
103409   return 0;
103410 }
103411
103412 /*
103413 ** Create a new mask for cursor iCursor.
103414 **
103415 ** There is one cursor per table in the FROM clause.  The number of
103416 ** tables in the FROM clause is limited by a test early in the
103417 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
103418 ** array will never overflow.
103419 */
103420 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
103421   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
103422   pMaskSet->ix[pMaskSet->n++] = iCursor;
103423 }
103424
103425 /*
103426 ** This routine walks (recursively) an expression tree and generates
103427 ** a bitmask indicating which tables are used in that expression
103428 ** tree.
103429 **
103430 ** In order for this routine to work, the calling function must have
103431 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
103432 ** the header comment on that routine for additional information.
103433 ** The sqlite3ResolveExprNames() routines looks for column names and
103434 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
103435 ** the VDBE cursor number of the table.  This routine just has to
103436 ** translate the cursor numbers into bitmask values and OR all
103437 ** the bitmasks together.
103438 */
103439 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
103440 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
103441 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
103442   Bitmask mask = 0;
103443   if( p==0 ) return 0;
103444   if( p->op==TK_COLUMN ){
103445     mask = getMask(pMaskSet, p->iTable);
103446     return mask;
103447   }
103448   mask = exprTableUsage(pMaskSet, p->pRight);
103449   mask |= exprTableUsage(pMaskSet, p->pLeft);
103450   if( ExprHasProperty(p, EP_xIsSelect) ){
103451     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
103452   }else{
103453     mask |= exprListTableUsage(pMaskSet, p->x.pList);
103454   }
103455   return mask;
103456 }
103457 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
103458   int i;
103459   Bitmask mask = 0;
103460   if( pList ){
103461     for(i=0; i<pList->nExpr; i++){
103462       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
103463     }
103464   }
103465   return mask;
103466 }
103467 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
103468   Bitmask mask = 0;
103469   while( pS ){
103470     SrcList *pSrc = pS->pSrc;
103471     mask |= exprListTableUsage(pMaskSet, pS->pEList);
103472     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
103473     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
103474     mask |= exprTableUsage(pMaskSet, pS->pWhere);
103475     mask |= exprTableUsage(pMaskSet, pS->pHaving);
103476     if( ALWAYS(pSrc!=0) ){
103477       int i;
103478       for(i=0; i<pSrc->nSrc; i++){
103479         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
103480         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
103481       }
103482     }
103483     pS = pS->pPrior;
103484   }
103485   return mask;
103486 }
103487
103488 /*
103489 ** Return TRUE if the given operator is one of the operators that is
103490 ** allowed for an indexable WHERE clause term.  The allowed operators are
103491 ** "=", "<", ">", "<=", ">=", and "IN".
103492 **
103493 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
103494 ** of one of the following forms: column = expression column > expression
103495 ** column >= expression column < expression column <= expression
103496 ** expression = column expression > column expression >= column
103497 ** expression < column expression <= column column IN
103498 ** (expression-list) column IN (subquery) column IS NULL
103499 */
103500 static int allowedOp(int op){
103501   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
103502   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
103503   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
103504   assert( TK_GE==TK_EQ+4 );
103505   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
103506 }
103507
103508 /*
103509 ** Swap two objects of type TYPE.
103510 */
103511 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
103512
103513 /*
103514 ** Commute a comparison operator.  Expressions of the form "X op Y"
103515 ** are converted into "Y op X".
103516 **
103517 ** If left/right precedence rules come into play when determining the
103518 ** collating
103519 ** side of the comparison, it remains associated with the same side after
103520 ** the commutation. So "Y collate NOCASE op X" becomes 
103521 ** "X op Y". This is because any collation sequence on
103522 ** the left hand side of a comparison overrides any collation sequence 
103523 ** attached to the right. For the same reason the EP_Collate flag
103524 ** is not commuted.
103525 */
103526 static void exprCommute(Parse *pParse, Expr *pExpr){
103527   u16 expRight = (pExpr->pRight->flags & EP_Collate);
103528   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
103529   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
103530   if( expRight==expLeft ){
103531     /* Either X and Y both have COLLATE operator or neither do */
103532     if( expRight ){
103533       /* Both X and Y have COLLATE operators.  Make sure X is always
103534       ** used by clearing the EP_Collate flag from Y. */
103535       pExpr->pRight->flags &= ~EP_Collate;
103536     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
103537       /* Neither X nor Y have COLLATE operators, but X has a non-default
103538       ** collating sequence.  So add the EP_Collate marker on X to cause
103539       ** it to be searched first. */
103540       pExpr->pLeft->flags |= EP_Collate;
103541     }
103542   }
103543   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
103544   if( pExpr->op>=TK_GT ){
103545     assert( TK_LT==TK_GT+2 );
103546     assert( TK_GE==TK_LE+2 );
103547     assert( TK_GT>TK_EQ );
103548     assert( TK_GT<TK_LE );
103549     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
103550     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
103551   }
103552 }
103553
103554 /*
103555 ** Translate from TK_xx operator to WO_xx bitmask.
103556 */
103557 static u16 operatorMask(int op){
103558   u16 c;
103559   assert( allowedOp(op) );
103560   if( op==TK_IN ){
103561     c = WO_IN;
103562   }else if( op==TK_ISNULL ){
103563     c = WO_ISNULL;
103564   }else{
103565     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
103566     c = (u16)(WO_EQ<<(op-TK_EQ));
103567   }
103568   assert( op!=TK_ISNULL || c==WO_ISNULL );
103569   assert( op!=TK_IN || c==WO_IN );
103570   assert( op!=TK_EQ || c==WO_EQ );
103571   assert( op!=TK_LT || c==WO_LT );
103572   assert( op!=TK_LE || c==WO_LE );
103573   assert( op!=TK_GT || c==WO_GT );
103574   assert( op!=TK_GE || c==WO_GE );
103575   return c;
103576 }
103577
103578 /*
103579 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
103580 ** where X is a reference to the iColumn of table iCur and <op> is one of
103581 ** the WO_xx operator codes specified by the op parameter.
103582 ** Return a pointer to the term.  Return 0 if not found.
103583 **
103584 ** The term returned might by Y=<expr> if there is another constraint in
103585 ** the WHERE clause that specifies that X=Y.  Any such constraints will be
103586 ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
103587 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
103588 ** taking up two slots in aEquiv[].  The first slot is for the cursor number
103589 ** and the second is for the column number.  There are 22 slots in aEquiv[]
103590 ** so that means we can look for X plus up to 10 other equivalent values.
103591 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
103592 ** and ... and A9=A10 and A10=<expr>.
103593 **
103594 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
103595 ** then try for the one with no dependencies on <expr> - in other words where
103596 ** <expr> is a constant expression of some kind.  Only return entries of
103597 ** the form "X <op> Y" where Y is a column in another table if no terms of
103598 ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
103599 ** exist, try to return a term that does not use WO_EQUIV.
103600 */
103601 static WhereTerm *findTerm(
103602   WhereClause *pWC,     /* The WHERE clause to be searched */
103603   int iCur,             /* Cursor number of LHS */
103604   int iColumn,          /* Column number of LHS */
103605   Bitmask notReady,     /* RHS must not overlap with this mask */
103606   u32 op,               /* Mask of WO_xx values describing operator */
103607   Index *pIdx           /* Must be compatible with this index, if not NULL */
103608 ){
103609   WhereTerm *pTerm;            /* Term being examined as possible result */
103610   WhereTerm *pResult = 0;      /* The answer to return */
103611   WhereClause *pWCOrig = pWC;  /* Original pWC value */
103612   int j, k;                    /* Loop counters */
103613   Expr *pX;                /* Pointer to an expression */
103614   Parse *pParse;           /* Parsing context */
103615   int iOrigCol = iColumn;  /* Original value of iColumn */
103616   int nEquiv = 2;          /* Number of entires in aEquiv[] */
103617   int iEquiv = 2;          /* Number of entries of aEquiv[] processed so far */
103618   int aEquiv[22];          /* iCur,iColumn and up to 10 other equivalents */
103619
103620   assert( iCur>=0 );
103621   aEquiv[0] = iCur;
103622   aEquiv[1] = iColumn;
103623   for(;;){
103624     for(pWC=pWCOrig; pWC; pWC=pWC->pOuter){
103625       for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
103626         if( pTerm->leftCursor==iCur
103627           && pTerm->u.leftColumn==iColumn
103628         ){
103629           if( (pTerm->prereqRight & notReady)==0
103630            && (pTerm->eOperator & op & WO_ALL)!=0
103631           ){
103632             if( iOrigCol>=0 && pIdx && (pTerm->eOperator & WO_ISNULL)==0 ){
103633               CollSeq *pColl;
103634               char idxaff;
103635       
103636               pX = pTerm->pExpr;
103637               pParse = pWC->pParse;
103638               idxaff = pIdx->pTable->aCol[iOrigCol].affinity;
103639               if( !sqlite3IndexAffinityOk(pX, idxaff) ){
103640                 continue;
103641               }
103642       
103643               /* Figure out the collation sequence required from an index for
103644               ** it to be useful for optimising expression pX. Store this
103645               ** value in variable pColl.
103646               */
103647               assert(pX->pLeft);
103648               pColl = sqlite3BinaryCompareCollSeq(pParse,pX->pLeft,pX->pRight);
103649               if( pColl==0 ) pColl = pParse->db->pDfltColl;
103650       
103651               for(j=0; pIdx->aiColumn[j]!=iOrigCol; j++){
103652                 if( NEVER(j>=pIdx->nColumn) ) return 0;
103653               }
103654               if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ){
103655                 continue;
103656               }
103657             }
103658             if( pTerm->prereqRight==0 ){
103659               pResult = pTerm;
103660               goto findTerm_success;
103661             }else if( pResult==0 ){
103662               pResult = pTerm;
103663             }
103664           }
103665           if( (pTerm->eOperator & WO_EQUIV)!=0
103666            && nEquiv<ArraySize(aEquiv)
103667           ){
103668             pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
103669             assert( pX->op==TK_COLUMN );
103670             for(j=0; j<nEquiv; j+=2){
103671               if( aEquiv[j]==pX->iTable && aEquiv[j+1]==pX->iColumn ) break;
103672             }
103673             if( j==nEquiv ){
103674               aEquiv[j] = pX->iTable;
103675               aEquiv[j+1] = pX->iColumn;
103676               nEquiv += 2;
103677             }
103678           }
103679         }
103680       }
103681     }
103682     if( iEquiv>=nEquiv ) break;
103683     iCur = aEquiv[iEquiv++];
103684     iColumn = aEquiv[iEquiv++];
103685   }
103686 findTerm_success:
103687   return pResult;
103688 }
103689
103690 /* Forward reference */
103691 static void exprAnalyze(SrcList*, WhereClause*, int);
103692
103693 /*
103694 ** Call exprAnalyze on all terms in a WHERE clause.  
103695 **
103696 **
103697 */
103698 static void exprAnalyzeAll(
103699   SrcList *pTabList,       /* the FROM clause */
103700   WhereClause *pWC         /* the WHERE clause to be analyzed */
103701 ){
103702   int i;
103703   for(i=pWC->nTerm-1; i>=0; i--){
103704     exprAnalyze(pTabList, pWC, i);
103705   }
103706 }
103707
103708 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
103709 /*
103710 ** Check to see if the given expression is a LIKE or GLOB operator that
103711 ** can be optimized using inequality constraints.  Return TRUE if it is
103712 ** so and false if not.
103713 **
103714 ** In order for the operator to be optimizible, the RHS must be a string
103715 ** literal that does not begin with a wildcard.  
103716 */
103717 static int isLikeOrGlob(
103718   Parse *pParse,    /* Parsing and code generating context */
103719   Expr *pExpr,      /* Test this expression */
103720   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
103721   int *pisComplete, /* True if the only wildcard is % in the last character */
103722   int *pnoCase      /* True if uppercase is equivalent to lowercase */
103723 ){
103724   const char *z = 0;         /* String on RHS of LIKE operator */
103725   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
103726   ExprList *pList;           /* List of operands to the LIKE operator */
103727   int c;                     /* One character in z[] */
103728   int cnt;                   /* Number of non-wildcard prefix characters */
103729   char wc[3];                /* Wildcard characters */
103730   sqlite3 *db = pParse->db;  /* Database connection */
103731   sqlite3_value *pVal = 0;
103732   int op;                    /* Opcode of pRight */
103733
103734   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
103735     return 0;
103736   }
103737 #ifdef SQLITE_EBCDIC
103738   if( *pnoCase ) return 0;
103739 #endif
103740   pList = pExpr->x.pList;
103741   pLeft = pList->a[1].pExpr;
103742   if( pLeft->op!=TK_COLUMN 
103743    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 
103744    || IsVirtual(pLeft->pTab)
103745   ){
103746     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
103747     ** be the name of an indexed column with TEXT affinity. */
103748     return 0;
103749   }
103750   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
103751
103752   pRight = pList->a[0].pExpr;
103753   op = pRight->op;
103754   if( op==TK_REGISTER ){
103755     op = pRight->op2;
103756   }
103757   if( op==TK_VARIABLE ){
103758     Vdbe *pReprepare = pParse->pReprepare;
103759     int iCol = pRight->iColumn;
103760     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
103761     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
103762       z = (char *)sqlite3_value_text(pVal);
103763     }
103764     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
103765     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
103766   }else if( op==TK_STRING ){
103767     z = pRight->u.zToken;
103768   }
103769   if( z ){
103770     cnt = 0;
103771     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
103772       cnt++;
103773     }
103774     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
103775       Expr *pPrefix;
103776       *pisComplete = c==wc[0] && z[cnt+1]==0;
103777       pPrefix = sqlite3Expr(db, TK_STRING, z);
103778       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
103779       *ppPrefix = pPrefix;
103780       if( op==TK_VARIABLE ){
103781         Vdbe *v = pParse->pVdbe;
103782         sqlite3VdbeSetVarmask(v, pRight->iColumn);
103783         if( *pisComplete && pRight->u.zToken[1] ){
103784           /* If the rhs of the LIKE expression is a variable, and the current
103785           ** value of the variable means there is no need to invoke the LIKE
103786           ** function, then no OP_Variable will be added to the program.
103787           ** This causes problems for the sqlite3_bind_parameter_name()
103788           ** API. To workaround them, add a dummy OP_Variable here.
103789           */ 
103790           int r1 = sqlite3GetTempReg(pParse);
103791           sqlite3ExprCodeTarget(pParse, pRight, r1);
103792           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
103793           sqlite3ReleaseTempReg(pParse, r1);
103794         }
103795       }
103796     }else{
103797       z = 0;
103798     }
103799   }
103800
103801   sqlite3ValueFree(pVal);
103802   return (z!=0);
103803 }
103804 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
103805
103806
103807 #ifndef SQLITE_OMIT_VIRTUALTABLE
103808 /*
103809 ** Check to see if the given expression is of the form
103810 **
103811 **         column MATCH expr
103812 **
103813 ** If it is then return TRUE.  If not, return FALSE.
103814 */
103815 static int isMatchOfColumn(
103816   Expr *pExpr      /* Test this expression */
103817 ){
103818   ExprList *pList;
103819
103820   if( pExpr->op!=TK_FUNCTION ){
103821     return 0;
103822   }
103823   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
103824     return 0;
103825   }
103826   pList = pExpr->x.pList;
103827   if( pList->nExpr!=2 ){
103828     return 0;
103829   }
103830   if( pList->a[1].pExpr->op != TK_COLUMN ){
103831     return 0;
103832   }
103833   return 1;
103834 }
103835 #endif /* SQLITE_OMIT_VIRTUALTABLE */
103836
103837 /*
103838 ** If the pBase expression originated in the ON or USING clause of
103839 ** a join, then transfer the appropriate markings over to derived.
103840 */
103841 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
103842   pDerived->flags |= pBase->flags & EP_FromJoin;
103843   pDerived->iRightJoinTable = pBase->iRightJoinTable;
103844 }
103845
103846 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
103847 /*
103848 ** Analyze a term that consists of two or more OR-connected
103849 ** subterms.  So in:
103850 **
103851 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
103852 **                          ^^^^^^^^^^^^^^^^^^^^
103853 **
103854 ** This routine analyzes terms such as the middle term in the above example.
103855 ** A WhereOrTerm object is computed and attached to the term under
103856 ** analysis, regardless of the outcome of the analysis.  Hence:
103857 **
103858 **     WhereTerm.wtFlags   |=  TERM_ORINFO
103859 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
103860 **
103861 ** The term being analyzed must have two or more of OR-connected subterms.
103862 ** A single subterm might be a set of AND-connected sub-subterms.
103863 ** Examples of terms under analysis:
103864 **
103865 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
103866 **     (B)     x=expr1 OR expr2=x OR x=expr3
103867 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
103868 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
103869 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
103870 **
103871 ** CASE 1:
103872 **
103873 ** If all subterms are of the form T.C=expr for some single column of C and
103874 ** a single table T (as shown in example B above) then create a new virtual
103875 ** term that is an equivalent IN expression.  In other words, if the term
103876 ** being analyzed is:
103877 **
103878 **      x = expr1  OR  expr2 = x  OR  x = expr3
103879 **
103880 ** then create a new virtual term like this:
103881 **
103882 **      x IN (expr1,expr2,expr3)
103883 **
103884 ** CASE 2:
103885 **
103886 ** If all subterms are indexable by a single table T, then set
103887 **
103888 **     WhereTerm.eOperator              =  WO_OR
103889 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
103890 **
103891 ** A subterm is "indexable" if it is of the form
103892 ** "T.C <op> <expr>" where C is any column of table T and 
103893 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
103894 ** A subterm is also indexable if it is an AND of two or more
103895 ** subsubterms at least one of which is indexable.  Indexable AND 
103896 ** subterms have their eOperator set to WO_AND and they have
103897 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
103898 **
103899 ** From another point of view, "indexable" means that the subterm could
103900 ** potentially be used with an index if an appropriate index exists.
103901 ** This analysis does not consider whether or not the index exists; that
103902 ** is something the bestIndex() routine will determine.  This analysis
103903 ** only looks at whether subterms appropriate for indexing exist.
103904 **
103905 ** All examples A through E above all satisfy case 2.  But if a term
103906 ** also statisfies case 1 (such as B) we know that the optimizer will
103907 ** always prefer case 1, so in that case we pretend that case 2 is not
103908 ** satisfied.
103909 **
103910 ** It might be the case that multiple tables are indexable.  For example,
103911 ** (E) above is indexable on tables P, Q, and R.
103912 **
103913 ** Terms that satisfy case 2 are candidates for lookup by using
103914 ** separate indices to find rowids for each subterm and composing
103915 ** the union of all rowids using a RowSet object.  This is similar
103916 ** to "bitmap indices" in other database engines.
103917 **
103918 ** OTHERWISE:
103919 **
103920 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
103921 ** zero.  This term is not useful for search.
103922 */
103923 static void exprAnalyzeOrTerm(
103924   SrcList *pSrc,            /* the FROM clause */
103925   WhereClause *pWC,         /* the complete WHERE clause */
103926   int idxTerm               /* Index of the OR-term to be analyzed */
103927 ){
103928   Parse *pParse = pWC->pParse;            /* Parser context */
103929   sqlite3 *db = pParse->db;               /* Database connection */
103930   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
103931   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
103932   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
103933   int i;                                  /* Loop counters */
103934   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
103935   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
103936   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
103937   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
103938   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
103939
103940   /*
103941   ** Break the OR clause into its separate subterms.  The subterms are
103942   ** stored in a WhereClause structure containing within the WhereOrInfo
103943   ** object that is attached to the original OR clause term.
103944   */
103945   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
103946   assert( pExpr->op==TK_OR );
103947   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
103948   if( pOrInfo==0 ) return;
103949   pTerm->wtFlags |= TERM_ORINFO;
103950   pOrWc = &pOrInfo->wc;
103951   whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103952   whereSplit(pOrWc, pExpr, TK_OR);
103953   exprAnalyzeAll(pSrc, pOrWc);
103954   if( db->mallocFailed ) return;
103955   assert( pOrWc->nTerm>=2 );
103956
103957   /*
103958   ** Compute the set of tables that might satisfy cases 1 or 2.
103959   */
103960   indexable = ~(Bitmask)0;
103961   chngToIN = ~(Bitmask)0;
103962   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
103963     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
103964       WhereAndInfo *pAndInfo;
103965       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
103966       chngToIN = 0;
103967       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
103968       if( pAndInfo ){
103969         WhereClause *pAndWC;
103970         WhereTerm *pAndTerm;
103971         int j;
103972         Bitmask b = 0;
103973         pOrTerm->u.pAndInfo = pAndInfo;
103974         pOrTerm->wtFlags |= TERM_ANDINFO;
103975         pOrTerm->eOperator = WO_AND;
103976         pAndWC = &pAndInfo->wc;
103977         whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103978         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
103979         exprAnalyzeAll(pSrc, pAndWC);
103980         pAndWC->pOuter = pWC;
103981         testcase( db->mallocFailed );
103982         if( !db->mallocFailed ){
103983           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
103984             assert( pAndTerm->pExpr );
103985             if( allowedOp(pAndTerm->pExpr->op) ){
103986               b |= getMask(pMaskSet, pAndTerm->leftCursor);
103987             }
103988           }
103989         }
103990         indexable &= b;
103991       }
103992     }else if( pOrTerm->wtFlags & TERM_COPIED ){
103993       /* Skip this term for now.  We revisit it when we process the
103994       ** corresponding TERM_VIRTUAL term */
103995     }else{
103996       Bitmask b;
103997       b = getMask(pMaskSet, pOrTerm->leftCursor);
103998       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
103999         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
104000         b |= getMask(pMaskSet, pOther->leftCursor);
104001       }
104002       indexable &= b;
104003       if( (pOrTerm->eOperator & WO_EQ)==0 ){
104004         chngToIN = 0;
104005       }else{
104006         chngToIN &= b;
104007       }
104008     }
104009   }
104010
104011   /*
104012   ** Record the set of tables that satisfy case 2.  The set might be
104013   ** empty.
104014   */
104015   pOrInfo->indexable = indexable;
104016   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
104017
104018   /*
104019   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
104020   ** we have to do some additional checking to see if case 1 really
104021   ** is satisfied.
104022   **
104023   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
104024   ** that there is no possibility of transforming the OR clause into an
104025   ** IN operator because one or more terms in the OR clause contain
104026   ** something other than == on a column in the single table.  The 1-bit
104027   ** case means that every term of the OR clause is of the form
104028   ** "table.column=expr" for some single table.  The one bit that is set
104029   ** will correspond to the common table.  We still need to check to make
104030   ** sure the same column is used on all terms.  The 2-bit case is when
104031   ** the all terms are of the form "table1.column=table2.column".  It
104032   ** might be possible to form an IN operator with either table1.column
104033   ** or table2.column as the LHS if either is common to every term of
104034   ** the OR clause.
104035   **
104036   ** Note that terms of the form "table.column1=table.column2" (the
104037   ** same table on both sizes of the ==) cannot be optimized.
104038   */
104039   if( chngToIN ){
104040     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
104041     int iColumn = -1;         /* Column index on lhs of IN operator */
104042     int iCursor = -1;         /* Table cursor common to all terms */
104043     int j = 0;                /* Loop counter */
104044
104045     /* Search for a table and column that appears on one side or the
104046     ** other of the == operator in every subterm.  That table and column
104047     ** will be recorded in iCursor and iColumn.  There might not be any
104048     ** such table and column.  Set okToChngToIN if an appropriate table
104049     ** and column is found but leave okToChngToIN false if not found.
104050     */
104051     for(j=0; j<2 && !okToChngToIN; j++){
104052       pOrTerm = pOrWc->a;
104053       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
104054         assert( pOrTerm->eOperator & WO_EQ );
104055         pOrTerm->wtFlags &= ~TERM_OR_OK;
104056         if( pOrTerm->leftCursor==iCursor ){
104057           /* This is the 2-bit case and we are on the second iteration and
104058           ** current term is from the first iteration.  So skip this term. */
104059           assert( j==1 );
104060           continue;
104061         }
104062         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
104063           /* This term must be of the form t1.a==t2.b where t2 is in the
104064           ** chngToIN set but t1 is not.  This term will be either preceeded
104065           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
104066           ** and use its inversion. */
104067           testcase( pOrTerm->wtFlags & TERM_COPIED );
104068           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
104069           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
104070           continue;
104071         }
104072         iColumn = pOrTerm->u.leftColumn;
104073         iCursor = pOrTerm->leftCursor;
104074         break;
104075       }
104076       if( i<0 ){
104077         /* No candidate table+column was found.  This can only occur
104078         ** on the second iteration */
104079         assert( j==1 );
104080         assert( IsPowerOfTwo(chngToIN) );
104081         assert( chngToIN==getMask(pMaskSet, iCursor) );
104082         break;
104083       }
104084       testcase( j==1 );
104085
104086       /* We have found a candidate table and column.  Check to see if that
104087       ** table and column is common to every term in the OR clause */
104088       okToChngToIN = 1;
104089       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
104090         assert( pOrTerm->eOperator & WO_EQ );
104091         if( pOrTerm->leftCursor!=iCursor ){
104092           pOrTerm->wtFlags &= ~TERM_OR_OK;
104093         }else if( pOrTerm->u.leftColumn!=iColumn ){
104094           okToChngToIN = 0;
104095         }else{
104096           int affLeft, affRight;
104097           /* If the right-hand side is also a column, then the affinities
104098           ** of both right and left sides must be such that no type
104099           ** conversions are required on the right.  (Ticket #2249)
104100           */
104101           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
104102           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
104103           if( affRight!=0 && affRight!=affLeft ){
104104             okToChngToIN = 0;
104105           }else{
104106             pOrTerm->wtFlags |= TERM_OR_OK;
104107           }
104108         }
104109       }
104110     }
104111
104112     /* At this point, okToChngToIN is true if original pTerm satisfies
104113     ** case 1.  In that case, construct a new virtual term that is 
104114     ** pTerm converted into an IN operator.
104115     **
104116     ** EV: R-00211-15100
104117     */
104118     if( okToChngToIN ){
104119       Expr *pDup;            /* A transient duplicate expression */
104120       ExprList *pList = 0;   /* The RHS of the IN operator */
104121       Expr *pLeft = 0;       /* The LHS of the IN operator */
104122       Expr *pNew;            /* The complete IN operator */
104123
104124       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
104125         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
104126         assert( pOrTerm->eOperator & WO_EQ );
104127         assert( pOrTerm->leftCursor==iCursor );
104128         assert( pOrTerm->u.leftColumn==iColumn );
104129         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
104130         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
104131         pLeft = pOrTerm->pExpr->pLeft;
104132       }
104133       assert( pLeft!=0 );
104134       pDup = sqlite3ExprDup(db, pLeft, 0);
104135       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
104136       if( pNew ){
104137         int idxNew;
104138         transferJoinMarkings(pNew, pExpr);
104139         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
104140         pNew->x.pList = pList;
104141         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
104142         testcase( idxNew==0 );
104143         exprAnalyze(pSrc, pWC, idxNew);
104144         pTerm = &pWC->a[idxTerm];
104145         pWC->a[idxNew].iParent = idxTerm;
104146         pTerm->nChild = 1;
104147       }else{
104148         sqlite3ExprListDelete(db, pList);
104149       }
104150       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
104151     }
104152   }
104153 }
104154 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
104155
104156 /*
104157 ** The input to this routine is an WhereTerm structure with only the
104158 ** "pExpr" field filled in.  The job of this routine is to analyze the
104159 ** subexpression and populate all the other fields of the WhereTerm
104160 ** structure.
104161 **
104162 ** If the expression is of the form "<expr> <op> X" it gets commuted
104163 ** to the standard form of "X <op> <expr>".
104164 **
104165 ** If the expression is of the form "X <op> Y" where both X and Y are
104166 ** columns, then the original expression is unchanged and a new virtual
104167 ** term of the form "Y <op> X" is added to the WHERE clause and
104168 ** analyzed separately.  The original term is marked with TERM_COPIED
104169 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
104170 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
104171 ** is a commuted copy of a prior term.)  The original term has nChild=1
104172 ** and the copy has idxParent set to the index of the original term.
104173 */
104174 static void exprAnalyze(
104175   SrcList *pSrc,            /* the FROM clause */
104176   WhereClause *pWC,         /* the WHERE clause */
104177   int idxTerm               /* Index of the term to be analyzed */
104178 ){
104179   WhereTerm *pTerm;                /* The term to be analyzed */
104180   WhereMaskSet *pMaskSet;          /* Set of table index masks */
104181   Expr *pExpr;                     /* The expression to be analyzed */
104182   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
104183   Bitmask prereqAll;               /* Prerequesites of pExpr */
104184   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
104185   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
104186   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
104187   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
104188   int op;                          /* Top-level operator.  pExpr->op */
104189   Parse *pParse = pWC->pParse;     /* Parsing context */
104190   sqlite3 *db = pParse->db;        /* Database connection */
104191
104192   if( db->mallocFailed ){
104193     return;
104194   }
104195   pTerm = &pWC->a[idxTerm];
104196   pMaskSet = pWC->pMaskSet;
104197   pExpr = pTerm->pExpr;
104198   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
104199   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
104200   op = pExpr->op;
104201   if( op==TK_IN ){
104202     assert( pExpr->pRight==0 );
104203     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
104204       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
104205     }else{
104206       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
104207     }
104208   }else if( op==TK_ISNULL ){
104209     pTerm->prereqRight = 0;
104210   }else{
104211     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
104212   }
104213   prereqAll = exprTableUsage(pMaskSet, pExpr);
104214   if( ExprHasProperty(pExpr, EP_FromJoin) ){
104215     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
104216     prereqAll |= x;
104217     extraRight = x-1;  /* ON clause terms may not be used with an index
104218                        ** on left table of a LEFT JOIN.  Ticket #3015 */
104219   }
104220   pTerm->prereqAll = prereqAll;
104221   pTerm->leftCursor = -1;
104222   pTerm->iParent = -1;
104223   pTerm->eOperator = 0;
104224   if( allowedOp(op) ){
104225     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
104226     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
104227     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
104228     if( pLeft->op==TK_COLUMN ){
104229       pTerm->leftCursor = pLeft->iTable;
104230       pTerm->u.leftColumn = pLeft->iColumn;
104231       pTerm->eOperator = operatorMask(op) & opMask;
104232     }
104233     if( pRight && pRight->op==TK_COLUMN ){
104234       WhereTerm *pNew;
104235       Expr *pDup;
104236       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
104237       if( pTerm->leftCursor>=0 ){
104238         int idxNew;
104239         pDup = sqlite3ExprDup(db, pExpr, 0);
104240         if( db->mallocFailed ){
104241           sqlite3ExprDelete(db, pDup);
104242           return;
104243         }
104244         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
104245         if( idxNew==0 ) return;
104246         pNew = &pWC->a[idxNew];
104247         pNew->iParent = idxTerm;
104248         pTerm = &pWC->a[idxTerm];
104249         pTerm->nChild = 1;
104250         pTerm->wtFlags |= TERM_COPIED;
104251         if( pExpr->op==TK_EQ
104252          && !ExprHasProperty(pExpr, EP_FromJoin)
104253          && OptimizationEnabled(db, SQLITE_Transitive)
104254         ){
104255           pTerm->eOperator |= WO_EQUIV;
104256           eExtraOp = WO_EQUIV;
104257         }
104258       }else{
104259         pDup = pExpr;
104260         pNew = pTerm;
104261       }
104262       exprCommute(pParse, pDup);
104263       pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
104264       pNew->leftCursor = pLeft->iTable;
104265       pNew->u.leftColumn = pLeft->iColumn;
104266       testcase( (prereqLeft | extraRight) != prereqLeft );
104267       pNew->prereqRight = prereqLeft | extraRight;
104268       pNew->prereqAll = prereqAll;
104269       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
104270     }
104271   }
104272
104273 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
104274   /* If a term is the BETWEEN operator, create two new virtual terms
104275   ** that define the range that the BETWEEN implements.  For example:
104276   **
104277   **      a BETWEEN b AND c
104278   **
104279   ** is converted into:
104280   **
104281   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
104282   **
104283   ** The two new terms are added onto the end of the WhereClause object.
104284   ** The new terms are "dynamic" and are children of the original BETWEEN
104285   ** term.  That means that if the BETWEEN term is coded, the children are
104286   ** skipped.  Or, if the children are satisfied by an index, the original
104287   ** BETWEEN term is skipped.
104288   */
104289   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
104290     ExprList *pList = pExpr->x.pList;
104291     int i;
104292     static const u8 ops[] = {TK_GE, TK_LE};
104293     assert( pList!=0 );
104294     assert( pList->nExpr==2 );
104295     for(i=0; i<2; i++){
104296       Expr *pNewExpr;
104297       int idxNew;
104298       pNewExpr = sqlite3PExpr(pParse, ops[i], 
104299                              sqlite3ExprDup(db, pExpr->pLeft, 0),
104300                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
104301       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
104302       testcase( idxNew==0 );
104303       exprAnalyze(pSrc, pWC, idxNew);
104304       pTerm = &pWC->a[idxTerm];
104305       pWC->a[idxNew].iParent = idxTerm;
104306     }
104307     pTerm->nChild = 2;
104308   }
104309 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
104310
104311 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
104312   /* Analyze a term that is composed of two or more subterms connected by
104313   ** an OR operator.
104314   */
104315   else if( pExpr->op==TK_OR ){
104316     assert( pWC->op==TK_AND );
104317     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
104318     pTerm = &pWC->a[idxTerm];
104319   }
104320 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
104321
104322 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
104323   /* Add constraints to reduce the search space on a LIKE or GLOB
104324   ** operator.
104325   **
104326   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
104327   **
104328   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
104329   **
104330   ** The last character of the prefix "abc" is incremented to form the
104331   ** termination condition "abd".
104332   */
104333   if( pWC->op==TK_AND 
104334    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
104335   ){
104336     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
104337     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
104338     Expr *pNewExpr1;
104339     Expr *pNewExpr2;
104340     int idxNew1;
104341     int idxNew2;
104342     Token sCollSeqName;  /* Name of collating sequence */
104343
104344     pLeft = pExpr->x.pList->a[1].pExpr;
104345     pStr2 = sqlite3ExprDup(db, pStr1, 0);
104346     if( !db->mallocFailed ){
104347       u8 c, *pC;       /* Last character before the first wildcard */
104348       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
104349       c = *pC;
104350       if( noCase ){
104351         /* The point is to increment the last character before the first
104352         ** wildcard.  But if we increment '@', that will push it into the
104353         ** alphabetic range where case conversions will mess up the 
104354         ** inequality.  To avoid this, make sure to also run the full
104355         ** LIKE on all candidate expressions by clearing the isComplete flag
104356         */
104357         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
104358
104359
104360         c = sqlite3UpperToLower[c];
104361       }
104362       *pC = c + 1;
104363     }
104364     sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
104365     sCollSeqName.n = 6;
104366     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
104367     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
104368            sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
104369            pStr1, 0);
104370     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
104371     testcase( idxNew1==0 );
104372     exprAnalyze(pSrc, pWC, idxNew1);
104373     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
104374     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
104375            sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
104376            pStr2, 0);
104377     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
104378     testcase( idxNew2==0 );
104379     exprAnalyze(pSrc, pWC, idxNew2);
104380     pTerm = &pWC->a[idxTerm];
104381     if( isComplete ){
104382       pWC->a[idxNew1].iParent = idxTerm;
104383       pWC->a[idxNew2].iParent = idxTerm;
104384       pTerm->nChild = 2;
104385     }
104386   }
104387 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
104388
104389 #ifndef SQLITE_OMIT_VIRTUALTABLE
104390   /* Add a WO_MATCH auxiliary term to the constraint set if the
104391   ** current expression is of the form:  column MATCH expr.
104392   ** This information is used by the xBestIndex methods of
104393   ** virtual tables.  The native query optimizer does not attempt
104394   ** to do anything with MATCH functions.
104395   */
104396   if( isMatchOfColumn(pExpr) ){
104397     int idxNew;
104398     Expr *pRight, *pLeft;
104399     WhereTerm *pNewTerm;
104400     Bitmask prereqColumn, prereqExpr;
104401
104402     pRight = pExpr->x.pList->a[0].pExpr;
104403     pLeft = pExpr->x.pList->a[1].pExpr;
104404     prereqExpr = exprTableUsage(pMaskSet, pRight);
104405     prereqColumn = exprTableUsage(pMaskSet, pLeft);
104406     if( (prereqExpr & prereqColumn)==0 ){
104407       Expr *pNewExpr;
104408       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
104409                               0, sqlite3ExprDup(db, pRight, 0), 0);
104410       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
104411       testcase( idxNew==0 );
104412       pNewTerm = &pWC->a[idxNew];
104413       pNewTerm->prereqRight = prereqExpr;
104414       pNewTerm->leftCursor = pLeft->iTable;
104415       pNewTerm->u.leftColumn = pLeft->iColumn;
104416       pNewTerm->eOperator = WO_MATCH;
104417       pNewTerm->iParent = idxTerm;
104418       pTerm = &pWC->a[idxTerm];
104419       pTerm->nChild = 1;
104420       pTerm->wtFlags |= TERM_COPIED;
104421       pNewTerm->prereqAll = pTerm->prereqAll;
104422     }
104423   }
104424 #endif /* SQLITE_OMIT_VIRTUALTABLE */
104425
104426 #ifdef SQLITE_ENABLE_STAT3
104427   /* When sqlite_stat3 histogram data is available an operator of the
104428   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
104429   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
104430   ** virtual term of that form.
104431   **
104432   ** Note that the virtual term must be tagged with TERM_VNULL.  This
104433   ** TERM_VNULL tag will suppress the not-null check at the beginning
104434   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
104435   ** the start of the loop will prevent any results from being returned.
104436   */
104437   if( pExpr->op==TK_NOTNULL
104438    && pExpr->pLeft->op==TK_COLUMN
104439    && pExpr->pLeft->iColumn>=0
104440   ){
104441     Expr *pNewExpr;
104442     Expr *pLeft = pExpr->pLeft;
104443     int idxNew;
104444     WhereTerm *pNewTerm;
104445
104446     pNewExpr = sqlite3PExpr(pParse, TK_GT,
104447                             sqlite3ExprDup(db, pLeft, 0),
104448                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
104449
104450     idxNew = whereClauseInsert(pWC, pNewExpr,
104451                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
104452     if( idxNew ){
104453       pNewTerm = &pWC->a[idxNew];
104454       pNewTerm->prereqRight = 0;
104455       pNewTerm->leftCursor = pLeft->iTable;
104456       pNewTerm->u.leftColumn = pLeft->iColumn;
104457       pNewTerm->eOperator = WO_GT;
104458       pNewTerm->iParent = idxTerm;
104459       pTerm = &pWC->a[idxTerm];
104460       pTerm->nChild = 1;
104461       pTerm->wtFlags |= TERM_COPIED;
104462       pNewTerm->prereqAll = pTerm->prereqAll;
104463     }
104464   }
104465 #endif /* SQLITE_ENABLE_STAT */
104466
104467   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
104468   ** an index for tables to the left of the join.
104469   */
104470   pTerm->prereqRight |= extraRight;
104471 }
104472
104473 /*
104474 ** This function searches the expression list passed as the second argument
104475 ** for an expression of type TK_COLUMN that refers to the same column and
104476 ** uses the same collation sequence as the iCol'th column of index pIdx.
104477 ** Argument iBase is the cursor number used for the table that pIdx refers
104478 ** to.
104479 **
104480 ** If such an expression is found, its index in pList->a[] is returned. If
104481 ** no expression is found, -1 is returned.
104482 */
104483 static int findIndexCol(
104484   Parse *pParse,                  /* Parse context */
104485   ExprList *pList,                /* Expression list to search */
104486   int iBase,                      /* Cursor for table associated with pIdx */
104487   Index *pIdx,                    /* Index to match column of */
104488   int iCol                        /* Column of index to match */
104489 ){
104490   int i;
104491   const char *zColl = pIdx->azColl[iCol];
104492
104493   for(i=0; i<pList->nExpr; i++){
104494     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
104495     if( p->op==TK_COLUMN
104496      && p->iColumn==pIdx->aiColumn[iCol]
104497      && p->iTable==iBase
104498     ){
104499       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
104500       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
104501         return i;
104502       }
104503     }
104504   }
104505
104506   return -1;
104507 }
104508
104509 /*
104510 ** This routine determines if pIdx can be used to assist in processing a
104511 ** DISTINCT qualifier. In other words, it tests whether or not using this
104512 ** index for the outer loop guarantees that rows with equal values for
104513 ** all expressions in the pDistinct list are delivered grouped together.
104514 **
104515 ** For example, the query 
104516 **
104517 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
104518 **
104519 ** can benefit from any index on columns "b" and "c".
104520 */
104521 static int isDistinctIndex(
104522   Parse *pParse,                  /* Parsing context */
104523   WhereClause *pWC,               /* The WHERE clause */
104524   Index *pIdx,                    /* The index being considered */
104525   int base,                       /* Cursor number for the table pIdx is on */
104526   ExprList *pDistinct,            /* The DISTINCT expressions */
104527   int nEqCol                      /* Number of index columns with == */
104528 ){
104529   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
104530   int i;                          /* Iterator variable */
104531
104532   assert( pDistinct!=0 );
104533   if( pIdx->zName==0 || pDistinct->nExpr>=BMS ) return 0;
104534   testcase( pDistinct->nExpr==BMS-1 );
104535
104536   /* Loop through all the expressions in the distinct list. If any of them
104537   ** are not simple column references, return early. Otherwise, test if the
104538   ** WHERE clause contains a "col=X" clause. If it does, the expression
104539   ** can be ignored. If it does not, and the column does not belong to the
104540   ** same table as index pIdx, return early. Finally, if there is no
104541   ** matching "col=X" expression and the column is on the same table as pIdx,
104542   ** set the corresponding bit in variable mask.
104543   */
104544   for(i=0; i<pDistinct->nExpr; i++){
104545     WhereTerm *pTerm;
104546     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
104547     if( p->op!=TK_COLUMN ) return 0;
104548     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
104549     if( pTerm ){
104550       Expr *pX = pTerm->pExpr;
104551       CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104552       CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
104553       if( p1==p2 ) continue;
104554     }
104555     if( p->iTable!=base ) return 0;
104556     mask |= (((Bitmask)1) << i);
104557   }
104558
104559   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
104560     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
104561     if( iExpr<0 ) break;
104562     mask &= ~(((Bitmask)1) << iExpr);
104563   }
104564
104565   return (mask==0);
104566 }
104567
104568
104569 /*
104570 ** Return true if the DISTINCT expression-list passed as the third argument
104571 ** is redundant. A DISTINCT list is redundant if the database contains a
104572 ** UNIQUE index that guarantees that the result of the query will be distinct
104573 ** anyway.
104574 */
104575 static int isDistinctRedundant(
104576   Parse *pParse,
104577   SrcList *pTabList,
104578   WhereClause *pWC,
104579   ExprList *pDistinct
104580 ){
104581   Table *pTab;
104582   Index *pIdx;
104583   int i;                          
104584   int iBase;
104585
104586   /* If there is more than one table or sub-select in the FROM clause of
104587   ** this query, then it will not be possible to show that the DISTINCT 
104588   ** clause is redundant. */
104589   if( pTabList->nSrc!=1 ) return 0;
104590   iBase = pTabList->a[0].iCursor;
104591   pTab = pTabList->a[0].pTab;
104592
104593   /* If any of the expressions is an IPK column on table iBase, then return 
104594   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
104595   ** current SELECT is a correlated sub-query.
104596   */
104597   for(i=0; i<pDistinct->nExpr; i++){
104598     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
104599     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
104600   }
104601
104602   /* Loop through all indices on the table, checking each to see if it makes
104603   ** the DISTINCT qualifier redundant. It does so if:
104604   **
104605   **   1. The index is itself UNIQUE, and
104606   **
104607   **   2. All of the columns in the index are either part of the pDistinct
104608   **      list, or else the WHERE clause contains a term of the form "col=X",
104609   **      where X is a constant value. The collation sequences of the
104610   **      comparison and select-list expressions must match those of the index.
104611   **
104612   **   3. All of those index columns for which the WHERE clause does not
104613   **      contain a "col=X" term are subject to a NOT NULL constraint.
104614   */
104615   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
104616     if( pIdx->onError==OE_None ) continue;
104617     for(i=0; i<pIdx->nColumn; i++){
104618       int iCol = pIdx->aiColumn[i];
104619       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
104620         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
104621         if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
104622           break;
104623         }
104624       }
104625     }
104626     if( i==pIdx->nColumn ){
104627       /* This index implies that the DISTINCT qualifier is redundant. */
104628       return 1;
104629     }
104630   }
104631
104632   return 0;
104633 }
104634
104635 /*
104636 ** Prepare a crude estimate of the logarithm of the input value.
104637 ** The results need not be exact.  This is only used for estimating
104638 ** the total cost of performing operations with O(logN) or O(NlogN)
104639 ** complexity.  Because N is just a guess, it is no great tragedy if
104640 ** logN is a little off.
104641 */
104642 static double estLog(double N){
104643   double logN = 1;
104644   double x = 10;
104645   while( N>x ){
104646     logN += 1;
104647     x *= 10;
104648   }
104649   return logN;
104650 }
104651
104652 /*
104653 ** Two routines for printing the content of an sqlite3_index_info
104654 ** structure.  Used for testing and debugging only.  If neither
104655 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
104656 ** are no-ops.
104657 */
104658 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
104659 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
104660   int i;
104661   if( !sqlite3WhereTrace ) return;
104662   for(i=0; i<p->nConstraint; i++){
104663     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
104664        i,
104665        p->aConstraint[i].iColumn,
104666        p->aConstraint[i].iTermOffset,
104667        p->aConstraint[i].op,
104668        p->aConstraint[i].usable);
104669   }
104670   for(i=0; i<p->nOrderBy; i++){
104671     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
104672        i,
104673        p->aOrderBy[i].iColumn,
104674        p->aOrderBy[i].desc);
104675   }
104676 }
104677 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
104678   int i;
104679   if( !sqlite3WhereTrace ) return;
104680   for(i=0; i<p->nConstraint; i++){
104681     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
104682        i,
104683        p->aConstraintUsage[i].argvIndex,
104684        p->aConstraintUsage[i].omit);
104685   }
104686   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
104687   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
104688   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
104689   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
104690 }
104691 #else
104692 #define TRACE_IDX_INPUTS(A)
104693 #define TRACE_IDX_OUTPUTS(A)
104694 #endif
104695
104696 /* 
104697 ** Required because bestIndex() is called by bestOrClauseIndex() 
104698 */
104699 static void bestIndex(WhereBestIdx*);
104700
104701 /*
104702 ** This routine attempts to find an scanning strategy that can be used 
104703 ** to optimize an 'OR' expression that is part of a WHERE clause. 
104704 **
104705 ** The table associated with FROM clause term pSrc may be either a
104706 ** regular B-Tree table or a virtual table.
104707 */
104708 static void bestOrClauseIndex(WhereBestIdx *p){
104709 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
104710   WhereClause *pWC = p->pWC;           /* The WHERE clause */
104711   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
104712   const int iCur = pSrc->iCursor;      /* The cursor of the table  */
104713   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
104714   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
104715   WhereTerm *pTerm;                    /* A single term of the WHERE clause */
104716
104717   /* The OR-clause optimization is disallowed if the INDEXED BY or
104718   ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
104719   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
104720     return;
104721   }
104722   if( pWC->wctrlFlags & WHERE_AND_ONLY ){
104723     return;
104724   }
104725
104726   /* Search the WHERE clause terms for a usable WO_OR term. */
104727   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104728     if( (pTerm->eOperator & WO_OR)!=0
104729      && ((pTerm->prereqAll & ~maskSrc) & p->notReady)==0
104730      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
104731     ){
104732       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
104733       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
104734       WhereTerm *pOrTerm;
104735       int flags = WHERE_MULTI_OR;
104736       double rTotal = 0;
104737       double nRow = 0;
104738       Bitmask used = 0;
104739       WhereBestIdx sBOI;
104740
104741       sBOI = *p;
104742       sBOI.pOrderBy = 0;
104743       sBOI.pDistinct = 0;
104744       sBOI.ppIdxInfo = 0;
104745       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
104746         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
104747           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
104748         ));
104749         if( (pOrTerm->eOperator& WO_AND)!=0 ){
104750           sBOI.pWC = &pOrTerm->u.pAndInfo->wc;
104751           bestIndex(&sBOI);
104752         }else if( pOrTerm->leftCursor==iCur ){
104753           WhereClause tempWC;
104754           tempWC.pParse = pWC->pParse;
104755           tempWC.pMaskSet = pWC->pMaskSet;
104756           tempWC.pOuter = pWC;
104757           tempWC.op = TK_AND;
104758           tempWC.a = pOrTerm;
104759           tempWC.wctrlFlags = 0;
104760           tempWC.nTerm = 1;
104761           sBOI.pWC = &tempWC;
104762           bestIndex(&sBOI);
104763         }else{
104764           continue;
104765         }
104766         rTotal += sBOI.cost.rCost;
104767         nRow += sBOI.cost.plan.nRow;
104768         used |= sBOI.cost.used;
104769         if( rTotal>=p->cost.rCost ) break;
104770       }
104771
104772       /* If there is an ORDER BY clause, increase the scan cost to account 
104773       ** for the cost of the sort. */
104774       if( p->pOrderBy!=0 ){
104775         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
104776                     rTotal, rTotal+nRow*estLog(nRow)));
104777         rTotal += nRow*estLog(nRow);
104778       }
104779
104780       /* If the cost of scanning using this OR term for optimization is
104781       ** less than the current cost stored in pCost, replace the contents
104782       ** of pCost. */
104783       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
104784       if( rTotal<p->cost.rCost ){
104785         p->cost.rCost = rTotal;
104786         p->cost.used = used;
104787         p->cost.plan.nRow = nRow;
104788         p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
104789         p->cost.plan.wsFlags = flags;
104790         p->cost.plan.u.pTerm = pTerm;
104791       }
104792     }
104793   }
104794 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
104795 }
104796
104797 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104798 /*
104799 ** Return TRUE if the WHERE clause term pTerm is of a form where it
104800 ** could be used with an index to access pSrc, assuming an appropriate
104801 ** index existed.
104802 */
104803 static int termCanDriveIndex(
104804   WhereTerm *pTerm,              /* WHERE clause term to check */
104805   struct SrcList_item *pSrc,     /* Table we are trying to access */
104806   Bitmask notReady               /* Tables in outer loops of the join */
104807 ){
104808   char aff;
104809   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
104810   if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
104811   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
104812   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
104813   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
104814   return 1;
104815 }
104816 #endif
104817
104818 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104819 /*
104820 ** If the query plan for pSrc specified in pCost is a full table scan
104821 ** and indexing is allows (if there is no NOT INDEXED clause) and it
104822 ** possible to construct a transient index that would perform better
104823 ** than a full table scan even when the cost of constructing the index
104824 ** is taken into account, then alter the query plan to use the
104825 ** transient index.
104826 */
104827 static void bestAutomaticIndex(WhereBestIdx *p){
104828   Parse *pParse = p->pParse;            /* The parsing context */
104829   WhereClause *pWC = p->pWC;            /* The WHERE clause */
104830   struct SrcList_item *pSrc = p->pSrc;  /* The FROM clause term to search */
104831   double nTableRow;                     /* Rows in the input table */
104832   double logN;                          /* log(nTableRow) */
104833   double costTempIdx;         /* per-query cost of the transient index */
104834   WhereTerm *pTerm;           /* A single term of the WHERE clause */
104835   WhereTerm *pWCEnd;          /* End of pWC->a[] */
104836   Table *pTable;              /* Table tht might be indexed */
104837
104838   if( pParse->nQueryLoop<=(double)1 ){
104839     /* There is no point in building an automatic index for a single scan */
104840     return;
104841   }
104842   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
104843     /* Automatic indices are disabled at run-time */
104844     return;
104845   }
104846   if( (p->cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0
104847    && (p->cost.plan.wsFlags & WHERE_COVER_SCAN)==0
104848   ){
104849     /* We already have some kind of index in use for this query. */
104850     return;
104851   }
104852   if( pSrc->viaCoroutine ){
104853     /* Cannot index a co-routine */
104854     return;
104855   }
104856   if( pSrc->notIndexed ){
104857     /* The NOT INDEXED clause appears in the SQL. */
104858     return;
104859   }
104860   if( pSrc->isCorrelated ){
104861     /* The source is a correlated sub-query. No point in indexing it. */
104862     return;
104863   }
104864
104865   assert( pParse->nQueryLoop >= (double)1 );
104866   pTable = pSrc->pTab;
104867   nTableRow = pTable->nRowEst;
104868   logN = estLog(nTableRow);
104869   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
104870   if( costTempIdx>=p->cost.rCost ){
104871     /* The cost of creating the transient table would be greater than
104872     ** doing the full table scan */
104873     return;
104874   }
104875
104876   /* Search for any equality comparison term */
104877   pWCEnd = &pWC->a[pWC->nTerm];
104878   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104879     if( termCanDriveIndex(pTerm, pSrc, p->notReady) ){
104880       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
104881                     p->cost.rCost, costTempIdx));
104882       p->cost.rCost = costTempIdx;
104883       p->cost.plan.nRow = logN + 1;
104884       p->cost.plan.wsFlags = WHERE_TEMP_INDEX;
104885       p->cost.used = pTerm->prereqRight;
104886       break;
104887     }
104888   }
104889 }
104890 #else
104891 # define bestAutomaticIndex(A)  /* no-op */
104892 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
104893
104894
104895 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104896 /*
104897 ** Generate code to construct the Index object for an automatic index
104898 ** and to set up the WhereLevel object pLevel so that the code generator
104899 ** makes use of the automatic index.
104900 */
104901 static void constructAutomaticIndex(
104902   Parse *pParse,              /* The parsing context */
104903   WhereClause *pWC,           /* The WHERE clause */
104904   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
104905   Bitmask notReady,           /* Mask of cursors that are not available */
104906   WhereLevel *pLevel          /* Write new index here */
104907 ){
104908   int nColumn;                /* Number of columns in the constructed index */
104909   WhereTerm *pTerm;           /* A single term of the WHERE clause */
104910   WhereTerm *pWCEnd;          /* End of pWC->a[] */
104911   int nByte;                  /* Byte of memory needed for pIdx */
104912   Index *pIdx;                /* Object describing the transient index */
104913   Vdbe *v;                    /* Prepared statement under construction */
104914   int addrInit;               /* Address of the initialization bypass jump */
104915   Table *pTable;              /* The table being indexed */
104916   KeyInfo *pKeyinfo;          /* Key information for the index */   
104917   int addrTop;                /* Top of the index fill loop */
104918   int regRecord;              /* Register holding an index record */
104919   int n;                      /* Column counter */
104920   int i;                      /* Loop counter */
104921   int mxBitCol;               /* Maximum column in pSrc->colUsed */
104922   CollSeq *pColl;             /* Collating sequence to on a column */
104923   Bitmask idxCols;            /* Bitmap of columns used for indexing */
104924   Bitmask extraCols;          /* Bitmap of additional columns */
104925
104926   /* Generate code to skip over the creation and initialization of the
104927   ** transient index on 2nd and subsequent iterations of the loop. */
104928   v = pParse->pVdbe;
104929   assert( v!=0 );
104930   addrInit = sqlite3CodeOnce(pParse);
104931
104932   /* Count the number of columns that will be added to the index
104933   ** and used to match WHERE clause constraints */
104934   nColumn = 0;
104935   pTable = pSrc->pTab;
104936   pWCEnd = &pWC->a[pWC->nTerm];
104937   idxCols = 0;
104938   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104939     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104940       int iCol = pTerm->u.leftColumn;
104941       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104942       testcase( iCol==BMS );
104943       testcase( iCol==BMS-1 );
104944       if( (idxCols & cMask)==0 ){
104945         nColumn++;
104946         idxCols |= cMask;
104947       }
104948     }
104949   }
104950   assert( nColumn>0 );
104951   pLevel->plan.nEq = nColumn;
104952
104953   /* Count the number of additional columns needed to create a
104954   ** covering index.  A "covering index" is an index that contains all
104955   ** columns that are needed by the query.  With a covering index, the
104956   ** original table never needs to be accessed.  Automatic indices must
104957   ** be a covering index because the index will not be updated if the
104958   ** original table changes and the index and table cannot both be used
104959   ** if they go out of sync.
104960   */
104961   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
104962   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
104963   testcase( pTable->nCol==BMS-1 );
104964   testcase( pTable->nCol==BMS-2 );
104965   for(i=0; i<mxBitCol; i++){
104966     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
104967   }
104968   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
104969     nColumn += pTable->nCol - BMS + 1;
104970   }
104971   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
104972
104973   /* Construct the Index object to describe this index */
104974   nByte = sizeof(Index);
104975   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
104976   nByte += nColumn*sizeof(char*);   /* Index.azColl */
104977   nByte += nColumn;                 /* Index.aSortOrder */
104978   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
104979   if( pIdx==0 ) return;
104980   pLevel->plan.u.pIdx = pIdx;
104981   pIdx->azColl = (char**)&pIdx[1];
104982   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
104983   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
104984   pIdx->zName = "auto-index";
104985   pIdx->nColumn = nColumn;
104986   pIdx->pTable = pTable;
104987   n = 0;
104988   idxCols = 0;
104989   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104990     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104991       int iCol = pTerm->u.leftColumn;
104992       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104993       if( (idxCols & cMask)==0 ){
104994         Expr *pX = pTerm->pExpr;
104995         idxCols |= cMask;
104996         pIdx->aiColumn[n] = pTerm->u.leftColumn;
104997         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104998         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
104999         n++;
105000       }
105001     }
105002   }
105003   assert( (u32)n==pLevel->plan.nEq );
105004
105005   /* Add additional columns needed to make the automatic index into
105006   ** a covering index */
105007   for(i=0; i<mxBitCol; i++){
105008     if( extraCols & (((Bitmask)1)<<i) ){
105009       pIdx->aiColumn[n] = i;
105010       pIdx->azColl[n] = "BINARY";
105011       n++;
105012     }
105013   }
105014   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
105015     for(i=BMS-1; i<pTable->nCol; i++){
105016       pIdx->aiColumn[n] = i;
105017       pIdx->azColl[n] = "BINARY";
105018       n++;
105019     }
105020   }
105021   assert( n==nColumn );
105022
105023   /* Create the automatic index */
105024   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
105025   assert( pLevel->iIdxCur>=0 );
105026   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
105027                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
105028   VdbeComment((v, "for %s", pTable->zName));
105029
105030   /* Fill the automatic index with content */
105031   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
105032   regRecord = sqlite3GetTempReg(pParse);
105033   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
105034   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
105035   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
105036   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
105037   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
105038   sqlite3VdbeJumpHere(v, addrTop);
105039   sqlite3ReleaseTempReg(pParse, regRecord);
105040   
105041   /* Jump here when skipping the initialization */
105042   sqlite3VdbeJumpHere(v, addrInit);
105043 }
105044 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
105045
105046 #ifndef SQLITE_OMIT_VIRTUALTABLE
105047 /*
105048 ** Allocate and populate an sqlite3_index_info structure. It is the 
105049 ** responsibility of the caller to eventually release the structure
105050 ** by passing the pointer returned by this function to sqlite3_free().
105051 */
105052 static sqlite3_index_info *allocateIndexInfo(WhereBestIdx *p){
105053   Parse *pParse = p->pParse; 
105054   WhereClause *pWC = p->pWC;
105055   struct SrcList_item *pSrc = p->pSrc;
105056   ExprList *pOrderBy = p->pOrderBy;
105057   int i, j;
105058   int nTerm;
105059   struct sqlite3_index_constraint *pIdxCons;
105060   struct sqlite3_index_orderby *pIdxOrderBy;
105061   struct sqlite3_index_constraint_usage *pUsage;
105062   WhereTerm *pTerm;
105063   int nOrderBy;
105064   sqlite3_index_info *pIdxInfo;
105065
105066   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
105067
105068   /* Count the number of possible WHERE clause constraints referring
105069   ** to this virtual table */
105070   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
105071     if( pTerm->leftCursor != pSrc->iCursor ) continue;
105072     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
105073     testcase( pTerm->eOperator & WO_IN );
105074     testcase( pTerm->eOperator & WO_ISNULL );
105075     if( pTerm->eOperator & (WO_ISNULL) ) continue;
105076     if( pTerm->wtFlags & TERM_VNULL ) continue;
105077     nTerm++;
105078   }
105079
105080   /* If the ORDER BY clause contains only columns in the current 
105081   ** virtual table then allocate space for the aOrderBy part of
105082   ** the sqlite3_index_info structure.
105083   */
105084   nOrderBy = 0;
105085   if( pOrderBy ){
105086     int n = pOrderBy->nExpr;
105087     for(i=0; i<n; i++){
105088       Expr *pExpr = pOrderBy->a[i].pExpr;
105089       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
105090     }
105091     if( i==n){
105092       nOrderBy = n;
105093     }
105094   }
105095
105096   /* Allocate the sqlite3_index_info structure
105097   */
105098   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
105099                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
105100                            + sizeof(*pIdxOrderBy)*nOrderBy );
105101   if( pIdxInfo==0 ){
105102     sqlite3ErrorMsg(pParse, "out of memory");
105103     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
105104     return 0;
105105   }
105106
105107   /* Initialize the structure.  The sqlite3_index_info structure contains
105108   ** many fields that are declared "const" to prevent xBestIndex from
105109   ** changing them.  We have to do some funky casting in order to
105110   ** initialize those fields.
105111   */
105112   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
105113   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
105114   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
105115   *(int*)&pIdxInfo->nConstraint = nTerm;
105116   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
105117   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
105118   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
105119   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
105120                                                                    pUsage;
105121
105122   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
105123     u8 op;
105124     if( pTerm->leftCursor != pSrc->iCursor ) continue;
105125     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
105126     testcase( pTerm->eOperator & WO_IN );
105127     testcase( pTerm->eOperator & WO_ISNULL );
105128     if( pTerm->eOperator & (WO_ISNULL) ) continue;
105129     if( pTerm->wtFlags & TERM_VNULL ) continue;
105130     pIdxCons[j].iColumn = pTerm->u.leftColumn;
105131     pIdxCons[j].iTermOffset = i;
105132     op = (u8)pTerm->eOperator & WO_ALL;
105133     if( op==WO_IN ) op = WO_EQ;
105134     pIdxCons[j].op = op;
105135     /* The direct assignment in the previous line is possible only because
105136     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
105137     ** following asserts verify this fact. */
105138     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
105139     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
105140     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
105141     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
105142     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
105143     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
105144     assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
105145     j++;
105146   }
105147   for(i=0; i<nOrderBy; i++){
105148     Expr *pExpr = pOrderBy->a[i].pExpr;
105149     pIdxOrderBy[i].iColumn = pExpr->iColumn;
105150     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
105151   }
105152
105153   return pIdxInfo;
105154 }
105155
105156 /*
105157 ** The table object reference passed as the second argument to this function
105158 ** must represent a virtual table. This function invokes the xBestIndex()
105159 ** method of the virtual table with the sqlite3_index_info pointer passed
105160 ** as the argument.
105161 **
105162 ** If an error occurs, pParse is populated with an error message and a
105163 ** non-zero value is returned. Otherwise, 0 is returned and the output
105164 ** part of the sqlite3_index_info structure is left populated.
105165 **
105166 ** Whether or not an error is returned, it is the responsibility of the
105167 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
105168 ** that this is required.
105169 */
105170 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
105171   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
105172   int i;
105173   int rc;
105174
105175   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
105176   TRACE_IDX_INPUTS(p);
105177   rc = pVtab->pModule->xBestIndex(pVtab, p);
105178   TRACE_IDX_OUTPUTS(p);
105179
105180   if( rc!=SQLITE_OK ){
105181     if( rc==SQLITE_NOMEM ){
105182       pParse->db->mallocFailed = 1;
105183     }else if( !pVtab->zErrMsg ){
105184       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
105185     }else{
105186       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
105187     }
105188   }
105189   sqlite3_free(pVtab->zErrMsg);
105190   pVtab->zErrMsg = 0;
105191
105192   for(i=0; i<p->nConstraint; i++){
105193     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
105194       sqlite3ErrorMsg(pParse, 
105195           "table %s: xBestIndex returned an invalid plan", pTab->zName);
105196     }
105197   }
105198
105199   return pParse->nErr;
105200 }
105201
105202
105203 /*
105204 ** Compute the best index for a virtual table.
105205 **
105206 ** The best index is computed by the xBestIndex method of the virtual
105207 ** table module.  This routine is really just a wrapper that sets up
105208 ** the sqlite3_index_info structure that is used to communicate with
105209 ** xBestIndex.
105210 **
105211 ** In a join, this routine might be called multiple times for the
105212 ** same virtual table.  The sqlite3_index_info structure is created
105213 ** and initialized on the first invocation and reused on all subsequent
105214 ** invocations.  The sqlite3_index_info structure is also used when
105215 ** code is generated to access the virtual table.  The whereInfoDelete() 
105216 ** routine takes care of freeing the sqlite3_index_info structure after
105217 ** everybody has finished with it.
105218 */
105219 static void bestVirtualIndex(WhereBestIdx *p){
105220   Parse *pParse = p->pParse;      /* The parsing context */
105221   WhereClause *pWC = p->pWC;      /* The WHERE clause */
105222   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
105223   Table *pTab = pSrc->pTab;
105224   sqlite3_index_info *pIdxInfo;
105225   struct sqlite3_index_constraint *pIdxCons;
105226   struct sqlite3_index_constraint_usage *pUsage;
105227   WhereTerm *pTerm;
105228   int i, j, k;
105229   int nOrderBy;
105230   int sortOrder;                  /* Sort order for IN clauses */
105231   int bAllowIN;                   /* Allow IN optimizations */
105232   double rCost;
105233
105234   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
105235   ** malloc in allocateIndexInfo() fails and this function returns leaving
105236   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
105237   */
105238   memset(&p->cost, 0, sizeof(p->cost));
105239   p->cost.plan.wsFlags = WHERE_VIRTUALTABLE;
105240
105241   /* If the sqlite3_index_info structure has not been previously
105242   ** allocated and initialized, then allocate and initialize it now.
105243   */
105244   pIdxInfo = *p->ppIdxInfo;
105245   if( pIdxInfo==0 ){
105246     *p->ppIdxInfo = pIdxInfo = allocateIndexInfo(p);
105247   }
105248   if( pIdxInfo==0 ){
105249     return;
105250   }
105251
105252   /* At this point, the sqlite3_index_info structure that pIdxInfo points
105253   ** to will have been initialized, either during the current invocation or
105254   ** during some prior invocation.  Now we just have to customize the
105255   ** details of pIdxInfo for the current invocation and pass it to
105256   ** xBestIndex.
105257   */
105258
105259   /* The module name must be defined. Also, by this point there must
105260   ** be a pointer to an sqlite3_vtab structure. Otherwise
105261   ** sqlite3ViewGetColumnNames() would have picked up the error. 
105262   */
105263   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
105264   assert( sqlite3GetVTable(pParse->db, pTab) );
105265
105266   /* Try once or twice.  On the first attempt, allow IN optimizations.
105267   ** If an IN optimization is accepted by the virtual table xBestIndex
105268   ** method, but the  pInfo->aConstrainUsage.omit flag is not set, then
105269   ** the query will not work because it might allow duplicate rows in
105270   ** output.  In that case, run the xBestIndex method a second time
105271   ** without the IN constraints.  Usually this loop only runs once.
105272   ** The loop will exit using a "break" statement.
105273   */
105274   for(bAllowIN=1; 1; bAllowIN--){
105275     assert( bAllowIN==0 || bAllowIN==1 );
105276
105277     /* Set the aConstraint[].usable fields and initialize all 
105278     ** output variables to zero.
105279     **
105280     ** aConstraint[].usable is true for constraints where the right-hand
105281     ** side contains only references to tables to the left of the current
105282     ** table.  In other words, if the constraint is of the form:
105283     **
105284     **           column = expr
105285     **
105286     ** and we are evaluating a join, then the constraint on column is 
105287     ** only valid if all tables referenced in expr occur to the left
105288     ** of the table containing column.
105289     **
105290     ** The aConstraints[] array contains entries for all constraints
105291     ** on the current table.  That way we only have to compute it once
105292     ** even though we might try to pick the best index multiple times.
105293     ** For each attempt at picking an index, the order of tables in the
105294     ** join might be different so we have to recompute the usable flag
105295     ** each time.
105296     */
105297     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
105298     pUsage = pIdxInfo->aConstraintUsage;
105299     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
105300       j = pIdxCons->iTermOffset;
105301       pTerm = &pWC->a[j];
105302       if( (pTerm->prereqRight&p->notReady)==0
105303        && (bAllowIN || (pTerm->eOperator & WO_IN)==0)
105304       ){
105305         pIdxCons->usable = 1;
105306       }else{
105307         pIdxCons->usable = 0;
105308       }
105309     }
105310     memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
105311     if( pIdxInfo->needToFreeIdxStr ){
105312       sqlite3_free(pIdxInfo->idxStr);
105313     }
105314     pIdxInfo->idxStr = 0;
105315     pIdxInfo->idxNum = 0;
105316     pIdxInfo->needToFreeIdxStr = 0;
105317     pIdxInfo->orderByConsumed = 0;
105318     /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
105319     pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
105320     nOrderBy = pIdxInfo->nOrderBy;
105321     if( !p->pOrderBy ){
105322       pIdxInfo->nOrderBy = 0;
105323     }
105324   
105325     if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
105326       return;
105327     }
105328   
105329     sortOrder = SQLITE_SO_ASC;
105330     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
105331     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
105332       if( pUsage[i].argvIndex>0 ){
105333         j = pIdxCons->iTermOffset;
105334         pTerm = &pWC->a[j];
105335         p->cost.used |= pTerm->prereqRight;
105336         if( (pTerm->eOperator & WO_IN)!=0 ){
105337           if( pUsage[i].omit==0 ){
105338             /* Do not attempt to use an IN constraint if the virtual table
105339             ** says that the equivalent EQ constraint cannot be safely omitted.
105340             ** If we do attempt to use such a constraint, some rows might be
105341             ** repeated in the output. */
105342             break;
105343           }
105344           for(k=0; k<pIdxInfo->nOrderBy; k++){
105345             if( pIdxInfo->aOrderBy[k].iColumn==pIdxCons->iColumn ){
105346               sortOrder = pIdxInfo->aOrderBy[k].desc;
105347               break;
105348             }
105349           }
105350         }
105351       }
105352     }
105353     if( i>=pIdxInfo->nConstraint ) break;
105354   }
105355   
105356   /* If there is an ORDER BY clause, and the selected virtual table index
105357   ** does not satisfy it, increase the cost of the scan accordingly. This
105358   ** matches the processing for non-virtual tables in bestBtreeIndex().
105359   */
105360   rCost = pIdxInfo->estimatedCost;
105361   if( p->pOrderBy && pIdxInfo->orderByConsumed==0 ){
105362     rCost += estLog(rCost)*rCost;
105363   }
105364
105365   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
105366   ** inital value of lowestCost in this loop. If it is, then the
105367   ** (cost<lowestCost) test below will never be true.
105368   ** 
105369   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
105370   ** is defined.
105371   */
105372   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
105373     p->cost.rCost = (SQLITE_BIG_DBL/((double)2));
105374   }else{
105375     p->cost.rCost = rCost;
105376   }
105377   p->cost.plan.u.pVtabIdx = pIdxInfo;
105378   if( pIdxInfo->orderByConsumed ){
105379     assert( sortOrder==0 || sortOrder==1 );
105380     p->cost.plan.wsFlags |= WHERE_ORDERED + sortOrder*WHERE_REVERSE;
105381     p->cost.plan.nOBSat = nOrderBy;
105382   }else{
105383     p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
105384   }
105385   p->cost.plan.nEq = 0;
105386   pIdxInfo->nOrderBy = nOrderBy;
105387
105388   /* Try to find a more efficient access pattern by using multiple indexes
105389   ** to optimize an OR expression within the WHERE clause. 
105390   */
105391   bestOrClauseIndex(p);
105392 }
105393 #endif /* SQLITE_OMIT_VIRTUALTABLE */
105394
105395 #ifdef SQLITE_ENABLE_STAT3
105396 /*
105397 ** Estimate the location of a particular key among all keys in an
105398 ** index.  Store the results in aStat as follows:
105399 **
105400 **    aStat[0]      Est. number of rows less than pVal
105401 **    aStat[1]      Est. number of rows equal to pVal
105402 **
105403 ** Return SQLITE_OK on success.
105404 */
105405 static int whereKeyStats(
105406   Parse *pParse,              /* Database connection */
105407   Index *pIdx,                /* Index to consider domain of */
105408   sqlite3_value *pVal,        /* Value to consider */
105409   int roundUp,                /* Round up if true.  Round down if false */
105410   tRowcnt *aStat              /* OUT: stats written here */
105411 ){
105412   tRowcnt n;
105413   IndexSample *aSample;
105414   int i, eType;
105415   int isEq = 0;
105416   i64 v;
105417   double r, rS;
105418
105419   assert( roundUp==0 || roundUp==1 );
105420   assert( pIdx->nSample>0 );
105421   if( pVal==0 ) return SQLITE_ERROR;
105422   n = pIdx->aiRowEst[0];
105423   aSample = pIdx->aSample;
105424   eType = sqlite3_value_type(pVal);
105425
105426   if( eType==SQLITE_INTEGER ){
105427     v = sqlite3_value_int64(pVal);
105428     r = (i64)v;
105429     for(i=0; i<pIdx->nSample; i++){
105430       if( aSample[i].eType==SQLITE_NULL ) continue;
105431       if( aSample[i].eType>=SQLITE_TEXT ) break;
105432       if( aSample[i].eType==SQLITE_INTEGER ){
105433         if( aSample[i].u.i>=v ){
105434           isEq = aSample[i].u.i==v;
105435           break;
105436         }
105437       }else{
105438         assert( aSample[i].eType==SQLITE_FLOAT );
105439         if( aSample[i].u.r>=r ){
105440           isEq = aSample[i].u.r==r;
105441           break;
105442         }
105443       }
105444     }
105445   }else if( eType==SQLITE_FLOAT ){
105446     r = sqlite3_value_double(pVal);
105447     for(i=0; i<pIdx->nSample; i++){
105448       if( aSample[i].eType==SQLITE_NULL ) continue;
105449       if( aSample[i].eType>=SQLITE_TEXT ) break;
105450       if( aSample[i].eType==SQLITE_FLOAT ){
105451         rS = aSample[i].u.r;
105452       }else{
105453         rS = aSample[i].u.i;
105454       }
105455       if( rS>=r ){
105456         isEq = rS==r;
105457         break;
105458       }
105459     }
105460   }else if( eType==SQLITE_NULL ){
105461     i = 0;
105462     if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
105463   }else{
105464     assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
105465     for(i=0; i<pIdx->nSample; i++){
105466       if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
105467         break;
105468       }
105469     }
105470     if( i<pIdx->nSample ){      
105471       sqlite3 *db = pParse->db;
105472       CollSeq *pColl;
105473       const u8 *z;
105474       if( eType==SQLITE_BLOB ){
105475         z = (const u8 *)sqlite3_value_blob(pVal);
105476         pColl = db->pDfltColl;
105477         assert( pColl->enc==SQLITE_UTF8 );
105478       }else{
105479         pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
105480         if( pColl==0 ){
105481           return SQLITE_ERROR;
105482         }
105483         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
105484         if( !z ){
105485           return SQLITE_NOMEM;
105486         }
105487         assert( z && pColl && pColl->xCmp );
105488       }
105489       n = sqlite3ValueBytes(pVal, pColl->enc);
105490   
105491       for(; i<pIdx->nSample; i++){
105492         int c;
105493         int eSampletype = aSample[i].eType;
105494         if( eSampletype<eType ) continue;
105495         if( eSampletype!=eType ) break;
105496 #ifndef SQLITE_OMIT_UTF16
105497         if( pColl->enc!=SQLITE_UTF8 ){
105498           int nSample;
105499           char *zSample = sqlite3Utf8to16(
105500               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
105501           );
105502           if( !zSample ){
105503             assert( db->mallocFailed );
105504             return SQLITE_NOMEM;
105505           }
105506           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
105507           sqlite3DbFree(db, zSample);
105508         }else
105509 #endif
105510         {
105511           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
105512         }
105513         if( c>=0 ){
105514           if( c==0 ) isEq = 1;
105515           break;
105516         }
105517       }
105518     }
105519   }
105520
105521   /* At this point, aSample[i] is the first sample that is greater than
105522   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
105523   ** than pVal.  If aSample[i]==pVal, then isEq==1.
105524   */
105525   if( isEq ){
105526     assert( i<pIdx->nSample );
105527     aStat[0] = aSample[i].nLt;
105528     aStat[1] = aSample[i].nEq;
105529   }else{
105530     tRowcnt iLower, iUpper, iGap;
105531     if( i==0 ){
105532       iLower = 0;
105533       iUpper = aSample[0].nLt;
105534     }else{
105535       iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
105536       iLower = aSample[i-1].nEq + aSample[i-1].nLt;
105537     }
105538     aStat[1] = pIdx->avgEq;
105539     if( iLower>=iUpper ){
105540       iGap = 0;
105541     }else{
105542       iGap = iUpper - iLower;
105543     }
105544     if( roundUp ){
105545       iGap = (iGap*2)/3;
105546     }else{
105547       iGap = iGap/3;
105548     }
105549     aStat[0] = iLower + iGap;
105550   }
105551   return SQLITE_OK;
105552 }
105553 #endif /* SQLITE_ENABLE_STAT3 */
105554
105555 /*
105556 ** If expression pExpr represents a literal value, set *pp to point to
105557 ** an sqlite3_value structure containing the same value, with affinity
105558 ** aff applied to it, before returning. It is the responsibility of the 
105559 ** caller to eventually release this structure by passing it to 
105560 ** sqlite3ValueFree().
105561 **
105562 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
105563 ** is an SQL variable that currently has a non-NULL value bound to it,
105564 ** create an sqlite3_value structure containing this value, again with
105565 ** affinity aff applied to it, instead.
105566 **
105567 ** If neither of the above apply, set *pp to NULL.
105568 **
105569 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
105570 */
105571 #ifdef SQLITE_ENABLE_STAT3
105572 static int valueFromExpr(
105573   Parse *pParse, 
105574   Expr *pExpr, 
105575   u8 aff, 
105576   sqlite3_value **pp
105577 ){
105578   if( pExpr->op==TK_VARIABLE
105579    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
105580   ){
105581     int iVar = pExpr->iColumn;
105582     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
105583     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
105584     return SQLITE_OK;
105585   }
105586   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
105587 }
105588 #endif
105589
105590 /*
105591 ** This function is used to estimate the number of rows that will be visited
105592 ** by scanning an index for a range of values. The range may have an upper
105593 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
105594 ** and lower bounds are represented by pLower and pUpper respectively. For
105595 ** example, assuming that index p is on t1(a):
105596 **
105597 **   ... FROM t1 WHERE a > ? AND a < ? ...
105598 **                    |_____|   |_____|
105599 **                       |         |
105600 **                     pLower    pUpper
105601 **
105602 ** If either of the upper or lower bound is not present, then NULL is passed in
105603 ** place of the corresponding WhereTerm.
105604 **
105605 ** The nEq parameter is passed the index of the index column subject to the
105606 ** range constraint. Or, equivalently, the number of equality constraints
105607 ** optimized by the proposed index scan. For example, assuming index p is
105608 ** on t1(a, b), and the SQL query is:
105609 **
105610 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
105611 **
105612 ** then nEq should be passed the value 1 (as the range restricted column,
105613 ** b, is the second left-most column of the index). Or, if the query is:
105614 **
105615 **   ... FROM t1 WHERE a > ? AND a < ? ...
105616 **
105617 ** then nEq should be passed 0.
105618 **
105619 ** The returned value is an integer divisor to reduce the estimated
105620 ** search space.  A return value of 1 means that range constraints are
105621 ** no help at all.  A return value of 2 means range constraints are
105622 ** expected to reduce the search space by half.  And so forth...
105623 **
105624 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
105625 ** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
105626 ** results in a return of 4 and a range constraint (x>? AND x<?) results
105627 ** in a return of 16.
105628 */
105629 static int whereRangeScanEst(
105630   Parse *pParse,       /* Parsing & code generating context */
105631   Index *p,            /* The index containing the range-compared column; "x" */
105632   int nEq,             /* index into p->aCol[] of the range-compared column */
105633   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
105634   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
105635   double *pRangeDiv   /* OUT: Reduce search space by this divisor */
105636 ){
105637   int rc = SQLITE_OK;
105638
105639 #ifdef SQLITE_ENABLE_STAT3
105640
105641   if( nEq==0 && p->nSample ){
105642     sqlite3_value *pRangeVal;
105643     tRowcnt iLower = 0;
105644     tRowcnt iUpper = p->aiRowEst[0];
105645     tRowcnt a[2];
105646     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
105647
105648     if( pLower ){
105649       Expr *pExpr = pLower->pExpr->pRight;
105650       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
105651       assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
105652       if( rc==SQLITE_OK
105653        && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
105654       ){
105655         iLower = a[0];
105656         if( (pLower->eOperator & WO_GT)!=0 ) iLower += a[1];
105657       }
105658       sqlite3ValueFree(pRangeVal);
105659     }
105660     if( rc==SQLITE_OK && pUpper ){
105661       Expr *pExpr = pUpper->pExpr->pRight;
105662       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
105663       assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
105664       if( rc==SQLITE_OK
105665        && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
105666       ){
105667         iUpper = a[0];
105668         if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
105669       }
105670       sqlite3ValueFree(pRangeVal);
105671     }
105672     if( rc==SQLITE_OK ){
105673       if( iUpper<=iLower ){
105674         *pRangeDiv = (double)p->aiRowEst[0];
105675       }else{
105676         *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
105677       }
105678       WHERETRACE(("range scan regions: %u..%u  div=%g\n",
105679                   (u32)iLower, (u32)iUpper, *pRangeDiv));
105680       return SQLITE_OK;
105681     }
105682   }
105683 #else
105684   UNUSED_PARAMETER(pParse);
105685   UNUSED_PARAMETER(p);
105686   UNUSED_PARAMETER(nEq);
105687 #endif
105688   assert( pLower || pUpper );
105689   *pRangeDiv = (double)1;
105690   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
105691   if( pUpper ) *pRangeDiv *= (double)4;
105692   return rc;
105693 }
105694
105695 #ifdef SQLITE_ENABLE_STAT3
105696 /*
105697 ** Estimate the number of rows that will be returned based on
105698 ** an equality constraint x=VALUE and where that VALUE occurs in
105699 ** the histogram data.  This only works when x is the left-most
105700 ** column of an index and sqlite_stat3 histogram data is available
105701 ** for that index.  When pExpr==NULL that means the constraint is
105702 ** "x IS NULL" instead of "x=VALUE".
105703 **
105704 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
105705 ** If unable to make an estimate, leave *pnRow unchanged and return
105706 ** non-zero.
105707 **
105708 ** This routine can fail if it is unable to load a collating sequence
105709 ** required for string comparison, or if unable to allocate memory
105710 ** for a UTF conversion required for comparison.  The error is stored
105711 ** in the pParse structure.
105712 */
105713 static int whereEqualScanEst(
105714   Parse *pParse,       /* Parsing & code generating context */
105715   Index *p,            /* The index whose left-most column is pTerm */
105716   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
105717   double *pnRow        /* Write the revised row estimate here */
105718 ){
105719   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
105720   u8 aff;                   /* Column affinity */
105721   int rc;                   /* Subfunction return code */
105722   tRowcnt a[2];             /* Statistics */
105723
105724   assert( p->aSample!=0 );
105725   assert( p->nSample>0 );
105726   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
105727   if( pExpr ){
105728     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
105729     if( rc ) goto whereEqualScanEst_cancel;
105730   }else{
105731     pRhs = sqlite3ValueNew(pParse->db);
105732   }
105733   if( pRhs==0 ) return SQLITE_NOTFOUND;
105734   rc = whereKeyStats(pParse, p, pRhs, 0, a);
105735   if( rc==SQLITE_OK ){
105736     WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
105737     *pnRow = a[1];
105738   }
105739 whereEqualScanEst_cancel:
105740   sqlite3ValueFree(pRhs);
105741   return rc;
105742 }
105743 #endif /* defined(SQLITE_ENABLE_STAT3) */
105744
105745 #ifdef SQLITE_ENABLE_STAT3
105746 /*
105747 ** Estimate the number of rows that will be returned based on
105748 ** an IN constraint where the right-hand side of the IN operator
105749 ** is a list of values.  Example:
105750 **
105751 **        WHERE x IN (1,2,3,4)
105752 **
105753 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
105754 ** If unable to make an estimate, leave *pnRow unchanged and return
105755 ** non-zero.
105756 **
105757 ** This routine can fail if it is unable to load a collating sequence
105758 ** required for string comparison, or if unable to allocate memory
105759 ** for a UTF conversion required for comparison.  The error is stored
105760 ** in the pParse structure.
105761 */
105762 static int whereInScanEst(
105763   Parse *pParse,       /* Parsing & code generating context */
105764   Index *p,            /* The index whose left-most column is pTerm */
105765   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
105766   double *pnRow        /* Write the revised row estimate here */
105767 ){
105768   int rc = SQLITE_OK;         /* Subfunction return code */
105769   double nEst;                /* Number of rows for a single term */
105770   double nRowEst = (double)0; /* New estimate of the number of rows */
105771   int i;                      /* Loop counter */
105772
105773   assert( p->aSample!=0 );
105774   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
105775     nEst = p->aiRowEst[0];
105776     rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
105777     nRowEst += nEst;
105778   }
105779   if( rc==SQLITE_OK ){
105780     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
105781     *pnRow = nRowEst;
105782     WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
105783   }
105784   return rc;
105785 }
105786 #endif /* defined(SQLITE_ENABLE_STAT3) */
105787
105788 /*
105789 ** Check to see if column iCol of the table with cursor iTab will appear
105790 ** in sorted order according to the current query plan.
105791 **
105792 ** Return values:
105793 **
105794 **    0   iCol is not ordered
105795 **    1   iCol has only a single value
105796 **    2   iCol is in ASC order
105797 **    3   iCol is in DESC order
105798 */
105799 static int isOrderedColumn(
105800   WhereBestIdx *p,
105801   int iTab,
105802   int iCol
105803 ){
105804   int i, j;
105805   WhereLevel *pLevel = &p->aLevel[p->i-1];
105806   Index *pIdx;
105807   u8 sortOrder;
105808   for(i=p->i-1; i>=0; i--, pLevel--){
105809     if( pLevel->iTabCur!=iTab ) continue;
105810     if( (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
105811       return 1;
105812     }
105813     assert( (pLevel->plan.wsFlags & WHERE_ORDERED)!=0 );
105814     if( (pIdx = pLevel->plan.u.pIdx)!=0 ){
105815       if( iCol<0 ){
105816         sortOrder = 0;
105817         testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
105818       }else{
105819         int n = pIdx->nColumn;
105820         for(j=0; j<n; j++){
105821           if( iCol==pIdx->aiColumn[j] ) break;
105822         }
105823         if( j>=n ) return 0;
105824         sortOrder = pIdx->aSortOrder[j];
105825         testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
105826       }
105827     }else{
105828       if( iCol!=(-1) ) return 0;
105829       sortOrder = 0;
105830       testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
105831     }
105832     if( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 ){
105833       assert( sortOrder==0 || sortOrder==1 );
105834       testcase( sortOrder==1 );
105835       sortOrder = 1 - sortOrder;
105836     }
105837     return sortOrder+2;
105838   }
105839   return 0;
105840 }
105841
105842 /*
105843 ** This routine decides if pIdx can be used to satisfy the ORDER BY
105844 ** clause, either in whole or in part.  The return value is the 
105845 ** cumulative number of terms in the ORDER BY clause that are satisfied
105846 ** by the index pIdx and other indices in outer loops.
105847 **
105848 ** The table being queried has a cursor number of "base".  pIdx is the
105849 ** index that is postulated for use to access the table.
105850 **
105851 ** The *pbRev value is set to 0 order 1 depending on whether or not
105852 ** pIdx should be run in the forward order or in reverse order.
105853 */
105854 static int isSortingIndex(
105855   WhereBestIdx *p,    /* Best index search context */
105856   Index *pIdx,        /* The index we are testing */
105857   int base,           /* Cursor number for the table to be sorted */
105858   int *pbRev,         /* Set to 1 for reverse-order scan of pIdx */
105859   int *pbObUnique     /* ORDER BY column values will different in every row */
105860 ){
105861   int i;                        /* Number of pIdx terms used */
105862   int j;                        /* Number of ORDER BY terms satisfied */
105863   int sortOrder = 2;            /* 0: forward.  1: backward.  2: unknown */
105864   int nTerm;                    /* Number of ORDER BY terms */
105865   struct ExprList_item *pOBItem;/* A term of the ORDER BY clause */
105866   Table *pTab = pIdx->pTable;   /* Table that owns index pIdx */
105867   ExprList *pOrderBy;           /* The ORDER BY clause */
105868   Parse *pParse = p->pParse;    /* Parser context */
105869   sqlite3 *db = pParse->db;     /* Database connection */
105870   int nPriorSat;                /* ORDER BY terms satisfied by outer loops */
105871   int seenRowid = 0;            /* True if an ORDER BY rowid term is seen */
105872   int uniqueNotNull;            /* pIdx is UNIQUE with all terms are NOT NULL */
105873   int outerObUnique;            /* Outer loops generate different values in
105874                                 ** every row for the ORDER BY columns */
105875
105876   if( p->i==0 ){
105877     nPriorSat = 0;
105878     outerObUnique = 1;
105879   }else{
105880     u32 wsFlags = p->aLevel[p->i-1].plan.wsFlags;
105881     nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
105882     if( (wsFlags & WHERE_ORDERED)==0 ){
105883       /* This loop cannot be ordered unless the next outer loop is
105884       ** also ordered */
105885       return nPriorSat;
105886     }
105887     if( OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ){
105888       /* Only look at the outer-most loop if the OrderByIdxJoin
105889       ** optimization is disabled */
105890       return nPriorSat;
105891     }
105892     testcase( wsFlags & WHERE_OB_UNIQUE );
105893     testcase( wsFlags & WHERE_ALL_UNIQUE );
105894     outerObUnique = (wsFlags & (WHERE_OB_UNIQUE|WHERE_ALL_UNIQUE))!=0;
105895   }
105896   pOrderBy = p->pOrderBy;
105897   assert( pOrderBy!=0 );
105898   if( pIdx->bUnordered ){
105899     /* Hash indices (indicated by the "unordered" tag on sqlite_stat1) cannot
105900     ** be used for sorting */
105901     return nPriorSat;
105902   }
105903   nTerm = pOrderBy->nExpr;
105904   uniqueNotNull = pIdx->onError!=OE_None;
105905   assert( nTerm>0 );
105906
105907   /* Argument pIdx must either point to a 'real' named index structure, 
105908   ** or an index structure allocated on the stack by bestBtreeIndex() to
105909   ** represent the rowid index that is part of every table.  */
105910   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
105911
105912   /* Match terms of the ORDER BY clause against columns of
105913   ** the index.
105914   **
105915   ** Note that indices have pIdx->nColumn regular columns plus
105916   ** one additional column containing the rowid.  The rowid column
105917   ** of the index is also allowed to match against the ORDER BY
105918   ** clause.
105919   */
105920   j = nPriorSat;
105921   for(i=0,pOBItem=&pOrderBy->a[j]; j<nTerm && i<=pIdx->nColumn; i++){
105922     Expr *pOBExpr;          /* The expression of the ORDER BY pOBItem */
105923     CollSeq *pColl;         /* The collating sequence of pOBExpr */
105924     int termSortOrder;      /* Sort order for this term */
105925     int iColumn;            /* The i-th column of the index.  -1 for rowid */
105926     int iSortOrder;         /* 1 for DESC, 0 for ASC on the i-th index term */
105927     int isEq;               /* Subject to an == or IS NULL constraint */
105928     int isMatch;            /* ORDER BY term matches the index term */
105929     const char *zColl;      /* Name of collating sequence for i-th index term */
105930     WhereTerm *pConstraint; /* A constraint in the WHERE clause */
105931
105932     /* If the next term of the ORDER BY clause refers to anything other than
105933     ** a column in the "base" table, then this index will not be of any
105934     ** further use in handling the ORDER BY. */
105935     pOBExpr = sqlite3ExprSkipCollate(pOBItem->pExpr);
105936     if( pOBExpr->op!=TK_COLUMN || pOBExpr->iTable!=base ){
105937       break;
105938     }
105939
105940     /* Find column number and collating sequence for the next entry
105941     ** in the index */
105942     if( pIdx->zName && i<pIdx->nColumn ){
105943       iColumn = pIdx->aiColumn[i];
105944       if( iColumn==pIdx->pTable->iPKey ){
105945         iColumn = -1;
105946       }
105947       iSortOrder = pIdx->aSortOrder[i];
105948       zColl = pIdx->azColl[i];
105949       assert( zColl!=0 );
105950     }else{
105951       iColumn = -1;
105952       iSortOrder = 0;
105953       zColl = 0;
105954     }
105955
105956     /* Check to see if the column number and collating sequence of the
105957     ** index match the column number and collating sequence of the ORDER BY
105958     ** clause entry.  Set isMatch to 1 if they both match. */
105959     if( pOBExpr->iColumn==iColumn ){
105960       if( zColl ){
105961         pColl = sqlite3ExprCollSeq(pParse, pOBItem->pExpr);
105962         if( !pColl ) pColl = db->pDfltColl;
105963         isMatch = sqlite3StrICmp(pColl->zName, zColl)==0;
105964       }else{
105965         isMatch = 1;
105966       }
105967     }else{
105968       isMatch = 0;
105969     }
105970
105971     /* termSortOrder is 0 or 1 for whether or not the access loop should
105972     ** run forward or backwards (respectively) in order to satisfy this 
105973     ** term of the ORDER BY clause. */
105974     assert( pOBItem->sortOrder==0 || pOBItem->sortOrder==1 );
105975     assert( iSortOrder==0 || iSortOrder==1 );
105976     termSortOrder = iSortOrder ^ pOBItem->sortOrder;
105977
105978     /* If X is the column in the index and ORDER BY clause, check to see
105979     ** if there are any X= or X IS NULL constraints in the WHERE clause. */
105980     pConstraint = findTerm(p->pWC, base, iColumn, p->notReady,
105981                            WO_EQ|WO_ISNULL|WO_IN, pIdx);
105982     if( pConstraint==0 ){
105983       isEq = 0;
105984     }else if( (pConstraint->eOperator & WO_IN)!=0 ){
105985       isEq = 0;
105986     }else if( (pConstraint->eOperator & WO_ISNULL)!=0 ){
105987       uniqueNotNull = 0;
105988       isEq = 1;  /* "X IS NULL" means X has only a single value */
105989     }else if( pConstraint->prereqRight==0 ){
105990       isEq = 1;  /* Constraint "X=constant" means X has only a single value */
105991     }else{
105992       Expr *pRight = pConstraint->pExpr->pRight;
105993       if( pRight->op==TK_COLUMN ){
105994         WHERETRACE(("       .. isOrderedColumn(tab=%d,col=%d)",
105995                     pRight->iTable, pRight->iColumn));
105996         isEq = isOrderedColumn(p, pRight->iTable, pRight->iColumn);
105997         WHERETRACE((" -> isEq=%d\n", isEq));
105998
105999         /* If the constraint is of the form X=Y where Y is an ordered value
106000         ** in an outer loop, then make sure the sort order of Y matches the
106001         ** sort order required for X. */
106002         if( isMatch && isEq>=2 && isEq!=pOBItem->sortOrder+2 ){
106003           testcase( isEq==2 );
106004           testcase( isEq==3 );
106005           break;
106006         }
106007       }else{
106008         isEq = 0;  /* "X=expr" places no ordering constraints on X */
106009       }
106010     }
106011     if( !isMatch ){
106012       if( isEq==0 ){
106013         break;
106014       }else{
106015         continue;
106016       }
106017     }else if( isEq!=1 ){
106018       if( sortOrder==2 ){
106019         sortOrder = termSortOrder;
106020       }else if( termSortOrder!=sortOrder ){
106021         break;
106022       }
106023     }
106024     j++;
106025     pOBItem++;
106026     if( iColumn<0 ){
106027       seenRowid = 1;
106028       break;
106029     }else if( pTab->aCol[iColumn].notNull==0 && isEq!=1 ){
106030       testcase( isEq==0 );
106031       testcase( isEq==2 );
106032       testcase( isEq==3 );
106033       uniqueNotNull = 0;
106034     }
106035   }
106036   if( seenRowid ){
106037     uniqueNotNull = 1;
106038   }else if( uniqueNotNull==0 || i<pIdx->nColumn ){
106039     uniqueNotNull = 0;
106040   }
106041
106042   /* If we have not found at least one ORDER BY term that matches the
106043   ** index, then show no progress. */
106044   if( pOBItem==&pOrderBy->a[nPriorSat] ) return nPriorSat;
106045
106046   /* Either the outer queries must generate rows where there are no two
106047   ** rows with the same values in all ORDER BY columns, or else this
106048   ** loop must generate just a single row of output.  Example:  Suppose
106049   ** the outer loops generate A=1 and A=1, and this loop generates B=3
106050   ** and B=4.  Then without the following test, ORDER BY A,B would 
106051   ** generate the wrong order output: 1,3 1,4 1,3 1,4
106052   */
106053   if( outerObUnique==0 && uniqueNotNull==0 ) return nPriorSat;
106054   *pbObUnique = uniqueNotNull;
106055
106056   /* Return the necessary scan order back to the caller */
106057   *pbRev = sortOrder & 1;
106058
106059   /* If there was an "ORDER BY rowid" term that matched, or it is only
106060   ** possible for a single row from this table to match, then skip over
106061   ** any additional ORDER BY terms dealing with this table.
106062   */
106063   if( uniqueNotNull ){
106064     /* Advance j over additional ORDER BY terms associated with base */
106065     WhereMaskSet *pMS = p->pWC->pMaskSet;
106066     Bitmask m = ~getMask(pMS, base);
106067     while( j<nTerm && (exprTableUsage(pMS, pOrderBy->a[j].pExpr)&m)==0 ){
106068       j++;
106069     }
106070   }
106071   return j;
106072 }
106073
106074 /*
106075 ** Find the best query plan for accessing a particular table.  Write the
106076 ** best query plan and its cost into the p->cost.
106077 **
106078 ** The lowest cost plan wins.  The cost is an estimate of the amount of
106079 ** CPU and disk I/O needed to process the requested result.
106080 ** Factors that influence cost include:
106081 **
106082 **    *  The estimated number of rows that will be retrieved.  (The
106083 **       fewer the better.)
106084 **
106085 **    *  Whether or not sorting must occur.
106086 **
106087 **    *  Whether or not there must be separate lookups in the
106088 **       index and in the main table.
106089 **
106090 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
106091 ** the SQL statement, then this function only considers plans using the 
106092 ** named index. If no such plan is found, then the returned cost is
106093 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
106094 ** then the cost is calculated in the usual way.
106095 **
106096 ** If a NOT INDEXED clause was attached to the table 
106097 ** in the SELECT statement, then no indexes are considered. However, the 
106098 ** selected plan may still take advantage of the built-in rowid primary key
106099 ** index.
106100 */
106101 static void bestBtreeIndex(WhereBestIdx *p){
106102   Parse *pParse = p->pParse;  /* The parsing context */
106103   WhereClause *pWC = p->pWC;  /* The WHERE clause */
106104   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106105   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
106106   Index *pProbe;              /* An index we are evaluating */
106107   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
106108   int eqTermMask;             /* Current mask of valid equality operators */
106109   int idxEqTermMask;          /* Index mask of valid equality operators */
106110   Index sPk;                  /* A fake index object for the primary key */
106111   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
106112   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
106113   int wsFlagMask;             /* Allowed flags in p->cost.plan.wsFlag */
106114   int nPriorSat;              /* ORDER BY terms satisfied by outer loops */
106115   int nOrderBy;               /* Number of ORDER BY terms */
106116   char bSortInit;             /* Initializer for bSort in inner loop */
106117   char bDistInit;             /* Initializer for bDist in inner loop */
106118
106119
106120   /* Initialize the cost to a worst-case value */
106121   memset(&p->cost, 0, sizeof(p->cost));
106122   p->cost.rCost = SQLITE_BIG_DBL;
106123
106124   /* If the pSrc table is the right table of a LEFT JOIN then we may not
106125   ** use an index to satisfy IS NULL constraints on that table.  This is
106126   ** because columns might end up being NULL if the table does not match -
106127   ** a circumstance which the index cannot help us discover.  Ticket #2177.
106128   */
106129   if( pSrc->jointype & JT_LEFT ){
106130     idxEqTermMask = WO_EQ|WO_IN;
106131   }else{
106132     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
106133   }
106134
106135   if( pSrc->pIndex ){
106136     /* An INDEXED BY clause specifies a particular index to use */
106137     pIdx = pProbe = pSrc->pIndex;
106138     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
106139     eqTermMask = idxEqTermMask;
106140   }else{
106141     /* There is no INDEXED BY clause.  Create a fake Index object in local
106142     ** variable sPk to represent the rowid primary key index.  Make this
106143     ** fake index the first in a chain of Index objects with all of the real
106144     ** indices to follow */
106145     Index *pFirst;                  /* First of real indices on the table */
106146     memset(&sPk, 0, sizeof(Index));
106147     sPk.nColumn = 1;
106148     sPk.aiColumn = &aiColumnPk;
106149     sPk.aiRowEst = aiRowEstPk;
106150     sPk.onError = OE_Replace;
106151     sPk.pTable = pSrc->pTab;
106152     aiRowEstPk[0] = pSrc->pTab->nRowEst;
106153     aiRowEstPk[1] = 1;
106154     pFirst = pSrc->pTab->pIndex;
106155     if( pSrc->notIndexed==0 ){
106156       /* The real indices of the table are only considered if the
106157       ** NOT INDEXED qualifier is omitted from the FROM clause */
106158       sPk.pNext = pFirst;
106159     }
106160     pProbe = &sPk;
106161     wsFlagMask = ~(
106162         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
106163     );
106164     eqTermMask = WO_EQ|WO_IN;
106165     pIdx = 0;
106166   }
106167
106168   nOrderBy = p->pOrderBy ? p->pOrderBy->nExpr : 0;
106169   if( p->i ){
106170     nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
106171     bSortInit = nPriorSat<nOrderBy;
106172     bDistInit = 0;
106173   }else{
106174     nPriorSat = 0;
106175     bSortInit = nOrderBy>0;
106176     bDistInit = p->pDistinct!=0;
106177   }
106178
106179   /* Loop over all indices looking for the best one to use
106180   */
106181   for(; pProbe; pIdx=pProbe=pProbe->pNext){
106182     const tRowcnt * const aiRowEst = pProbe->aiRowEst;
106183     WhereCost pc;               /* Cost of using pProbe */
106184     double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
106185
106186     /* The following variables are populated based on the properties of
106187     ** index being evaluated. They are then used to determine the expected
106188     ** cost and number of rows returned.
106189     **
106190     **  pc.plan.nEq: 
106191     **    Number of equality terms that can be implemented using the index.
106192     **    In other words, the number of initial fields in the index that
106193     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
106194     **
106195     **  nInMul:  
106196     **    The "in-multiplier". This is an estimate of how many seek operations 
106197     **    SQLite must perform on the index in question. For example, if the 
106198     **    WHERE clause is:
106199     **
106200     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
106201     **
106202     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
106203     **    set to 9. Given the same schema and either of the following WHERE 
106204     **    clauses:
106205     **
106206     **      WHERE a =  1
106207     **      WHERE a >= 2
106208     **
106209     **    nInMul is set to 1.
106210     **
106211     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
106212     **    the sub-select is assumed to return 25 rows for the purposes of 
106213     **    determining nInMul.
106214     **
106215     **  bInEst:  
106216     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
106217     **    in determining the value of nInMul.  Note that the RHS of the
106218     **    IN operator must be a SELECT, not a value list, for this variable
106219     **    to be true.
106220     **
106221     **  rangeDiv:
106222     **    An estimate of a divisor by which to reduce the search space due
106223     **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
106224     **    data, a single inequality reduces the search space to 1/4rd its
106225     **    original size (rangeDiv==4).  Two inequalities reduce the search
106226     **    space to 1/16th of its original size (rangeDiv==16).
106227     **
106228     **  bSort:   
106229     **    Boolean. True if there is an ORDER BY clause that will require an 
106230     **    external sort (i.e. scanning the index being evaluated will not 
106231     **    correctly order records).
106232     **
106233     **  bDist:
106234     **    Boolean. True if there is a DISTINCT clause that will require an 
106235     **    external btree.
106236     **
106237     **  bLookup: 
106238     **    Boolean. True if a table lookup is required for each index entry
106239     **    visited.  In other words, true if this is not a covering index.
106240     **    This is always false for the rowid primary key index of a table.
106241     **    For other indexes, it is true unless all the columns of the table
106242     **    used by the SELECT statement are present in the index (such an
106243     **    index is sometimes described as a covering index).
106244     **    For example, given the index on (a, b), the second of the following 
106245     **    two queries requires table b-tree lookups in order to find the value
106246     **    of column c, but the first does not because columns a and b are
106247     **    both available in the index.
106248     **
106249     **             SELECT a, b    FROM tbl WHERE a = 1;
106250     **             SELECT a, b, c FROM tbl WHERE a = 1;
106251     */
106252     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
106253     int nInMul = 1;               /* Number of distinct equalities to lookup */
106254     double rangeDiv = (double)1;  /* Estimated reduction in search space */
106255     int nBound = 0;               /* Number of range constraints seen */
106256     char bSort = bSortInit;       /* True if external sort required */
106257     char bDist = bDistInit;       /* True if index cannot help with DISTINCT */
106258     char bLookup = 0;             /* True if not a covering index */
106259     WhereTerm *pTerm;             /* A single term of the WHERE clause */
106260 #ifdef SQLITE_ENABLE_STAT3
106261     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
106262 #endif
106263
106264     WHERETRACE((
106265       "   %s(%s):\n",
106266       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk")
106267     ));
106268     memset(&pc, 0, sizeof(pc));
106269     pc.plan.nOBSat = nPriorSat;
106270
106271     /* Determine the values of pc.plan.nEq and nInMul */
106272     for(pc.plan.nEq=0; pc.plan.nEq<pProbe->nColumn; pc.plan.nEq++){
106273       int j = pProbe->aiColumn[pc.plan.nEq];
106274       pTerm = findTerm(pWC, iCur, j, p->notReady, eqTermMask, pIdx);
106275       if( pTerm==0 ) break;
106276       pc.plan.wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
106277       testcase( pTerm->pWC!=pWC );
106278       if( pTerm->eOperator & WO_IN ){
106279         Expr *pExpr = pTerm->pExpr;
106280         pc.plan.wsFlags |= WHERE_COLUMN_IN;
106281         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
106282           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
106283           nInMul *= 25;
106284           bInEst = 1;
106285         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
106286           /* "x IN (value, value, ...)" */
106287           nInMul *= pExpr->x.pList->nExpr;
106288         }
106289       }else if( pTerm->eOperator & WO_ISNULL ){
106290         pc.plan.wsFlags |= WHERE_COLUMN_NULL;
106291       }
106292 #ifdef SQLITE_ENABLE_STAT3
106293       if( pc.plan.nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
106294 #endif
106295       pc.used |= pTerm->prereqRight;
106296     }
106297  
106298     /* If the index being considered is UNIQUE, and there is an equality 
106299     ** constraint for all columns in the index, then this search will find
106300     ** at most a single row. In this case set the WHERE_UNIQUE flag to 
106301     ** indicate this to the caller.
106302     **
106303     ** Otherwise, if the search may find more than one row, test to see if
106304     ** there is a range constraint on indexed column (pc.plan.nEq+1) that
106305     ** can be optimized using the index. 
106306     */
106307     if( pc.plan.nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
106308       testcase( pc.plan.wsFlags & WHERE_COLUMN_IN );
106309       testcase( pc.plan.wsFlags & WHERE_COLUMN_NULL );
106310       if( (pc.plan.wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
106311         pc.plan.wsFlags |= WHERE_UNIQUE;
106312         if( p->i==0 || (p->aLevel[p->i-1].plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
106313           pc.plan.wsFlags |= WHERE_ALL_UNIQUE;
106314         }
106315       }
106316     }else if( pProbe->bUnordered==0 ){
106317       int j;
106318       j = (pc.plan.nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[pc.plan.nEq]);
106319       if( findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
106320         WhereTerm *pTop, *pBtm;
106321         pTop = findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE, pIdx);
106322         pBtm = findTerm(pWC, iCur, j, p->notReady, WO_GT|WO_GE, pIdx);
106323         whereRangeScanEst(pParse, pProbe, pc.plan.nEq, pBtm, pTop, &rangeDiv);
106324         if( pTop ){
106325           nBound = 1;
106326           pc.plan.wsFlags |= WHERE_TOP_LIMIT;
106327           pc.used |= pTop->prereqRight;
106328           testcase( pTop->pWC!=pWC );
106329         }
106330         if( pBtm ){
106331           nBound++;
106332           pc.plan.wsFlags |= WHERE_BTM_LIMIT;
106333           pc.used |= pBtm->prereqRight;
106334           testcase( pBtm->pWC!=pWC );
106335         }
106336         pc.plan.wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
106337       }
106338     }
106339
106340     /* If there is an ORDER BY clause and the index being considered will
106341     ** naturally scan rows in the required order, set the appropriate flags
106342     ** in pc.plan.wsFlags. Otherwise, if there is an ORDER BY clause but
106343     ** the index will scan rows in a different order, set the bSort
106344     ** variable.  */
106345     if( bSort && (pSrc->jointype & JT_LEFT)==0 ){
106346       int bRev = 2;
106347       int bObUnique = 0;
106348       WHERETRACE(("      --> before isSortIndex: nPriorSat=%d\n",nPriorSat));
106349       pc.plan.nOBSat = isSortingIndex(p, pProbe, iCur, &bRev, &bObUnique);
106350       WHERETRACE(("      --> after  isSortIndex: bRev=%d bObU=%d nOBSat=%d\n",
106351                   bRev, bObUnique, pc.plan.nOBSat));
106352       if( nPriorSat<pc.plan.nOBSat || (pc.plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
106353         pc.plan.wsFlags |= WHERE_ORDERED;
106354         if( bObUnique ) pc.plan.wsFlags |= WHERE_OB_UNIQUE;
106355       }
106356       if( nOrderBy==pc.plan.nOBSat ){
106357         bSort = 0;
106358         pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE;
106359       }
106360       if( bRev & 1 ) pc.plan.wsFlags |= WHERE_REVERSE;
106361     }
106362
106363     /* If there is a DISTINCT qualifier and this index will scan rows in
106364     ** order of the DISTINCT expressions, clear bDist and set the appropriate
106365     ** flags in pc.plan.wsFlags. */
106366     if( bDist
106367      && isDistinctIndex(pParse, pWC, pProbe, iCur, p->pDistinct, pc.plan.nEq)
106368      && (pc.plan.wsFlags & WHERE_COLUMN_IN)==0
106369     ){
106370       bDist = 0;
106371       pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
106372     }
106373
106374     /* If currently calculating the cost of using an index (not the IPK
106375     ** index), determine if all required column data may be obtained without 
106376     ** using the main table (i.e. if the index is a covering
106377     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
106378     ** pc.plan.wsFlags. Otherwise, set the bLookup variable to true.  */
106379     if( pIdx ){
106380       Bitmask m = pSrc->colUsed;
106381       int j;
106382       for(j=0; j<pIdx->nColumn; j++){
106383         int x = pIdx->aiColumn[j];
106384         if( x<BMS-1 ){
106385           m &= ~(((Bitmask)1)<<x);
106386         }
106387       }
106388       if( m==0 ){
106389         pc.plan.wsFlags |= WHERE_IDX_ONLY;
106390       }else{
106391         bLookup = 1;
106392       }
106393     }
106394
106395     /*
106396     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
106397     ** constraint, do not let the estimate exceed half the rows in the table.
106398     */
106399     pc.plan.nRow = (double)(aiRowEst[pc.plan.nEq] * nInMul);
106400     if( bInEst && pc.plan.nRow*2>aiRowEst[0] ){
106401       pc.plan.nRow = aiRowEst[0]/2;
106402       nInMul = (int)(pc.plan.nRow / aiRowEst[pc.plan.nEq]);
106403     }
106404
106405 #ifdef SQLITE_ENABLE_STAT3
106406     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
106407     ** and we do not think that values of x are unique and if histogram
106408     ** data is available for column x, then it might be possible
106409     ** to get a better estimate on the number of rows based on
106410     ** VALUE and how common that value is according to the histogram.
106411     */
106412     if( pc.plan.nRow>(double)1 && pc.plan.nEq==1
106413      && pFirstTerm!=0 && aiRowEst[1]>1 ){
106414       assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
106415       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
106416         testcase( pFirstTerm->eOperator & WO_EQ );
106417         testcase( pFirstTerm->eOperator & WO_EQUIV );
106418         testcase( pFirstTerm->eOperator & WO_ISNULL );
106419         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight,
106420                           &pc.plan.nRow);
106421       }else if( bInEst==0 ){
106422         assert( pFirstTerm->eOperator & WO_IN );
106423         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList,
106424                        &pc.plan.nRow);
106425       }
106426     }
106427 #endif /* SQLITE_ENABLE_STAT3 */
106428
106429     /* Adjust the number of output rows and downward to reflect rows
106430     ** that are excluded by range constraints.
106431     */
106432     pc.plan.nRow = pc.plan.nRow/rangeDiv;
106433     if( pc.plan.nRow<1 ) pc.plan.nRow = 1;
106434
106435     /* Experiments run on real SQLite databases show that the time needed
106436     ** to do a binary search to locate a row in a table or index is roughly
106437     ** log10(N) times the time to move from one row to the next row within
106438     ** a table or index.  The actual times can vary, with the size of
106439     ** records being an important factor.  Both moves and searches are
106440     ** slower with larger records, presumably because fewer records fit
106441     ** on one page and hence more pages have to be fetched.
106442     **
106443     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
106444     ** not give us data on the relative sizes of table and index records.
106445     ** So this computation assumes table records are about twice as big
106446     ** as index records
106447     */
106448     if( (pc.plan.wsFlags&~(WHERE_REVERSE|WHERE_ORDERED|WHERE_OB_UNIQUE))
106449                                                               ==WHERE_IDX_ONLY
106450      && (pWC->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
106451      && sqlite3GlobalConfig.bUseCis
106452      && OptimizationEnabled(pParse->db, SQLITE_CoverIdxScan)
106453     ){
106454       /* This index is not useful for indexing, but it is a covering index.
106455       ** A full-scan of the index might be a little faster than a full-scan
106456       ** of the table, so give this case a cost slightly less than a table
106457       ** scan. */
106458       pc.rCost = aiRowEst[0]*3 + pProbe->nColumn;
106459       pc.plan.wsFlags |= WHERE_COVER_SCAN|WHERE_COLUMN_RANGE;
106460     }else if( (pc.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
106461       /* The cost of a full table scan is a number of move operations equal
106462       ** to the number of rows in the table.
106463       **
106464       ** We add an additional 4x penalty to full table scans.  This causes
106465       ** the cost function to err on the side of choosing an index over
106466       ** choosing a full scan.  This 4x full-scan penalty is an arguable
106467       ** decision and one which we expect to revisit in the future.  But
106468       ** it seems to be working well enough at the moment.
106469       */
106470       pc.rCost = aiRowEst[0]*4;
106471       pc.plan.wsFlags &= ~WHERE_IDX_ONLY;
106472       if( pIdx ){
106473         pc.plan.wsFlags &= ~WHERE_ORDERED;
106474         pc.plan.nOBSat = nPriorSat;
106475       }
106476     }else{
106477       log10N = estLog(aiRowEst[0]);
106478       pc.rCost = pc.plan.nRow;
106479       if( pIdx ){
106480         if( bLookup ){
106481           /* For an index lookup followed by a table lookup:
106482           **    nInMul index searches to find the start of each index range
106483           **  + nRow steps through the index
106484           **  + nRow table searches to lookup the table entry using the rowid
106485           */
106486           pc.rCost += (nInMul + pc.plan.nRow)*log10N;
106487         }else{
106488           /* For a covering index:
106489           **     nInMul index searches to find the initial entry 
106490           **   + nRow steps through the index
106491           */
106492           pc.rCost += nInMul*log10N;
106493         }
106494       }else{
106495         /* For a rowid primary key lookup:
106496         **    nInMult table searches to find the initial entry for each range
106497         **  + nRow steps through the table
106498         */
106499         pc.rCost += nInMul*log10N;
106500       }
106501     }
106502
106503     /* Add in the estimated cost of sorting the result.  Actual experimental
106504     ** measurements of sorting performance in SQLite show that sorting time
106505     ** adds C*N*log10(N) to the cost, where N is the number of rows to be 
106506     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
106507     ** difference and select C of 3.0.
106508     */
106509     if( bSort ){
106510       double m = estLog(pc.plan.nRow*(nOrderBy - pc.plan.nOBSat)/nOrderBy);
106511       m *= (double)(pc.plan.nOBSat ? 2 : 3);
106512       pc.rCost += pc.plan.nRow*m;
106513     }
106514     if( bDist ){
106515       pc.rCost += pc.plan.nRow*estLog(pc.plan.nRow)*3;
106516     }
106517
106518     /**** Cost of using this index has now been computed ****/
106519
106520     /* If there are additional constraints on this table that cannot
106521     ** be used with the current index, but which might lower the number
106522     ** of output rows, adjust the nRow value accordingly.  This only 
106523     ** matters if the current index is the least costly, so do not bother
106524     ** with this step if we already know this index will not be chosen.
106525     ** Also, never reduce the output row count below 2 using this step.
106526     **
106527     ** It is critical that the notValid mask be used here instead of
106528     ** the notReady mask.  When computing an "optimal" index, the notReady
106529     ** mask will only have one bit set - the bit for the current table.
106530     ** The notValid mask, on the other hand, always has all bits set for
106531     ** tables that are not in outer loops.  If notReady is used here instead
106532     ** of notValid, then a optimal index that depends on inner joins loops
106533     ** might be selected even when there exists an optimal index that has
106534     ** no such dependency.
106535     */
106536     if( pc.plan.nRow>2 && pc.rCost<=p->cost.rCost ){
106537       int k;                       /* Loop counter */
106538       int nSkipEq = pc.plan.nEq;   /* Number of == constraints to skip */
106539       int nSkipRange = nBound;     /* Number of < constraints to skip */
106540       Bitmask thisTab;             /* Bitmap for pSrc */
106541
106542       thisTab = getMask(pWC->pMaskSet, iCur);
106543       for(pTerm=pWC->a, k=pWC->nTerm; pc.plan.nRow>2 && k; k--, pTerm++){
106544         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
106545         if( (pTerm->prereqAll & p->notValid)!=thisTab ) continue;
106546         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
106547           if( nSkipEq ){
106548             /* Ignore the first pc.plan.nEq equality matches since the index
106549             ** has already accounted for these */
106550             nSkipEq--;
106551           }else{
106552             /* Assume each additional equality match reduces the result
106553             ** set size by a factor of 10 */
106554             pc.plan.nRow /= 10;
106555           }
106556         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
106557           if( nSkipRange ){
106558             /* Ignore the first nSkipRange range constraints since the index
106559             ** has already accounted for these */
106560             nSkipRange--;
106561           }else{
106562             /* Assume each additional range constraint reduces the result
106563             ** set size by a factor of 3.  Indexed range constraints reduce
106564             ** the search space by a larger factor: 4.  We make indexed range
106565             ** more selective intentionally because of the subjective 
106566             ** observation that indexed range constraints really are more
106567             ** selective in practice, on average. */
106568             pc.plan.nRow /= 3;
106569           }
106570         }else if( (pTerm->eOperator & WO_NOOP)==0 ){
106571           /* Any other expression lowers the output row count by half */
106572           pc.plan.nRow /= 2;
106573         }
106574       }
106575       if( pc.plan.nRow<2 ) pc.plan.nRow = 2;
106576     }
106577
106578
106579     WHERETRACE((
106580       "      nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%08x\n"
106581       "      notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f\n"
106582       "      used=0x%llx nOBSat=%d\n",
106583       pc.plan.nEq, nInMul, (int)rangeDiv, bSort, bLookup, pc.plan.wsFlags,
106584       p->notReady, log10N, pc.plan.nRow, pc.rCost, pc.used,
106585       pc.plan.nOBSat
106586     ));
106587
106588     /* If this index is the best we have seen so far, then record this
106589     ** index and its cost in the p->cost structure.
106590     */
106591     if( (!pIdx || pc.plan.wsFlags) && compareCost(&pc, &p->cost) ){
106592       p->cost = pc;
106593       p->cost.plan.wsFlags &= wsFlagMask;
106594       p->cost.plan.u.pIdx = pIdx;
106595     }
106596
106597     /* If there was an INDEXED BY clause, then only that one index is
106598     ** considered. */
106599     if( pSrc->pIndex ) break;
106600
106601     /* Reset masks for the next index in the loop */
106602     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
106603     eqTermMask = idxEqTermMask;
106604   }
106605
106606   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
106607   ** is set, then reverse the order that the index will be scanned
106608   ** in. This is used for application testing, to help find cases
106609   ** where application behavior depends on the (undefined) order that
106610   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
106611   if( !p->pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
106612     p->cost.plan.wsFlags |= WHERE_REVERSE;
106613   }
106614
106615   assert( p->pOrderBy || (p->cost.plan.wsFlags&WHERE_ORDERED)==0 );
106616   assert( p->cost.plan.u.pIdx==0 || (p->cost.plan.wsFlags&WHERE_ROWID_EQ)==0 );
106617   assert( pSrc->pIndex==0 
106618        || p->cost.plan.u.pIdx==0 
106619        || p->cost.plan.u.pIdx==pSrc->pIndex 
106620   );
106621
106622   WHERETRACE(("   best index is %s cost=%.1f\n",
106623          p->cost.plan.u.pIdx ? p->cost.plan.u.pIdx->zName : "ipk",
106624          p->cost.rCost));
106625   
106626   bestOrClauseIndex(p);
106627   bestAutomaticIndex(p);
106628   p->cost.plan.wsFlags |= eqTermMask;
106629 }
106630
106631 /*
106632 ** Find the query plan for accessing table pSrc->pTab. Write the
106633 ** best query plan and its cost into the WhereCost object supplied 
106634 ** as the last parameter. This function may calculate the cost of
106635 ** both real and virtual table scans.
106636 **
106637 ** This function does not take ORDER BY or DISTINCT into account.  Nor
106638 ** does it remember the virtual table query plan.  All it does is compute
106639 ** the cost while determining if an OR optimization is applicable.  The
106640 ** details will be reconsidered later if the optimization is found to be
106641 ** applicable.
106642 */
106643 static void bestIndex(WhereBestIdx *p){
106644 #ifndef SQLITE_OMIT_VIRTUALTABLE
106645   if( IsVirtual(p->pSrc->pTab) ){
106646     sqlite3_index_info *pIdxInfo = 0;
106647     p->ppIdxInfo = &pIdxInfo;
106648     bestVirtualIndex(p);
106649     assert( pIdxInfo!=0 || p->pParse->db->mallocFailed );
106650     if( pIdxInfo && pIdxInfo->needToFreeIdxStr ){
106651       sqlite3_free(pIdxInfo->idxStr);
106652     }
106653     sqlite3DbFree(p->pParse->db, pIdxInfo);
106654   }else
106655 #endif
106656   {
106657     bestBtreeIndex(p);
106658   }
106659 }
106660
106661 /*
106662 ** Disable a term in the WHERE clause.  Except, do not disable the term
106663 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
106664 ** or USING clause of that join.
106665 **
106666 ** Consider the term t2.z='ok' in the following queries:
106667 **
106668 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
106669 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
106670 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
106671 **
106672 ** The t2.z='ok' is disabled in the in (2) because it originates
106673 ** in the ON clause.  The term is disabled in (3) because it is not part
106674 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
106675 **
106676 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
106677 ** completely satisfied by indices.
106678 **
106679 ** Disabling a term causes that term to not be tested in the inner loop
106680 ** of the join.  Disabling is an optimization.  When terms are satisfied
106681 ** by indices, we disable them to prevent redundant tests in the inner
106682 ** loop.  We would get the correct results if nothing were ever disabled,
106683 ** but joins might run a little slower.  The trick is to disable as much
106684 ** as we can without disabling too much.  If we disabled in (1), we'd get
106685 ** the wrong answer.  See ticket #813.
106686 */
106687 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
106688   if( pTerm
106689       && (pTerm->wtFlags & TERM_CODED)==0
106690       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
106691   ){
106692     pTerm->wtFlags |= TERM_CODED;
106693     if( pTerm->iParent>=0 ){
106694       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
106695       if( (--pOther->nChild)==0 ){
106696         disableTerm(pLevel, pOther);
106697       }
106698     }
106699   }
106700 }
106701
106702 /*
106703 ** Code an OP_Affinity opcode to apply the column affinity string zAff
106704 ** to the n registers starting at base. 
106705 **
106706 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
106707 ** beginning and end of zAff are ignored.  If all entries in zAff are
106708 ** SQLITE_AFF_NONE, then no code gets generated.
106709 **
106710 ** This routine makes its own copy of zAff so that the caller is free
106711 ** to modify zAff after this routine returns.
106712 */
106713 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
106714   Vdbe *v = pParse->pVdbe;
106715   if( zAff==0 ){
106716     assert( pParse->db->mallocFailed );
106717     return;
106718   }
106719   assert( v!=0 );
106720
106721   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
106722   ** and end of the affinity string.
106723   */
106724   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
106725     n--;
106726     base++;
106727     zAff++;
106728   }
106729   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
106730     n--;
106731   }
106732
106733   /* Code the OP_Affinity opcode if there is anything left to do. */
106734   if( n>0 ){
106735     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
106736     sqlite3VdbeChangeP4(v, -1, zAff, n);
106737     sqlite3ExprCacheAffinityChange(pParse, base, n);
106738   }
106739 }
106740
106741
106742 /*
106743 ** Generate code for a single equality term of the WHERE clause.  An equality
106744 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
106745 ** coded.
106746 **
106747 ** The current value for the constraint is left in register iReg.
106748 **
106749 ** For a constraint of the form X=expr, the expression is evaluated and its
106750 ** result is left on the stack.  For constraints of the form X IN (...)
106751 ** this routine sets up a loop that will iterate over all values of X.
106752 */
106753 static int codeEqualityTerm(
106754   Parse *pParse,      /* The parsing context */
106755   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
106756   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
106757   int iEq,            /* Index of the equality term within this level */
106758   int iTarget         /* Attempt to leave results in this register */
106759 ){
106760   Expr *pX = pTerm->pExpr;
106761   Vdbe *v = pParse->pVdbe;
106762   int iReg;                  /* Register holding results */
106763
106764   assert( iTarget>0 );
106765   if( pX->op==TK_EQ ){
106766     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
106767   }else if( pX->op==TK_ISNULL ){
106768     iReg = iTarget;
106769     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
106770 #ifndef SQLITE_OMIT_SUBQUERY
106771   }else{
106772     int eType;
106773     int iTab;
106774     struct InLoop *pIn;
106775     u8 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
106776
106777     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 
106778       && pLevel->plan.u.pIdx->aSortOrder[iEq]
106779     ){
106780       testcase( iEq==0 );
106781       testcase( iEq==pLevel->plan.u.pIdx->nColumn-1 );
106782       testcase( iEq>0 && iEq+1<pLevel->plan.u.pIdx->nColumn );
106783       testcase( bRev );
106784       bRev = !bRev;
106785     }
106786     assert( pX->op==TK_IN );
106787     iReg = iTarget;
106788     eType = sqlite3FindInIndex(pParse, pX, 0);
106789     if( eType==IN_INDEX_INDEX_DESC ){
106790       testcase( bRev );
106791       bRev = !bRev;
106792     }
106793     iTab = pX->iTable;
106794     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
106795     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
106796     if( pLevel->u.in.nIn==0 ){
106797       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
106798     }
106799     pLevel->u.in.nIn++;
106800     pLevel->u.in.aInLoop =
106801        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
106802                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
106803     pIn = pLevel->u.in.aInLoop;
106804     if( pIn ){
106805       pIn += pLevel->u.in.nIn - 1;
106806       pIn->iCur = iTab;
106807       if( eType==IN_INDEX_ROWID ){
106808         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
106809       }else{
106810         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
106811       }
106812       pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
106813       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
106814     }else{
106815       pLevel->u.in.nIn = 0;
106816     }
106817 #endif
106818   }
106819   disableTerm(pLevel, pTerm);
106820   return iReg;
106821 }
106822
106823 /*
106824 ** Generate code that will evaluate all == and IN constraints for an
106825 ** index.
106826 **
106827 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
106828 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
106829 ** The index has as many as three equality constraints, but in this
106830 ** example, the third "c" value is an inequality.  So only two 
106831 ** constraints are coded.  This routine will generate code to evaluate
106832 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
106833 ** in consecutive registers and the index of the first register is returned.
106834 **
106835 ** In the example above nEq==2.  But this subroutine works for any value
106836 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
106837 ** The only thing it does is allocate the pLevel->iMem memory cell and
106838 ** compute the affinity string.
106839 **
106840 ** This routine always allocates at least one memory cell and returns
106841 ** the index of that memory cell. The code that
106842 ** calls this routine will use that memory cell to store the termination
106843 ** key value of the loop.  If one or more IN operators appear, then
106844 ** this routine allocates an additional nEq memory cells for internal
106845 ** use.
106846 **
106847 ** Before returning, *pzAff is set to point to a buffer containing a
106848 ** copy of the column affinity string of the index allocated using
106849 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
106850 ** with equality constraints that use NONE affinity are set to
106851 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
106852 **
106853 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
106854 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
106855 **
106856 ** In the example above, the index on t1(a) has TEXT affinity. But since
106857 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
106858 ** no conversion should be attempted before using a t2.b value as part of
106859 ** a key to search the index. Hence the first byte in the returned affinity
106860 ** string in this example would be set to SQLITE_AFF_NONE.
106861 */
106862 static int codeAllEqualityTerms(
106863   Parse *pParse,        /* Parsing context */
106864   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
106865   WhereClause *pWC,     /* The WHERE clause */
106866   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
106867   int nExtraReg,        /* Number of extra registers to allocate */
106868   char **pzAff          /* OUT: Set to point to affinity string */
106869 ){
106870   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
106871   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
106872   Index *pIdx;                  /* The index being used for this loop */
106873   int iCur = pLevel->iTabCur;   /* The cursor of the table */
106874   WhereTerm *pTerm;             /* A single constraint term */
106875   int j;                        /* Loop counter */
106876   int regBase;                  /* Base register */
106877   int nReg;                     /* Number of registers to allocate */
106878   char *zAff;                   /* Affinity string to return */
106879
106880   /* This module is only called on query plans that use an index. */
106881   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
106882   pIdx = pLevel->plan.u.pIdx;
106883
106884   /* Figure out how many memory cells we will need then allocate them.
106885   */
106886   regBase = pParse->nMem + 1;
106887   nReg = pLevel->plan.nEq + nExtraReg;
106888   pParse->nMem += nReg;
106889
106890   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
106891   if( !zAff ){
106892     pParse->db->mallocFailed = 1;
106893   }
106894
106895   /* Evaluate the equality constraints
106896   */
106897   assert( pIdx->nColumn>=nEq );
106898   for(j=0; j<nEq; j++){
106899     int r1;
106900     int k = pIdx->aiColumn[j];
106901     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
106902     if( pTerm==0 ) break;
106903     /* The following true for indices with redundant columns. 
106904     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
106905     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
106906     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106907     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, regBase+j);
106908     if( r1!=regBase+j ){
106909       if( nReg==1 ){
106910         sqlite3ReleaseTempReg(pParse, regBase);
106911         regBase = r1;
106912       }else{
106913         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
106914       }
106915     }
106916     testcase( pTerm->eOperator & WO_ISNULL );
106917     testcase( pTerm->eOperator & WO_IN );
106918     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
106919       Expr *pRight = pTerm->pExpr->pRight;
106920       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
106921       if( zAff ){
106922         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
106923           zAff[j] = SQLITE_AFF_NONE;
106924         }
106925         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
106926           zAff[j] = SQLITE_AFF_NONE;
106927         }
106928       }
106929     }
106930   }
106931   *pzAff = zAff;
106932   return regBase;
106933 }
106934
106935 #ifndef SQLITE_OMIT_EXPLAIN
106936 /*
106937 ** This routine is a helper for explainIndexRange() below
106938 **
106939 ** pStr holds the text of an expression that we are building up one term
106940 ** at a time.  This routine adds a new term to the end of the expression.
106941 ** Terms are separated by AND so add the "AND" text for second and subsequent
106942 ** terms only.
106943 */
106944 static void explainAppendTerm(
106945   StrAccum *pStr,             /* The text expression being built */
106946   int iTerm,                  /* Index of this term.  First is zero */
106947   const char *zColumn,        /* Name of the column */
106948   const char *zOp             /* Name of the operator */
106949 ){
106950   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
106951   sqlite3StrAccumAppend(pStr, zColumn, -1);
106952   sqlite3StrAccumAppend(pStr, zOp, 1);
106953   sqlite3StrAccumAppend(pStr, "?", 1);
106954 }
106955
106956 /*
106957 ** Argument pLevel describes a strategy for scanning table pTab. This 
106958 ** function returns a pointer to a string buffer containing a description
106959 ** of the subset of table rows scanned by the strategy in the form of an
106960 ** SQL expression. Or, if all rows are scanned, NULL is returned.
106961 **
106962 ** For example, if the query:
106963 **
106964 **   SELECT * FROM t1 WHERE a=1 AND b>2;
106965 **
106966 ** is run and there is an index on (a, b), then this function returns a
106967 ** string similar to:
106968 **
106969 **   "a=? AND b>?"
106970 **
106971 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
106972 ** It is the responsibility of the caller to free the buffer when it is
106973 ** no longer required.
106974 */
106975 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
106976   WherePlan *pPlan = &pLevel->plan;
106977   Index *pIndex = pPlan->u.pIdx;
106978   int nEq = pPlan->nEq;
106979   int i, j;
106980   Column *aCol = pTab->aCol;
106981   int *aiColumn = pIndex->aiColumn;
106982   StrAccum txt;
106983
106984   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
106985     return 0;
106986   }
106987   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
106988   txt.db = db;
106989   sqlite3StrAccumAppend(&txt, " (", 2);
106990   for(i=0; i<nEq; i++){
106991     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
106992   }
106993
106994   j = i;
106995   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
106996     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
106997     explainAppendTerm(&txt, i++, z, ">");
106998   }
106999   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
107000     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
107001     explainAppendTerm(&txt, i, z, "<");
107002   }
107003   sqlite3StrAccumAppend(&txt, ")", 1);
107004   return sqlite3StrAccumFinish(&txt);
107005 }
107006
107007 /*
107008 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
107009 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
107010 ** record is added to the output to describe the table scan strategy in 
107011 ** pLevel.
107012 */
107013 static void explainOneScan(
107014   Parse *pParse,                  /* Parse context */
107015   SrcList *pTabList,              /* Table list this loop refers to */
107016   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
107017   int iLevel,                     /* Value for "level" column of output */
107018   int iFrom,                      /* Value for "from" column of output */
107019   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
107020 ){
107021   if( pParse->explain==2 ){
107022     u32 flags = pLevel->plan.wsFlags;
107023     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
107024     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
107025     sqlite3 *db = pParse->db;     /* Database handle */
107026     char *zMsg;                   /* Text to add to EQP output */
107027     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
107028     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
107029     int isSearch;                 /* True for a SEARCH. False for SCAN. */
107030
107031     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
107032
107033     isSearch = (pLevel->plan.nEq>0)
107034              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
107035              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
107036
107037     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
107038     if( pItem->pSelect ){
107039       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
107040     }else{
107041       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
107042     }
107043
107044     if( pItem->zAlias ){
107045       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
107046     }
107047     if( (flags & WHERE_INDEXED)!=0 ){
107048       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
107049       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg, 
107050           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
107051           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
107052           ((flags & WHERE_TEMP_INDEX)?"":" "),
107053           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
107054           zWhere
107055       );
107056       sqlite3DbFree(db, zWhere);
107057     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
107058       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
107059
107060       if( flags&WHERE_ROWID_EQ ){
107061         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
107062       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
107063         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
107064       }else if( flags&WHERE_BTM_LIMIT ){
107065         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
107066       }else if( flags&WHERE_TOP_LIMIT ){
107067         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
107068       }
107069     }
107070 #ifndef SQLITE_OMIT_VIRTUALTABLE
107071     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
107072       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
107073       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
107074                   pVtabIdx->idxNum, pVtabIdx->idxStr);
107075     }
107076 #endif
107077     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
107078       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
107079       nRow = 1;
107080     }else{
107081       nRow = (sqlite3_int64)pLevel->plan.nRow;
107082     }
107083     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
107084     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
107085   }
107086 }
107087 #else
107088 # define explainOneScan(u,v,w,x,y,z)
107089 #endif /* SQLITE_OMIT_EXPLAIN */
107090
107091
107092 /*
107093 ** Generate code for the start of the iLevel-th loop in the WHERE clause
107094 ** implementation described by pWInfo.
107095 */
107096 static Bitmask codeOneLoopStart(
107097   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
107098   int iLevel,          /* Which level of pWInfo->a[] should be coded */
107099   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
107100   Bitmask notReady     /* Which tables are currently available */
107101 ){
107102   int j, k;            /* Loop counters */
107103   int iCur;            /* The VDBE cursor for the table */
107104   int addrNxt;         /* Where to jump to continue with the next IN case */
107105   int omitTable;       /* True if we use the index only */
107106   int bRev;            /* True if we need to scan in reverse order */
107107   WhereLevel *pLevel;  /* The where level to be coded */
107108   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
107109   WhereTerm *pTerm;               /* A WHERE clause term */
107110   Parse *pParse;                  /* Parsing context */
107111   Vdbe *v;                        /* The prepared stmt under constructions */
107112   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
107113   int addrBrk;                    /* Jump here to break out of the loop */
107114   int addrCont;                   /* Jump here to continue with next cycle */
107115   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
107116   int iReleaseReg = 0;      /* Temp register to free before returning */
107117
107118   pParse = pWInfo->pParse;
107119   v = pParse->pVdbe;
107120   pWC = pWInfo->pWC;
107121   pLevel = &pWInfo->a[iLevel];
107122   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
107123   iCur = pTabItem->iCursor;
107124   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
107125   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
107126            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
107127
107128   /* Create labels for the "break" and "continue" instructions
107129   ** for the current loop.  Jump to addrBrk to break out of a loop.
107130   ** Jump to cont to go immediately to the next iteration of the
107131   ** loop.
107132   **
107133   ** When there is an IN operator, we also have a "addrNxt" label that
107134   ** means to continue with the next IN value combination.  When
107135   ** there are no IN operators in the constraints, the "addrNxt" label
107136   ** is the same as "addrBrk".
107137   */
107138   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
107139   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
107140
107141   /* If this is the right table of a LEFT OUTER JOIN, allocate and
107142   ** initialize a memory cell that records if this table matches any
107143   ** row of the left table of the join.
107144   */
107145   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
107146     pLevel->iLeftJoin = ++pParse->nMem;
107147     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
107148     VdbeComment((v, "init LEFT JOIN no-match flag"));
107149   }
107150
107151   /* Special case of a FROM clause subquery implemented as a co-routine */
107152   if( pTabItem->viaCoroutine ){
107153     int regYield = pTabItem->regReturn;
107154     sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
107155     pLevel->p2 =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
107156     VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
107157     sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
107158     pLevel->op = OP_Goto;
107159   }else
107160
107161 #ifndef SQLITE_OMIT_VIRTUALTABLE
107162   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
107163     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
107164     **          to access the data.
107165     */
107166     int iReg;   /* P3 Value for OP_VFilter */
107167     int addrNotFound;
107168     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
107169     int nConstraint = pVtabIdx->nConstraint;
107170     struct sqlite3_index_constraint_usage *aUsage =
107171                                                 pVtabIdx->aConstraintUsage;
107172     const struct sqlite3_index_constraint *aConstraint =
107173                                                 pVtabIdx->aConstraint;
107174
107175     sqlite3ExprCachePush(pParse);
107176     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
107177     addrNotFound = pLevel->addrBrk;
107178     for(j=1; j<=nConstraint; j++){
107179       for(k=0; k<nConstraint; k++){
107180         if( aUsage[k].argvIndex==j ){
107181           int iTarget = iReg+j+1;
107182           pTerm = &pWC->a[aConstraint[k].iTermOffset];
107183           if( pTerm->eOperator & WO_IN ){
107184             codeEqualityTerm(pParse, pTerm, pLevel, k, iTarget);
107185             addrNotFound = pLevel->addrNxt;
107186           }else{
107187             sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
107188           }
107189           break;
107190         }
107191       }
107192       if( k==nConstraint ) break;
107193     }
107194     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
107195     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
107196     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pVtabIdx->idxStr,
107197                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
107198     pVtabIdx->needToFreeIdxStr = 0;
107199     for(j=0; j<nConstraint; j++){
107200       if( aUsage[j].omit ){
107201         int iTerm = aConstraint[j].iTermOffset;
107202         disableTerm(pLevel, &pWC->a[iTerm]);
107203       }
107204     }
107205     pLevel->op = OP_VNext;
107206     pLevel->p1 = iCur;
107207     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
107208     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
107209     sqlite3ExprCachePop(pParse, 1);
107210   }else
107211 #endif /* SQLITE_OMIT_VIRTUALTABLE */
107212
107213   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
107214     /* Case 1:  We can directly reference a single row using an
107215     **          equality comparison against the ROWID field.  Or
107216     **          we reference multiple rows using a "rowid IN (...)"
107217     **          construct.
107218     */
107219     iReleaseReg = sqlite3GetTempReg(pParse);
107220     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
107221     assert( pTerm!=0 );
107222     assert( pTerm->pExpr!=0 );
107223     assert( omitTable==0 );
107224     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107225     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, iReleaseReg);
107226     addrNxt = pLevel->addrNxt;
107227     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
107228     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
107229     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
107230     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107231     VdbeComment((v, "pk"));
107232     pLevel->op = OP_Noop;
107233   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
107234     /* Case 2:  We have an inequality comparison against the ROWID field.
107235     */
107236     int testOp = OP_Noop;
107237     int start;
107238     int memEndValue = 0;
107239     WhereTerm *pStart, *pEnd;
107240
107241     assert( omitTable==0 );
107242     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
107243     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
107244     if( bRev ){
107245       pTerm = pStart;
107246       pStart = pEnd;
107247       pEnd = pTerm;
107248     }
107249     if( pStart ){
107250       Expr *pX;             /* The expression that defines the start bound */
107251       int r1, rTemp;        /* Registers for holding the start boundary */
107252
107253       /* The following constant maps TK_xx codes into corresponding 
107254       ** seek opcodes.  It depends on a particular ordering of TK_xx
107255       */
107256       const u8 aMoveOp[] = {
107257            /* TK_GT */  OP_SeekGt,
107258            /* TK_LE */  OP_SeekLe,
107259            /* TK_LT */  OP_SeekLt,
107260            /* TK_GE */  OP_SeekGe
107261       };
107262       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
107263       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
107264       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
107265
107266       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107267       pX = pStart->pExpr;
107268       assert( pX!=0 );
107269       assert( pStart->leftCursor==iCur );
107270       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
107271       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
107272       VdbeComment((v, "pk"));
107273       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
107274       sqlite3ReleaseTempReg(pParse, rTemp);
107275       disableTerm(pLevel, pStart);
107276     }else{
107277       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
107278     }
107279     if( pEnd ){
107280       Expr *pX;
107281       pX = pEnd->pExpr;
107282       assert( pX!=0 );
107283       assert( pEnd->leftCursor==iCur );
107284       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107285       memEndValue = ++pParse->nMem;
107286       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
107287       if( pX->op==TK_LT || pX->op==TK_GT ){
107288         testOp = bRev ? OP_Le : OP_Ge;
107289       }else{
107290         testOp = bRev ? OP_Lt : OP_Gt;
107291       }
107292       disableTerm(pLevel, pEnd);
107293     }
107294     start = sqlite3VdbeCurrentAddr(v);
107295     pLevel->op = bRev ? OP_Prev : OP_Next;
107296     pLevel->p1 = iCur;
107297     pLevel->p2 = start;
107298     if( pStart==0 && pEnd==0 ){
107299       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
107300     }else{
107301       assert( pLevel->p5==0 );
107302     }
107303     if( testOp!=OP_Noop ){
107304       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
107305       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
107306       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107307       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
107308       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
107309     }
107310   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
107311     /* Case 3: A scan using an index.
107312     **
107313     **         The WHERE clause may contain zero or more equality 
107314     **         terms ("==" or "IN" operators) that refer to the N
107315     **         left-most columns of the index. It may also contain
107316     **         inequality constraints (>, <, >= or <=) on the indexed
107317     **         column that immediately follows the N equalities. Only 
107318     **         the right-most column can be an inequality - the rest must
107319     **         use the "==" and "IN" operators. For example, if the 
107320     **         index is on (x,y,z), then the following clauses are all 
107321     **         optimized:
107322     **
107323     **            x=5
107324     **            x=5 AND y=10
107325     **            x=5 AND y<10
107326     **            x=5 AND y>5 AND y<10
107327     **            x=5 AND y=5 AND z<=10
107328     **
107329     **         The z<10 term of the following cannot be used, only
107330     **         the x=5 term:
107331     **
107332     **            x=5 AND z<10
107333     **
107334     **         N may be zero if there are inequality constraints.
107335     **         If there are no inequality constraints, then N is at
107336     **         least one.
107337     **
107338     **         This case is also used when there are no WHERE clause
107339     **         constraints but an index is selected anyway, in order
107340     **         to force the output order to conform to an ORDER BY.
107341     */  
107342     static const u8 aStartOp[] = {
107343       0,
107344       0,
107345       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
107346       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
107347       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
107348       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
107349       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
107350       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
107351     };
107352     static const u8 aEndOp[] = {
107353       OP_Noop,             /* 0: (!end_constraints) */
107354       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
107355       OP_IdxLT             /* 2: (end_constraints && bRev) */
107356     };
107357     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
107358     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
107359     int regBase;                 /* Base register holding constraint values */
107360     int r1;                      /* Temp register */
107361     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
107362     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
107363     int startEq;                 /* True if range start uses ==, >= or <= */
107364     int endEq;                   /* True if range end uses ==, >= or <= */
107365     int start_constraints;       /* Start of range is constrained */
107366     int nConstraint;             /* Number of constraint terms */
107367     Index *pIdx;                 /* The index we will be using */
107368     int iIdxCur;                 /* The VDBE cursor for the index */
107369     int nExtraReg = 0;           /* Number of extra registers needed */
107370     int op;                      /* Instruction opcode */
107371     char *zStartAff;             /* Affinity for start of range constraint */
107372     char *zEndAff;               /* Affinity for end of range constraint */
107373
107374     pIdx = pLevel->plan.u.pIdx;
107375     iIdxCur = pLevel->iIdxCur;
107376     k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
107377
107378     /* If this loop satisfies a sort order (pOrderBy) request that 
107379     ** was passed to this function to implement a "SELECT min(x) ..." 
107380     ** query, then the caller will only allow the loop to run for
107381     ** a single iteration. This means that the first row returned
107382     ** should not have a NULL value stored in 'x'. If column 'x' is
107383     ** the first one after the nEq equality constraints in the index,
107384     ** this requires some special handling.
107385     */
107386     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
107387      && (pLevel->plan.wsFlags&WHERE_ORDERED)
107388      && (pIdx->nColumn>nEq)
107389     ){
107390       /* assert( pOrderBy->nExpr==1 ); */
107391       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
107392       isMinQuery = 1;
107393       nExtraReg = 1;
107394     }
107395
107396     /* Find any inequality constraint terms for the start and end 
107397     ** of the range. 
107398     */
107399     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
107400       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
107401       nExtraReg = 1;
107402     }
107403     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
107404       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
107405       nExtraReg = 1;
107406     }
107407
107408     /* Generate code to evaluate all constraint terms using == or IN
107409     ** and store the values of those terms in an array of registers
107410     ** starting at regBase.
107411     */
107412     regBase = codeAllEqualityTerms(
107413         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
107414     );
107415     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
107416     addrNxt = pLevel->addrNxt;
107417
107418     /* If we are doing a reverse order scan on an ascending index, or
107419     ** a forward order scan on a descending index, interchange the 
107420     ** start and end terms (pRangeStart and pRangeEnd).
107421     */
107422     if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
107423      || (bRev && pIdx->nColumn==nEq)
107424     ){
107425       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
107426     }
107427
107428     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
107429     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
107430     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
107431     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
107432     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
107433     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
107434     start_constraints = pRangeStart || nEq>0;
107435
107436     /* Seek the index cursor to the start of the range. */
107437     nConstraint = nEq;
107438     if( pRangeStart ){
107439       Expr *pRight = pRangeStart->pExpr->pRight;
107440       sqlite3ExprCode(pParse, pRight, regBase+nEq);
107441       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
107442         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
107443       }
107444       if( zStartAff ){
107445         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
107446           /* Since the comparison is to be performed with no conversions
107447           ** applied to the operands, set the affinity to apply to pRight to 
107448           ** SQLITE_AFF_NONE.  */
107449           zStartAff[nEq] = SQLITE_AFF_NONE;
107450         }
107451         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
107452           zStartAff[nEq] = SQLITE_AFF_NONE;
107453         }
107454       }  
107455       nConstraint++;
107456       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107457     }else if( isMinQuery ){
107458       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
107459       nConstraint++;
107460       startEq = 0;
107461       start_constraints = 1;
107462     }
107463     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
107464     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
107465     assert( op!=0 );
107466     testcase( op==OP_Rewind );
107467     testcase( op==OP_Last );
107468     testcase( op==OP_SeekGt );
107469     testcase( op==OP_SeekGe );
107470     testcase( op==OP_SeekLe );
107471     testcase( op==OP_SeekLt );
107472     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
107473
107474     /* Load the value for the inequality constraint at the end of the
107475     ** range (if any).
107476     */
107477     nConstraint = nEq;
107478     if( pRangeEnd ){
107479       Expr *pRight = pRangeEnd->pExpr->pRight;
107480       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
107481       sqlite3ExprCode(pParse, pRight, regBase+nEq);
107482       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
107483         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
107484       }
107485       if( zEndAff ){
107486         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
107487           /* Since the comparison is to be performed with no conversions
107488           ** applied to the operands, set the affinity to apply to pRight to 
107489           ** SQLITE_AFF_NONE.  */
107490           zEndAff[nEq] = SQLITE_AFF_NONE;
107491         }
107492         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
107493           zEndAff[nEq] = SQLITE_AFF_NONE;
107494         }
107495       }  
107496       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
107497       nConstraint++;
107498       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107499     }
107500     sqlite3DbFree(pParse->db, zStartAff);
107501     sqlite3DbFree(pParse->db, zEndAff);
107502
107503     /* Top of the loop body */
107504     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
107505
107506     /* Check if the index cursor is past the end of the range. */
107507     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
107508     testcase( op==OP_Noop );
107509     testcase( op==OP_IdxGE );
107510     testcase( op==OP_IdxLT );
107511     if( op!=OP_Noop ){
107512       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
107513       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
107514     }
107515
107516     /* If there are inequality constraints, check that the value
107517     ** of the table column that the inequality contrains is not NULL.
107518     ** If it is, jump to the next iteration of the loop.
107519     */
107520     r1 = sqlite3GetTempReg(pParse);
107521     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
107522     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
107523     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
107524       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
107525       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
107526     }
107527     sqlite3ReleaseTempReg(pParse, r1);
107528
107529     /* Seek the table cursor, if required */
107530     disableTerm(pLevel, pRangeStart);
107531     disableTerm(pLevel, pRangeEnd);
107532     if( !omitTable ){
107533       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
107534       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
107535       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107536       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
107537     }
107538
107539     /* Record the instruction used to terminate the loop. Disable 
107540     ** WHERE clause terms made redundant by the index range scan.
107541     */
107542     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
107543       pLevel->op = OP_Noop;
107544     }else if( bRev ){
107545       pLevel->op = OP_Prev;
107546     }else{
107547       pLevel->op = OP_Next;
107548     }
107549     pLevel->p1 = iIdxCur;
107550     if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
107551       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
107552     }else{
107553       assert( pLevel->p5==0 );
107554     }
107555   }else
107556
107557 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
107558   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
107559     /* Case 4:  Two or more separately indexed terms connected by OR
107560     **
107561     ** Example:
107562     **
107563     **   CREATE TABLE t1(a,b,c,d);
107564     **   CREATE INDEX i1 ON t1(a);
107565     **   CREATE INDEX i2 ON t1(b);
107566     **   CREATE INDEX i3 ON t1(c);
107567     **
107568     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
107569     **
107570     ** In the example, there are three indexed terms connected by OR.
107571     ** The top of the loop looks like this:
107572     **
107573     **          Null       1                # Zero the rowset in reg 1
107574     **
107575     ** Then, for each indexed term, the following. The arguments to
107576     ** RowSetTest are such that the rowid of the current row is inserted
107577     ** into the RowSet. If it is already present, control skips the
107578     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
107579     **
107580     **        sqlite3WhereBegin(<term>)
107581     **          RowSetTest                  # Insert rowid into rowset
107582     **          Gosub      2 A
107583     **        sqlite3WhereEnd()
107584     **
107585     ** Following the above, code to terminate the loop. Label A, the target
107586     ** of the Gosub above, jumps to the instruction right after the Goto.
107587     **
107588     **          Null       1                # Zero the rowset in reg 1
107589     **          Goto       B                # The loop is finished.
107590     **
107591     **       A: <loop body>                 # Return data, whatever.
107592     **
107593     **          Return     2                # Jump back to the Gosub
107594     **
107595     **       B: <after the loop>
107596     **
107597     */
107598     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
107599     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
107600     Index *pCov = 0;             /* Potential covering index (or NULL) */
107601     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
107602
107603     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
107604     int regRowset = 0;                        /* Register for RowSet object */
107605     int regRowid = 0;                         /* Register holding rowid */
107606     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
107607     int iRetInit;                             /* Address of regReturn init */
107608     int untestedTerms = 0;             /* Some terms not completely tested */
107609     int ii;                            /* Loop counter */
107610     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
107611    
107612     pTerm = pLevel->plan.u.pTerm;
107613     assert( pTerm!=0 );
107614     assert( pTerm->eOperator & WO_OR );
107615     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
107616     pOrWc = &pTerm->u.pOrInfo->wc;
107617     pLevel->op = OP_Return;
107618     pLevel->p1 = regReturn;
107619
107620     /* Set up a new SrcList in pOrTab containing the table being scanned
107621     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
107622     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
107623     */
107624     if( pWInfo->nLevel>1 ){
107625       int nNotReady;                 /* The number of notReady tables */
107626       struct SrcList_item *origSrc;     /* Original list of tables */
107627       nNotReady = pWInfo->nLevel - iLevel - 1;
107628       pOrTab = sqlite3StackAllocRaw(pParse->db,
107629                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
107630       if( pOrTab==0 ) return notReady;
107631       pOrTab->nAlloc = (i16)(nNotReady + 1);
107632       pOrTab->nSrc = pOrTab->nAlloc;
107633       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
107634       origSrc = pWInfo->pTabList->a;
107635       for(k=1; k<=nNotReady; k++){
107636         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
107637       }
107638     }else{
107639       pOrTab = pWInfo->pTabList;
107640     }
107641
107642     /* Initialize the rowset register to contain NULL. An SQL NULL is 
107643     ** equivalent to an empty rowset.
107644     **
107645     ** Also initialize regReturn to contain the address of the instruction 
107646     ** immediately following the OP_Return at the bottom of the loop. This
107647     ** is required in a few obscure LEFT JOIN cases where control jumps
107648     ** over the top of the loop into the body of it. In this case the 
107649     ** correct response for the end-of-loop code (the OP_Return) is to 
107650     ** fall through to the next instruction, just as an OP_Next does if
107651     ** called on an uninitialized cursor.
107652     */
107653     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
107654       regRowset = ++pParse->nMem;
107655       regRowid = ++pParse->nMem;
107656       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
107657     }
107658     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
107659
107660     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
107661     ** Then for every term xN, evaluate as the subexpression: xN AND z
107662     ** That way, terms in y that are factored into the disjunction will
107663     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
107664     **
107665     ** Actually, each subexpression is converted to "xN AND w" where w is
107666     ** the "interesting" terms of z - terms that did not originate in the
107667     ** ON or USING clause of a LEFT JOIN, and terms that are usable as 
107668     ** indices.
107669     */
107670     if( pWC->nTerm>1 ){
107671       int iTerm;
107672       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
107673         Expr *pExpr = pWC->a[iTerm].pExpr;
107674         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
107675         if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
107676         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
107677         pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
107678         pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
107679       }
107680       if( pAndExpr ){
107681         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
107682       }
107683     }
107684
107685     for(ii=0; ii<pOrWc->nTerm; ii++){
107686       WhereTerm *pOrTerm = &pOrWc->a[ii];
107687       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
107688         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
107689         Expr *pOrExpr = pOrTerm->pExpr;
107690         if( pAndExpr ){
107691           pAndExpr->pLeft = pOrExpr;
107692           pOrExpr = pAndExpr;
107693         }
107694         /* Loop through table entries that match term pOrTerm. */
107695         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
107696                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
107697                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
107698         assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
107699         if( pSubWInfo ){
107700           WhereLevel *pLvl;
107701           explainOneScan(
107702               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
107703           );
107704           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
107705             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
107706             int r;
107707             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
107708                                          regRowid, 0);
107709             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
107710                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
107711           }
107712           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
107713
107714           /* The pSubWInfo->untestedTerms flag means that this OR term
107715           ** contained one or more AND term from a notReady table.  The
107716           ** terms from the notReady table could not be tested and will
107717           ** need to be tested later.
107718           */
107719           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
107720
107721           /* If all of the OR-connected terms are optimized using the same
107722           ** index, and the index is opened using the same cursor number
107723           ** by each call to sqlite3WhereBegin() made by this loop, it may
107724           ** be possible to use that index as a covering index.
107725           **
107726           ** If the call to sqlite3WhereBegin() above resulted in a scan that
107727           ** uses an index, and this is either the first OR-connected term
107728           ** processed or the index is the same as that used by all previous
107729           ** terms, set pCov to the candidate covering index. Otherwise, set 
107730           ** pCov to NULL to indicate that no candidate covering index will 
107731           ** be available.
107732           */
107733           pLvl = &pSubWInfo->a[0];
107734           if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
107735            && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
107736            && (ii==0 || pLvl->plan.u.pIdx==pCov)
107737           ){
107738             assert( pLvl->iIdxCur==iCovCur );
107739             pCov = pLvl->plan.u.pIdx;
107740           }else{
107741             pCov = 0;
107742           }
107743
107744           /* Finish the loop through table entries that match term pOrTerm. */
107745           sqlite3WhereEnd(pSubWInfo);
107746         }
107747       }
107748     }
107749     pLevel->u.pCovidx = pCov;
107750     if( pCov ) pLevel->iIdxCur = iCovCur;
107751     if( pAndExpr ){
107752       pAndExpr->pLeft = 0;
107753       sqlite3ExprDelete(pParse->db, pAndExpr);
107754     }
107755     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
107756     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
107757     sqlite3VdbeResolveLabel(v, iLoopBody);
107758
107759     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
107760     if( !untestedTerms ) disableTerm(pLevel, pTerm);
107761   }else
107762 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
107763
107764   {
107765     /* Case 5:  There is no usable index.  We must do a complete
107766     **          scan of the entire table.
107767     */
107768     static const u8 aStep[] = { OP_Next, OP_Prev };
107769     static const u8 aStart[] = { OP_Rewind, OP_Last };
107770     assert( bRev==0 || bRev==1 );
107771     assert( omitTable==0 );
107772     pLevel->op = aStep[bRev];
107773     pLevel->p1 = iCur;
107774     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
107775     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
107776   }
107777   notReady &= ~getMask(pWC->pMaskSet, iCur);
107778
107779   /* Insert code to test every subexpression that can be completely
107780   ** computed using the current set of tables.
107781   **
107782   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
107783   ** the use of indices become tests that are evaluated against each row of
107784   ** the relevant input tables.
107785   */
107786   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
107787     Expr *pE;
107788     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
107789     testcase( pTerm->wtFlags & TERM_CODED );
107790     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
107791     if( (pTerm->prereqAll & notReady)!=0 ){
107792       testcase( pWInfo->untestedTerms==0
107793                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
107794       pWInfo->untestedTerms = 1;
107795       continue;
107796     }
107797     pE = pTerm->pExpr;
107798     assert( pE!=0 );
107799     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
107800       continue;
107801     }
107802     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
107803     pTerm->wtFlags |= TERM_CODED;
107804   }
107805
107806   /* For a LEFT OUTER JOIN, generate code that will record the fact that
107807   ** at least one row of the right table has matched the left table.  
107808   */
107809   if( pLevel->iLeftJoin ){
107810     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
107811     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
107812     VdbeComment((v, "record LEFT JOIN hit"));
107813     sqlite3ExprCacheClear(pParse);
107814     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
107815       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
107816       testcase( pTerm->wtFlags & TERM_CODED );
107817       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
107818       if( (pTerm->prereqAll & notReady)!=0 ){
107819         assert( pWInfo->untestedTerms );
107820         continue;
107821       }
107822       assert( pTerm->pExpr );
107823       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
107824       pTerm->wtFlags |= TERM_CODED;
107825     }
107826   }
107827   sqlite3ReleaseTempReg(pParse, iReleaseReg);
107828
107829   return notReady;
107830 }
107831
107832 #if defined(SQLITE_TEST)
107833 /*
107834 ** The following variable holds a text description of query plan generated
107835 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
107836 ** overwrites the previous.  This information is used for testing and
107837 ** analysis only.
107838 */
107839 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
107840 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
107841
107842 #endif /* SQLITE_TEST */
107843
107844
107845 /*
107846 ** Free a WhereInfo structure
107847 */
107848 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
107849   if( ALWAYS(pWInfo) ){
107850     int i;
107851     for(i=0; i<pWInfo->nLevel; i++){
107852       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
107853       if( pInfo ){
107854         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
107855         if( pInfo->needToFreeIdxStr ){
107856           sqlite3_free(pInfo->idxStr);
107857         }
107858         sqlite3DbFree(db, pInfo);
107859       }
107860       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
107861         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
107862         if( pIdx ){
107863           sqlite3DbFree(db, pIdx->zColAff);
107864           sqlite3DbFree(db, pIdx);
107865         }
107866       }
107867     }
107868     whereClauseClear(pWInfo->pWC);
107869     sqlite3DbFree(db, pWInfo);
107870   }
107871 }
107872
107873
107874 /*
107875 ** Generate the beginning of the loop used for WHERE clause processing.
107876 ** The return value is a pointer to an opaque structure that contains
107877 ** information needed to terminate the loop.  Later, the calling routine
107878 ** should invoke sqlite3WhereEnd() with the return value of this function
107879 ** in order to complete the WHERE clause processing.
107880 **
107881 ** If an error occurs, this routine returns NULL.
107882 **
107883 ** The basic idea is to do a nested loop, one loop for each table in
107884 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
107885 ** same as a SELECT with only a single table in the FROM clause.)  For
107886 ** example, if the SQL is this:
107887 **
107888 **       SELECT * FROM t1, t2, t3 WHERE ...;
107889 **
107890 ** Then the code generated is conceptually like the following:
107891 **
107892 **      foreach row1 in t1 do       \    Code generated
107893 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
107894 **          foreach row3 in t3 do   /
107895 **            ...
107896 **          end                     \    Code generated
107897 **        end                        |-- by sqlite3WhereEnd()
107898 **      end                         /
107899 **
107900 ** Note that the loops might not be nested in the order in which they
107901 ** appear in the FROM clause if a different order is better able to make
107902 ** use of indices.  Note also that when the IN operator appears in
107903 ** the WHERE clause, it might result in additional nested loops for
107904 ** scanning through all values on the right-hand side of the IN.
107905 **
107906 ** There are Btree cursors associated with each table.  t1 uses cursor
107907 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
107908 ** And so forth.  This routine generates code to open those VDBE cursors
107909 ** and sqlite3WhereEnd() generates the code to close them.
107910 **
107911 ** The code that sqlite3WhereBegin() generates leaves the cursors named
107912 ** in pTabList pointing at their appropriate entries.  The [...] code
107913 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
107914 ** data from the various tables of the loop.
107915 **
107916 ** If the WHERE clause is empty, the foreach loops must each scan their
107917 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
107918 ** the tables have indices and there are terms in the WHERE clause that
107919 ** refer to those indices, a complete table scan can be avoided and the
107920 ** code will run much faster.  Most of the work of this routine is checking
107921 ** to see if there are indices that can be used to speed up the loop.
107922 **
107923 ** Terms of the WHERE clause are also used to limit which rows actually
107924 ** make it to the "..." in the middle of the loop.  After each "foreach",
107925 ** terms of the WHERE clause that use only terms in that loop and outer
107926 ** loops are evaluated and if false a jump is made around all subsequent
107927 ** inner loops (or around the "..." if the test occurs within the inner-
107928 ** most loop)
107929 **
107930 ** OUTER JOINS
107931 **
107932 ** An outer join of tables t1 and t2 is conceptally coded as follows:
107933 **
107934 **    foreach row1 in t1 do
107935 **      flag = 0
107936 **      foreach row2 in t2 do
107937 **        start:
107938 **          ...
107939 **          flag = 1
107940 **      end
107941 **      if flag==0 then
107942 **        move the row2 cursor to a null row
107943 **        goto start
107944 **      fi
107945 **    end
107946 **
107947 ** ORDER BY CLAUSE PROCESSING
107948 **
107949 ** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
107950 ** if there is one.  If there is no ORDER BY clause or if this routine
107951 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
107952 **
107953 ** If an index can be used so that the natural output order of the table
107954 ** scan is correct for the ORDER BY clause, then that index is used and
107955 ** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr.  This
107956 ** is an optimization that prevents an unnecessary sort of the result set
107957 ** if an index appropriate for the ORDER BY clause already exists.
107958 **
107959 ** If the where clause loops cannot be arranged to provide the correct
107960 ** output order, then WhereInfo.nOBSat is 0.
107961 */
107962 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
107963   Parse *pParse,        /* The parser context */
107964   SrcList *pTabList,    /* A list of all tables to be scanned */
107965   Expr *pWhere,         /* The WHERE clause */
107966   ExprList *pOrderBy,   /* An ORDER BY clause, or NULL */
107967   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
107968   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
107969   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
107970 ){
107971   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
107972   int nTabList;              /* Number of elements in pTabList */
107973   WhereInfo *pWInfo;         /* Will become the return value of this function */
107974   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
107975   Bitmask notReady;          /* Cursors that are not yet positioned */
107976   WhereBestIdx sWBI;         /* Best index search context */
107977   WhereMaskSet *pMaskSet;    /* The expression mask set */
107978   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
107979   int iFrom;                 /* First unused FROM clause element */
107980   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
107981   int ii;                    /* Loop counter */
107982   sqlite3 *db;               /* Database connection */
107983
107984
107985   /* Variable initialization */
107986   memset(&sWBI, 0, sizeof(sWBI));
107987   sWBI.pParse = pParse;
107988
107989   /* The number of tables in the FROM clause is limited by the number of
107990   ** bits in a Bitmask 
107991   */
107992   testcase( pTabList->nSrc==BMS );
107993   if( pTabList->nSrc>BMS ){
107994     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
107995     return 0;
107996   }
107997
107998   /* This function normally generates a nested loop for all tables in 
107999   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
108000   ** only generate code for the first table in pTabList and assume that
108001   ** any cursors associated with subsequent tables are uninitialized.
108002   */
108003   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
108004
108005   /* Allocate and initialize the WhereInfo structure that will become the
108006   ** return value. A single allocation is used to store the WhereInfo
108007   ** struct, the contents of WhereInfo.a[], the WhereClause structure
108008   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
108009   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
108010   ** some architectures. Hence the ROUND8() below.
108011   */
108012   db = pParse->db;
108013   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
108014   pWInfo = sqlite3DbMallocZero(db, 
108015       nByteWInfo + 
108016       sizeof(WhereClause) +
108017       sizeof(WhereMaskSet)
108018   );
108019   if( db->mallocFailed ){
108020     sqlite3DbFree(db, pWInfo);
108021     pWInfo = 0;
108022     goto whereBeginError;
108023   }
108024   pWInfo->nLevel = nTabList;
108025   pWInfo->pParse = pParse;
108026   pWInfo->pTabList = pTabList;
108027   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
108028   pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
108029   pWInfo->wctrlFlags = wctrlFlags;
108030   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
108031   pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
108032   sWBI.aLevel = pWInfo->a;
108033
108034   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
108035   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
108036   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
108037
108038   /* Split the WHERE clause into separate subexpressions where each
108039   ** subexpression is separated by an AND operator.
108040   */
108041   initMaskSet(pMaskSet);
108042   whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
108043   sqlite3ExprCodeConstants(pParse, pWhere);
108044   whereSplit(sWBI.pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
108045     
108046   /* Special case: a WHERE clause that is constant.  Evaluate the
108047   ** expression and either jump over all of the code or fall thru.
108048   */
108049   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
108050     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
108051     pWhere = 0;
108052   }
108053
108054   /* Assign a bit from the bitmask to every term in the FROM clause.
108055   **
108056   ** When assigning bitmask values to FROM clause cursors, it must be
108057   ** the case that if X is the bitmask for the N-th FROM clause term then
108058   ** the bitmask for all FROM clause terms to the left of the N-th term
108059   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
108060   ** its Expr.iRightJoinTable value to find the bitmask of the right table
108061   ** of the join.  Subtracting one from the right table bitmask gives a
108062   ** bitmask for all tables to the left of the join.  Knowing the bitmask
108063   ** for all tables to the left of a left join is important.  Ticket #3015.
108064   **
108065   ** Note that bitmasks are created for all pTabList->nSrc tables in
108066   ** pTabList, not just the first nTabList tables.  nTabList is normally
108067   ** equal to pTabList->nSrc but might be shortened to 1 if the
108068   ** WHERE_ONETABLE_ONLY flag is set.
108069   */
108070   for(ii=0; ii<pTabList->nSrc; ii++){
108071     createMask(pMaskSet, pTabList->a[ii].iCursor);
108072   }
108073 #ifndef NDEBUG
108074   {
108075     Bitmask toTheLeft = 0;
108076     for(ii=0; ii<pTabList->nSrc; ii++){
108077       Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
108078       assert( (m-1)==toTheLeft );
108079       toTheLeft |= m;
108080     }
108081   }
108082 #endif
108083
108084   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
108085   ** add new virtual terms onto the end of the WHERE clause.  We do not
108086   ** want to analyze these virtual terms, so start analyzing at the end
108087   ** and work forward so that the added virtual terms are never processed.
108088   */
108089   exprAnalyzeAll(pTabList, sWBI.pWC);
108090   if( db->mallocFailed ){
108091     goto whereBeginError;
108092   }
108093
108094   /* Check if the DISTINCT qualifier, if there is one, is redundant. 
108095   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
108096   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
108097   */
108098   if( pDistinct && isDistinctRedundant(pParse, pTabList, sWBI.pWC, pDistinct) ){
108099     pDistinct = 0;
108100     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
108101   }
108102
108103   /* Chose the best index to use for each table in the FROM clause.
108104   **
108105   ** This loop fills in the following fields:
108106   **
108107   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
108108   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
108109   **   pWInfo->a[].nEq       The number of == and IN constraints
108110   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
108111   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
108112   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
108113   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
108114   **
108115   ** This loop also figures out the nesting order of tables in the FROM
108116   ** clause.
108117   */
108118   sWBI.notValid = ~(Bitmask)0;
108119   sWBI.pOrderBy = pOrderBy;
108120   sWBI.n = nTabList;
108121   sWBI.pDistinct = pDistinct;
108122   andFlags = ~0;
108123   WHERETRACE(("*** Optimizer Start ***\n"));
108124   for(sWBI.i=iFrom=0, pLevel=pWInfo->a; sWBI.i<nTabList; sWBI.i++, pLevel++){
108125     WhereCost bestPlan;         /* Most efficient plan seen so far */
108126     Index *pIdx;                /* Index for FROM table at pTabItem */
108127     int j;                      /* For looping over FROM tables */
108128     int bestJ = -1;             /* The value of j */
108129     Bitmask m;                  /* Bitmask value for j or bestJ */
108130     int isOptimal;              /* Iterator for optimal/non-optimal search */
108131     int ckOptimal;              /* Do the optimal scan check */
108132     int nUnconstrained;         /* Number tables without INDEXED BY */
108133     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
108134
108135     memset(&bestPlan, 0, sizeof(bestPlan));
108136     bestPlan.rCost = SQLITE_BIG_DBL;
108137     WHERETRACE(("*** Begin search for loop %d ***\n", sWBI.i));
108138
108139     /* Loop through the remaining entries in the FROM clause to find the
108140     ** next nested loop. The loop tests all FROM clause entries
108141     ** either once or twice. 
108142     **
108143     ** The first test is always performed if there are two or more entries
108144     ** remaining and never performed if there is only one FROM clause entry
108145     ** to choose from.  The first test looks for an "optimal" scan.  In
108146     ** this context an optimal scan is one that uses the same strategy
108147     ** for the given FROM clause entry as would be selected if the entry
108148     ** were used as the innermost nested loop.  In other words, a table
108149     ** is chosen such that the cost of running that table cannot be reduced
108150     ** by waiting for other tables to run first.  This "optimal" test works
108151     ** by first assuming that the FROM clause is on the inner loop and finding
108152     ** its query plan, then checking to see if that query plan uses any
108153     ** other FROM clause terms that are sWBI.notValid.  If no notValid terms
108154     ** are used then the "optimal" query plan works.
108155     **
108156     ** Note that the WhereCost.nRow parameter for an optimal scan might
108157     ** not be as small as it would be if the table really were the innermost
108158     ** join.  The nRow value can be reduced by WHERE clause constraints
108159     ** that do not use indices.  But this nRow reduction only happens if the
108160     ** table really is the innermost join.  
108161     **
108162     ** The second loop iteration is only performed if no optimal scan
108163     ** strategies were found by the first iteration. This second iteration
108164     ** is used to search for the lowest cost scan overall.
108165     **
108166     ** Without the optimal scan step (the first iteration) a suboptimal
108167     ** plan might be chosen for queries like this:
108168     **   
108169     **   CREATE TABLE t1(a, b); 
108170     **   CREATE TABLE t2(c, d);
108171     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
108172     **
108173     ** The best strategy is to iterate through table t1 first. However it
108174     ** is not possible to determine this with a simple greedy algorithm.
108175     ** Since the cost of a linear scan through table t2 is the same 
108176     ** as the cost of a linear scan through table t1, a simple greedy 
108177     ** algorithm may choose to use t2 for the outer loop, which is a much
108178     ** costlier approach.
108179     */
108180     nUnconstrained = 0;
108181     notIndexed = 0;
108182
108183     /* The optimal scan check only occurs if there are two or more tables
108184     ** available to be reordered */
108185     if( iFrom==nTabList-1 ){
108186       ckOptimal = 0;  /* Common case of just one table in the FROM clause */
108187     }else{
108188       ckOptimal = -1;
108189       for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
108190         m = getMask(pMaskSet, sWBI.pSrc->iCursor);
108191         if( (m & sWBI.notValid)==0 ){
108192           if( j==iFrom ) iFrom++;
108193           continue;
108194         }
108195         if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ) break;
108196         if( ++ckOptimal ) break;
108197         if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
108198       }
108199     }
108200     assert( ckOptimal==0 || ckOptimal==1 );
108201
108202     for(isOptimal=ckOptimal; isOptimal>=0 && bestJ<0; isOptimal--){
108203       for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
108204         if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ){
108205           /* This break and one like it in the ckOptimal computation loop
108206           ** above prevent table reordering across LEFT and CROSS JOINs.
108207           ** The LEFT JOIN case is necessary for correctness.  The prohibition
108208           ** against reordering across a CROSS JOIN is an SQLite feature that
108209           ** allows the developer to control table reordering */
108210           break;
108211         }
108212         m = getMask(pMaskSet, sWBI.pSrc->iCursor);
108213         if( (m & sWBI.notValid)==0 ){
108214           assert( j>iFrom );
108215           continue;
108216         }
108217         sWBI.notReady = (isOptimal ? m : sWBI.notValid);
108218         if( sWBI.pSrc->pIndex==0 ) nUnconstrained++;
108219   
108220         WHERETRACE(("   === trying table %d (%s) with isOptimal=%d ===\n",
108221                     j, sWBI.pSrc->pTab->zName, isOptimal));
108222         assert( sWBI.pSrc->pTab );
108223 #ifndef SQLITE_OMIT_VIRTUALTABLE
108224         if( IsVirtual(sWBI.pSrc->pTab) ){
108225           sWBI.ppIdxInfo = &pWInfo->a[j].pIdxInfo;
108226           bestVirtualIndex(&sWBI);
108227         }else 
108228 #endif
108229         {
108230           bestBtreeIndex(&sWBI);
108231         }
108232         assert( isOptimal || (sWBI.cost.used&sWBI.notValid)==0 );
108233
108234         /* If an INDEXED BY clause is present, then the plan must use that
108235         ** index if it uses any index at all */
108236         assert( sWBI.pSrc->pIndex==0 
108237                   || (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
108238                   || sWBI.cost.plan.u.pIdx==sWBI.pSrc->pIndex );
108239
108240         if( isOptimal && (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
108241           notIndexed |= m;
108242         }
108243         if( isOptimal ){
108244           pWInfo->a[j].rOptCost = sWBI.cost.rCost;
108245         }else if( ckOptimal ){
108246           /* If two or more tables have nearly the same outer loop cost, but
108247           ** very different inner loop (optimal) cost, we want to choose
108248           ** for the outer loop that table which benefits the least from
108249           ** being in the inner loop.  The following code scales the 
108250           ** outer loop cost estimate to accomplish that. */
108251           WHERETRACE(("   scaling cost from %.1f to %.1f\n",
108252                       sWBI.cost.rCost,
108253                       sWBI.cost.rCost/pWInfo->a[j].rOptCost));
108254           sWBI.cost.rCost /= pWInfo->a[j].rOptCost;
108255         }
108256
108257         /* Conditions under which this table becomes the best so far:
108258         **
108259         **   (1) The table must not depend on other tables that have not
108260         **       yet run.  (In other words, it must not depend on tables
108261         **       in inner loops.)
108262         **
108263         **   (2) (This rule was removed on 2012-11-09.  The scaling of the
108264         **       cost using the optimal scan cost made this rule obsolete.)
108265         **
108266         **   (3) All tables have an INDEXED BY clause or this table lacks an
108267         **       INDEXED BY clause or this table uses the specific
108268         **       index specified by its INDEXED BY clause.  This rule ensures
108269         **       that a best-so-far is always selected even if an impossible
108270         **       combination of INDEXED BY clauses are given.  The error
108271         **       will be detected and relayed back to the application later.
108272         **       The NEVER() comes about because rule (2) above prevents
108273         **       An indexable full-table-scan from reaching rule (3).
108274         **
108275         **   (4) The plan cost must be lower than prior plans, where "cost"
108276         **       is defined by the compareCost() function above. 
108277         */
108278         if( (sWBI.cost.used&sWBI.notValid)==0                    /* (1) */
108279             && (nUnconstrained==0 || sWBI.pSrc->pIndex==0        /* (3) */
108280                 || NEVER((sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
108281             && (bestJ<0 || compareCost(&sWBI.cost, &bestPlan))   /* (4) */
108282         ){
108283           WHERETRACE(("   === table %d (%s) is best so far\n"
108284                       "       cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=%08x\n",
108285                       j, sWBI.pSrc->pTab->zName,
108286                       sWBI.cost.rCost, sWBI.cost.plan.nRow,
108287                       sWBI.cost.plan.nOBSat, sWBI.cost.plan.wsFlags));
108288           bestPlan = sWBI.cost;
108289           bestJ = j;
108290         }
108291
108292         /* In a join like "w JOIN x LEFT JOIN y JOIN z"  make sure that
108293         ** table y (and not table z) is always the next inner loop inside
108294         ** of table x. */
108295         if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
108296       }
108297     }
108298     assert( bestJ>=0 );
108299     assert( sWBI.notValid & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
108300     assert( bestJ==iFrom || (pTabList->a[iFrom].jointype & JT_LEFT)==0 );
108301     testcase( bestJ>iFrom && (pTabList->a[iFrom].jointype & JT_CROSS)!=0 );
108302     testcase( bestJ>iFrom && bestJ<nTabList-1
108303                           && (pTabList->a[bestJ+1].jointype & JT_LEFT)!=0 );
108304     WHERETRACE(("*** Optimizer selects table %d (%s) for loop %d with:\n"
108305                 "    cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=0x%08x\n",
108306                 bestJ, pTabList->a[bestJ].pTab->zName,
108307                 pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow,
108308                 bestPlan.plan.nOBSat, bestPlan.plan.wsFlags));
108309     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
108310       assert( pWInfo->eDistinct==0 );
108311       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
108312     }
108313     andFlags &= bestPlan.plan.wsFlags;
108314     pLevel->plan = bestPlan.plan;
108315     pLevel->iTabCur = pTabList->a[bestJ].iCursor;
108316     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
108317     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
108318     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
108319       if( (wctrlFlags & WHERE_ONETABLE_ONLY) 
108320        && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0 
108321       ){
108322         pLevel->iIdxCur = iIdxCur;
108323       }else{
108324         pLevel->iIdxCur = pParse->nTab++;
108325       }
108326     }else{
108327       pLevel->iIdxCur = -1;
108328     }
108329     sWBI.notValid &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
108330     pLevel->iFrom = (u8)bestJ;
108331     if( bestPlan.plan.nRow>=(double)1 ){
108332       pParse->nQueryLoop *= bestPlan.plan.nRow;
108333     }
108334
108335     /* Check that if the table scanned by this loop iteration had an
108336     ** INDEXED BY clause attached to it, that the named index is being
108337     ** used for the scan. If not, then query compilation has failed.
108338     ** Return an error.
108339     */
108340     pIdx = pTabList->a[bestJ].pIndex;
108341     if( pIdx ){
108342       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
108343         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
108344         goto whereBeginError;
108345       }else{
108346         /* If an INDEXED BY clause is used, the bestIndex() function is
108347         ** guaranteed to find the index specified in the INDEXED BY clause
108348         ** if it find an index at all. */
108349         assert( bestPlan.plan.u.pIdx==pIdx );
108350       }
108351     }
108352   }
108353   WHERETRACE(("*** Optimizer Finished ***\n"));
108354   if( pParse->nErr || db->mallocFailed ){
108355     goto whereBeginError;
108356   }
108357   if( nTabList ){
108358     pLevel--;
108359     pWInfo->nOBSat = pLevel->plan.nOBSat;
108360   }else{
108361     pWInfo->nOBSat = 0;
108362   }
108363
108364   /* If the total query only selects a single row, then the ORDER BY
108365   ** clause is irrelevant.
108366   */
108367   if( (andFlags & WHERE_UNIQUE)!=0 && pOrderBy ){
108368     assert( nTabList==0 || (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 );
108369     pWInfo->nOBSat = pOrderBy->nExpr;
108370   }
108371
108372   /* If the caller is an UPDATE or DELETE statement that is requesting
108373   ** to use a one-pass algorithm, determine if this is appropriate.
108374   ** The one-pass algorithm only works if the WHERE clause constraints
108375   ** the statement to update a single row.
108376   */
108377   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
108378   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
108379     pWInfo->okOnePass = 1;
108380     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
108381   }
108382
108383   /* Open all tables in the pTabList and any indices selected for
108384   ** searching those tables.
108385   */
108386   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
108387   notReady = ~(Bitmask)0;
108388   pWInfo->nRowOut = (double)1;
108389   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
108390     Table *pTab;     /* Table to open */
108391     int iDb;         /* Index of database containing table/index */
108392     struct SrcList_item *pTabItem;
108393
108394     pTabItem = &pTabList->a[pLevel->iFrom];
108395     pTab = pTabItem->pTab;
108396     pWInfo->nRowOut *= pLevel->plan.nRow;
108397     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
108398     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
108399       /* Do nothing */
108400     }else
108401 #ifndef SQLITE_OMIT_VIRTUALTABLE
108402     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
108403       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
108404       int iCur = pTabItem->iCursor;
108405       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
108406     }else if( IsVirtual(pTab) ){
108407       /* noop */
108408     }else
108409 #endif
108410     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
108411          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
108412       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
108413       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
108414       testcase( pTab->nCol==BMS-1 );
108415       testcase( pTab->nCol==BMS );
108416       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
108417         Bitmask b = pTabItem->colUsed;
108418         int n = 0;
108419         for(; b; b=b>>1, n++){}
108420         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
108421                             SQLITE_INT_TO_PTR(n), P4_INT32);
108422         assert( n<=pTab->nCol );
108423       }
108424     }else{
108425       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
108426     }
108427 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
108428     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
108429       constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
108430     }else
108431 #endif
108432     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
108433       Index *pIx = pLevel->plan.u.pIdx;
108434       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
108435       int iIndexCur = pLevel->iIdxCur;
108436       assert( pIx->pSchema==pTab->pSchema );
108437       assert( iIndexCur>=0 );
108438       sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
108439                         (char*)pKey, P4_KEYINFO_HANDOFF);
108440       VdbeComment((v, "%s", pIx->zName));
108441     }
108442     sqlite3CodeVerifySchema(pParse, iDb);
108443     notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
108444   }
108445   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
108446   if( db->mallocFailed ) goto whereBeginError;
108447
108448   /* Generate the code to do the search.  Each iteration of the for
108449   ** loop below generates code for a single nested loop of the VM
108450   ** program.
108451   */
108452   notReady = ~(Bitmask)0;
108453   for(ii=0; ii<nTabList; ii++){
108454     pLevel = &pWInfo->a[ii];
108455     explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
108456     notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
108457     pWInfo->iContinue = pLevel->addrCont;
108458   }
108459
108460 #ifdef SQLITE_TEST  /* For testing and debugging use only */
108461   /* Record in the query plan information about the current table
108462   ** and the index used to access it (if any).  If the table itself
108463   ** is not used, its name is just '{}'.  If no index is used
108464   ** the index is listed as "{}".  If the primary key is used the
108465   ** index name is '*'.
108466   */
108467   for(ii=0; ii<nTabList; ii++){
108468     char *z;
108469     int n;
108470     int w;
108471     struct SrcList_item *pTabItem;
108472
108473     pLevel = &pWInfo->a[ii];
108474     w = pLevel->plan.wsFlags;
108475     pTabItem = &pTabList->a[pLevel->iFrom];
108476     z = pTabItem->zAlias;
108477     if( z==0 ) z = pTabItem->pTab->zName;
108478     n = sqlite3Strlen30(z);
108479     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
108480       if( (w & WHERE_IDX_ONLY)!=0 && (w & WHERE_COVER_SCAN)==0 ){
108481         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
108482         nQPlan += 2;
108483       }else{
108484         memcpy(&sqlite3_query_plan[nQPlan], z, n);
108485         nQPlan += n;
108486       }
108487       sqlite3_query_plan[nQPlan++] = ' ';
108488     }
108489     testcase( w & WHERE_ROWID_EQ );
108490     testcase( w & WHERE_ROWID_RANGE );
108491     if( w & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
108492       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
108493       nQPlan += 2;
108494     }else if( (w & WHERE_INDEXED)!=0 && (w & WHERE_COVER_SCAN)==0 ){
108495       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
108496       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
108497         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
108498         nQPlan += n;
108499         sqlite3_query_plan[nQPlan++] = ' ';
108500       }
108501     }else{
108502       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
108503       nQPlan += 3;
108504     }
108505   }
108506   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
108507     sqlite3_query_plan[--nQPlan] = 0;
108508   }
108509   sqlite3_query_plan[nQPlan] = 0;
108510   nQPlan = 0;
108511 #endif /* SQLITE_TEST // Testing and debugging use only */
108512
108513   /* Record the continuation address in the WhereInfo structure.  Then
108514   ** clean up and return.
108515   */
108516   return pWInfo;
108517
108518   /* Jump here if malloc fails */
108519 whereBeginError:
108520   if( pWInfo ){
108521     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
108522     whereInfoFree(db, pWInfo);
108523   }
108524   return 0;
108525 }
108526
108527 /*
108528 ** Generate the end of the WHERE loop.  See comments on 
108529 ** sqlite3WhereBegin() for additional information.
108530 */
108531 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
108532   Parse *pParse = pWInfo->pParse;
108533   Vdbe *v = pParse->pVdbe;
108534   int i;
108535   WhereLevel *pLevel;
108536   SrcList *pTabList = pWInfo->pTabList;
108537   sqlite3 *db = pParse->db;
108538
108539   /* Generate loop termination code.
108540   */
108541   sqlite3ExprCacheClear(pParse);
108542   for(i=pWInfo->nLevel-1; i>=0; i--){
108543     pLevel = &pWInfo->a[i];
108544     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
108545     if( pLevel->op!=OP_Noop ){
108546       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
108547       sqlite3VdbeChangeP5(v, pLevel->p5);
108548     }
108549     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
108550       struct InLoop *pIn;
108551       int j;
108552       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
108553       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
108554         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
108555         sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
108556         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
108557       }
108558       sqlite3DbFree(db, pLevel->u.in.aInLoop);
108559     }
108560     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
108561     if( pLevel->iLeftJoin ){
108562       int addr;
108563       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
108564       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
108565            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
108566       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
108567         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
108568       }
108569       if( pLevel->iIdxCur>=0 ){
108570         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
108571       }
108572       if( pLevel->op==OP_Return ){
108573         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
108574       }else{
108575         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
108576       }
108577       sqlite3VdbeJumpHere(v, addr);
108578     }
108579   }
108580
108581   /* The "break" point is here, just past the end of the outer loop.
108582   ** Set it.
108583   */
108584   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
108585
108586   /* Close all of the cursors that were opened by sqlite3WhereBegin.
108587   */
108588   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
108589   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
108590     Index *pIdx = 0;
108591     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
108592     Table *pTab = pTabItem->pTab;
108593     assert( pTab!=0 );
108594     if( (pTab->tabFlags & TF_Ephemeral)==0
108595      && pTab->pSelect==0
108596      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
108597     ){
108598       int ws = pLevel->plan.wsFlags;
108599       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
108600         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
108601       }
108602       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
108603         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
108604       }
108605     }
108606
108607     /* If this scan uses an index, make code substitutions to read data
108608     ** from the index in preference to the table. Sometimes, this means
108609     ** the table need never be read from. This is a performance boost,
108610     ** as the vdbe level waits until the table is read before actually
108611     ** seeking the table cursor to the record corresponding to the current
108612     ** position in the index.
108613     ** 
108614     ** Calls to the code generator in between sqlite3WhereBegin and
108615     ** sqlite3WhereEnd will have created code that references the table
108616     ** directly.  This loop scans all that code looking for opcodes
108617     ** that reference the table and converts them into opcodes that
108618     ** reference the index.
108619     */
108620     if( pLevel->plan.wsFlags & WHERE_INDEXED ){
108621       pIdx = pLevel->plan.u.pIdx;
108622     }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
108623       pIdx = pLevel->u.pCovidx;
108624     }
108625     if( pIdx && !db->mallocFailed){
108626       int k, j, last;
108627       VdbeOp *pOp;
108628
108629       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
108630       last = sqlite3VdbeCurrentAddr(v);
108631       for(k=pWInfo->iTop; k<last; k++, pOp++){
108632         if( pOp->p1!=pLevel->iTabCur ) continue;
108633         if( pOp->opcode==OP_Column ){
108634           for(j=0; j<pIdx->nColumn; j++){
108635             if( pOp->p2==pIdx->aiColumn[j] ){
108636               pOp->p2 = j;
108637               pOp->p1 = pLevel->iIdxCur;
108638               break;
108639             }
108640           }
108641           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
108642                || j<pIdx->nColumn );
108643         }else if( pOp->opcode==OP_Rowid ){
108644           pOp->p1 = pLevel->iIdxCur;
108645           pOp->opcode = OP_IdxRowid;
108646         }
108647       }
108648     }
108649   }
108650
108651   /* Final cleanup
108652   */
108653   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
108654   whereInfoFree(db, pWInfo);
108655   return;
108656 }
108657
108658 /************** End of where.c ***********************************************/
108659 /************** Begin file parse.c *******************************************/
108660 /* Driver template for the LEMON parser generator.
108661 ** The author disclaims copyright to this source code.
108662 **
108663 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
108664 ** The only modifications are the addition of a couple of NEVER()
108665 ** macros to disable tests that are needed in the case of a general
108666 ** LALR(1) grammar but which are always false in the
108667 ** specific grammar used by SQLite.
108668 */
108669 /* First off, code is included that follows the "include" declaration
108670 ** in the input grammar file. */
108671 /* #include <stdio.h> */
108672
108673
108674 /*
108675 ** Disable all error recovery processing in the parser push-down
108676 ** automaton.
108677 */
108678 #define YYNOERRORRECOVERY 1
108679
108680 /*
108681 ** Make yytestcase() the same as testcase()
108682 */
108683 #define yytestcase(X) testcase(X)
108684
108685 /*
108686 ** An instance of this structure holds information about the
108687 ** LIMIT clause of a SELECT statement.
108688 */
108689 struct LimitVal {
108690   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
108691   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
108692 };
108693
108694 /*
108695 ** An instance of this structure is used to store the LIKE,
108696 ** GLOB, NOT LIKE, and NOT GLOB operators.
108697 */
108698 struct LikeOp {
108699   Token eOperator;  /* "like" or "glob" or "regexp" */
108700   int bNot;         /* True if the NOT keyword is present */
108701 };
108702
108703 /*
108704 ** An instance of the following structure describes the event of a
108705 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
108706 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
108707 **
108708 **      UPDATE ON (a,b,c)
108709 **
108710 ** Then the "b" IdList records the list "a,b,c".
108711 */
108712 struct TrigEvent { int a; IdList * b; };
108713
108714 /*
108715 ** An instance of this structure holds the ATTACH key and the key type.
108716 */
108717 struct AttachKey { int type;  Token key; };
108718
108719 /*
108720 ** One or more VALUES claues
108721 */
108722 struct ValueList {
108723   ExprList *pList;
108724   Select *pSelect;
108725 };
108726
108727
108728   /* This is a utility routine used to set the ExprSpan.zStart and
108729   ** ExprSpan.zEnd values of pOut so that the span covers the complete
108730   ** range of text beginning with pStart and going to the end of pEnd.
108731   */
108732   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
108733     pOut->zStart = pStart->z;
108734     pOut->zEnd = &pEnd->z[pEnd->n];
108735   }
108736
108737   /* Construct a new Expr object from a single identifier.  Use the
108738   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
108739   ** that created the expression.
108740   */
108741   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
108742     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
108743     pOut->zStart = pValue->z;
108744     pOut->zEnd = &pValue->z[pValue->n];
108745   }
108746
108747   /* This routine constructs a binary expression node out of two ExprSpan
108748   ** objects and uses the result to populate a new ExprSpan object.
108749   */
108750   static void spanBinaryExpr(
108751     ExprSpan *pOut,     /* Write the result here */
108752     Parse *pParse,      /* The parsing context.  Errors accumulate here */
108753     int op,             /* The binary operation */
108754     ExprSpan *pLeft,    /* The left operand */
108755     ExprSpan *pRight    /* The right operand */
108756   ){
108757     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
108758     pOut->zStart = pLeft->zStart;
108759     pOut->zEnd = pRight->zEnd;
108760   }
108761
108762   /* Construct an expression node for a unary postfix operator
108763   */
108764   static void spanUnaryPostfix(
108765     ExprSpan *pOut,        /* Write the new expression node here */
108766     Parse *pParse,         /* Parsing context to record errors */
108767     int op,                /* The operator */
108768     ExprSpan *pOperand,    /* The operand */
108769     Token *pPostOp         /* The operand token for setting the span */
108770   ){
108771     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
108772     pOut->zStart = pOperand->zStart;
108773     pOut->zEnd = &pPostOp->z[pPostOp->n];
108774   }                           
108775
108776   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
108777   ** unary TK_ISNULL or TK_NOTNULL expression. */
108778   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
108779     sqlite3 *db = pParse->db;
108780     if( db->mallocFailed==0 && pY->op==TK_NULL ){
108781       pA->op = (u8)op;
108782       sqlite3ExprDelete(db, pA->pRight);
108783       pA->pRight = 0;
108784     }
108785   }
108786
108787   /* Construct an expression node for a unary prefix operator
108788   */
108789   static void spanUnaryPrefix(
108790     ExprSpan *pOut,        /* Write the new expression node here */
108791     Parse *pParse,         /* Parsing context to record errors */
108792     int op,                /* The operator */
108793     ExprSpan *pOperand,    /* The operand */
108794     Token *pPreOp         /* The operand token for setting the span */
108795   ){
108796     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
108797     pOut->zStart = pPreOp->z;
108798     pOut->zEnd = pOperand->zEnd;
108799   }
108800 /* Next is all token values, in a form suitable for use by makeheaders.
108801 ** This section will be null unless lemon is run with the -m switch.
108802 */
108803 /* 
108804 ** These constants (all generated automatically by the parser generator)
108805 ** specify the various kinds of tokens (terminals) that the parser
108806 ** understands. 
108807 **
108808 ** Each symbol here is a terminal symbol in the grammar.
108809 */
108810 /* Make sure the INTERFACE macro is defined.
108811 */
108812 #ifndef INTERFACE
108813 # define INTERFACE 1
108814 #endif
108815 /* The next thing included is series of defines which control
108816 ** various aspects of the generated parser.
108817 **    YYCODETYPE         is the data type used for storing terminal
108818 **                       and nonterminal numbers.  "unsigned char" is
108819 **                       used if there are fewer than 250 terminals
108820 **                       and nonterminals.  "int" is used otherwise.
108821 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
108822 **                       to no legal terminal or nonterminal number.  This
108823 **                       number is used to fill in empty slots of the hash 
108824 **                       table.
108825 **    YYFALLBACK         If defined, this indicates that one or more tokens
108826 **                       have fall-back values which should be used if the
108827 **                       original value of the token will not parse.
108828 **    YYACTIONTYPE       is the data type used for storing terminal
108829 **                       and nonterminal numbers.  "unsigned char" is
108830 **                       used if there are fewer than 250 rules and
108831 **                       states combined.  "int" is used otherwise.
108832 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
108833 **                       directly to the parser from the tokenizer.
108834 **    YYMINORTYPE        is the data type used for all minor tokens.
108835 **                       This is typically a union of many types, one of
108836 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
108837 **                       for base tokens is called "yy0".
108838 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
108839 **                       zero the stack is dynamically sized using realloc()
108840 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
108841 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
108842 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
108843 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
108844 **    YYNSTATE           the combined number of states.
108845 **    YYNRULE            the number of rules in the grammar
108846 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
108847 **                       defined, then do no error processing.
108848 */
108849 #define YYCODETYPE unsigned char
108850 #define YYNOCODE 251
108851 #define YYACTIONTYPE unsigned short int
108852 #define YYWILDCARD 67
108853 #define sqlite3ParserTOKENTYPE Token
108854 typedef union {
108855   int yyinit;
108856   sqlite3ParserTOKENTYPE yy0;
108857   struct LimitVal yy64;
108858   Expr* yy122;
108859   Select* yy159;
108860   IdList* yy180;
108861   struct {int value; int mask;} yy207;
108862   u8 yy258;
108863   u16 yy305;
108864   struct LikeOp yy318;
108865   TriggerStep* yy327;
108866   ExprSpan yy342;
108867   SrcList* yy347;
108868   int yy392;
108869   struct TrigEvent yy410;
108870   ExprList* yy442;
108871   struct ValueList yy487;
108872 } YYMINORTYPE;
108873 #ifndef YYSTACKDEPTH
108874 #define YYSTACKDEPTH 100
108875 #endif
108876 #define sqlite3ParserARG_SDECL Parse *pParse;
108877 #define sqlite3ParserARG_PDECL ,Parse *pParse
108878 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
108879 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
108880 #define YYNSTATE 627
108881 #define YYNRULE 327
108882 #define YYFALLBACK 1
108883 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
108884 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
108885 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
108886
108887 /* The yyzerominor constant is used to initialize instances of
108888 ** YYMINORTYPE objects to zero. */
108889 static const YYMINORTYPE yyzerominor = { 0 };
108890
108891 /* Define the yytestcase() macro to be a no-op if is not already defined
108892 ** otherwise.
108893 **
108894 ** Applications can choose to define yytestcase() in the %include section
108895 ** to a macro that can assist in verifying code coverage.  For production
108896 ** code the yytestcase() macro should be turned off.  But it is useful
108897 ** for testing.
108898 */
108899 #ifndef yytestcase
108900 # define yytestcase(X)
108901 #endif
108902
108903
108904 /* Next are the tables used to determine what action to take based on the
108905 ** current state and lookahead token.  These tables are used to implement
108906 ** functions that take a state number and lookahead value and return an
108907 ** action integer.  
108908 **
108909 ** Suppose the action integer is N.  Then the action is determined as
108910 ** follows
108911 **
108912 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
108913 **                                      token onto the stack and goto state N.
108914 **
108915 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
108916 **
108917 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
108918 **
108919 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
108920 **
108921 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
108922 **                                      slots in the yy_action[] table.
108923 **
108924 ** The action table is constructed as a single large table named yy_action[].
108925 ** Given state S and lookahead X, the action is computed as
108926 **
108927 **      yy_action[ yy_shift_ofst[S] + X ]
108928 **
108929 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
108930 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
108931 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
108932 ** and that yy_default[S] should be used instead.  
108933 **
108934 ** The formula above is for computing the action when the lookahead is
108935 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
108936 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
108937 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
108938 ** YY_SHIFT_USE_DFLT.
108939 **
108940 ** The following are the tables generated in this section:
108941 **
108942 **  yy_action[]        A single table containing all actions.
108943 **  yy_lookahead[]     A table containing the lookahead for each entry in
108944 **                     yy_action.  Used to detect hash collisions.
108945 **  yy_shift_ofst[]    For each state, the offset into yy_action for
108946 **                     shifting terminals.
108947 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
108948 **                     shifting non-terminals after a reduce.
108949 **  yy_default[]       Default action for each state.
108950 */
108951 #define YY_ACTTAB_COUNT (1564)
108952 static const YYACTIONTYPE yy_action[] = {
108953  /*     0 */   309,  955,  184,  417,    2,  171,  624,  594,   56,   56,
108954  /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,
108955  /*    20 */    52,   52,   51,  233,  620,  619,  298,  620,  619,  234,
108956  /*    30 */   587,  581,   56,   56,   56,   56,   19,   54,   54,   54,
108957  /*    40 */    54,   53,   53,   52,   52,   52,   51,  233,  605,   57,
108958  /*    50 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
108959  /*    60 */    56,   56,  541,   54,   54,   54,   54,   53,   53,   52,
108960  /*    70 */    52,   52,   51,  233,  309,  594,  325,  196,  195,  194,
108961  /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108962  /*    90 */    51,  233,  617,  616,  165,  617,  616,  380,  377,  376,
108963  /*   100 */   407,  532,  576,  576,  587,  581,  303,  422,  375,   59,
108964  /*   110 */    53,   53,   52,   52,   52,   51,  233,   50,   47,  146,
108965  /*   120 */   574,  545,   65,   57,   58,   48,  579,  578,  580,  580,
108966  /*   130 */    55,   55,   56,   56,   56,   56,  213,   54,   54,   54,
108967  /*   140 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  223,
108968  /*   150 */   539,  420,  170,  176,  138,  280,  383,  275,  382,  168,
108969  /*   160 */   489,  551,  409,  668,  620,  619,  271,  438,  409,  438,
108970  /*   170 */   550,  604,   67,  482,  507,  618,  599,  412,  587,  581,
108971  /*   180 */   600,  483,  618,  412,  618,  598,   91,  439,  440,  439,
108972  /*   190 */   335,  598,   73,  669,  222,  266,  480,   57,   58,   48,
108973  /*   200 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
108974  /*   210 */   670,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108975  /*   220 */    51,  233,  309,  279,  232,  231,    1,  132,  200,  385,
108976  /*   230 */   620,  619,  617,  616,  278,  435,  289,  563,  175,  262,
108977  /*   240 */   409,  264,  437,  497,  436,  166,  441,  568,  336,  568,
108978  /*   250 */   201,  537,  587,  581,  599,  412,  165,  594,  600,  380,
108979  /*   260 */   377,  376,  597,  598,   92,  523,  618,  569,  569,  592,
108980  /*   270 */   375,   57,   58,   48,  579,  578,  580,  580,   55,   55,
108981  /*   280 */    56,   56,   56,   56,  597,   54,   54,   54,   54,   53,
108982  /*   290 */    53,   52,   52,   52,   51,  233,  309,  463,  617,  616,
108983  /*   300 */   590,  590,  590,  174,  272,  396,  409,  272,  409,  548,
108984  /*   310 */   397,  620,  619,   68,  326,  620,  619,  620,  619,  618,
108985  /*   320 */   546,  412,  618,  412,  471,  594,  587,  581,  472,  598,
108986  /*   330 */    92,  598,   92,   52,   52,   52,   51,  233,  513,  512,
108987  /*   340 */   206,  322,  363,  464,  221,   57,   58,   48,  579,  578,
108988  /*   350 */   580,  580,   55,   55,   56,   56,   56,   56,  529,   54,
108989  /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
108990  /*   370 */   309,  396,  409,  396,  597,  372,  386,  530,  347,  617,
108991  /*   380 */   616,  575,  202,  617,  616,  617,  616,  412,  620,  619,
108992  /*   390 */   145,  255,  346,  254,  577,  598,   74,  351,   45,  489,
108993  /*   400 */   587,  581,  235,  189,  464,  544,  167,  296,  187,  469,
108994  /*   410 */   479,   67,   62,   39,  618,  546,  597,  345,  573,   57,
108995  /*   420 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
108996  /*   430 */    56,   56,    6,   54,   54,   54,   54,   53,   53,   52,
108997  /*   440 */    52,   52,   51,  233,  309,  562,  558,  407,  528,  576,
108998  /*   450 */   576,  344,  255,  346,  254,  182,  617,  616,  503,  504,
108999  /*   460 */   314,  409,  557,  235,  166,  271,  409,  352,  564,  181,
109000  /*   470 */   407,  546,  576,  576,  587,  581,  412,  537,  556,  561,
109001  /*   480 */   517,  412,  618,  249,  598,   16,    7,   36,  467,  598,
109002  /*   490 */    92,  516,  618,   57,   58,   48,  579,  578,  580,  580,
109003  /*   500 */    55,   55,   56,   56,   56,   56,  541,   54,   54,   54,
109004  /*   510 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  327,
109005  /*   520 */   572,  571,  525,  558,  560,  394,  871,  246,  409,  248,
109006  /*   530 */   171,  392,  594,  219,  407,  409,  576,  576,  502,  557,
109007  /*   540 */   364,  145,  510,  412,  407,  229,  576,  576,  587,  581,
109008  /*   550 */   412,  598,   92,  381,  269,  556,  166,  400,  598,   69,
109009  /*   560 */   501,  419,  945,  199,  945,  198,  546,   57,   58,   48,
109010  /*   570 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
109011  /*   580 */   568,   54,   54,   54,   54,   53,   53,   52,   52,   52,
109012  /*   590 */    51,  233,  309,  317,  419,  944,  508,  944,  308,  597,
109013  /*   600 */   594,  565,  490,  212,  173,  247,  423,  615,  614,  613,
109014  /*   610 */   323,  197,  143,  405,  572,  571,  489,   66,   50,   47,
109015  /*   620 */   146,  594,  587,  581,  232,  231,  559,  427,   67,  555,
109016  /*   630 */    15,  618,  186,  543,  303,  421,   35,  206,  432,  423,
109017  /*   640 */   552,   57,   58,   48,  579,  578,  580,  580,   55,   55,
109018  /*   650 */    56,   56,   56,   56,  205,   54,   54,   54,   54,   53,
109019  /*   660 */    53,   52,   52,   52,   51,  233,  309,  569,  569,  260,
109020  /*   670 */   268,  597,   12,  373,  568,  166,  409,  313,  409,  420,
109021  /*   680 */   409,  473,  473,  365,  618,   50,   47,  146,  597,  594,
109022  /*   690 */   468,  412,  166,  412,  351,  412,  587,  581,   32,  598,
109023  /*   700 */    94,  598,   97,  598,   95,  627,  625,  329,  142,   50,
109024  /*   710 */    47,  146,  333,  349,  358,   57,   58,   48,  579,  578,
109025  /*   720 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
109026  /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
109027  /*   740 */   309,  409,  388,  412,  409,   22,  565,  404,  212,  362,
109028  /*   750 */   389,  598,  104,  359,  409,  156,  412,  409,  603,  412,
109029  /*   760 */   537,  331,  569,  569,  598,  103,  493,  598,  105,  412,
109030  /*   770 */   587,  581,  412,  260,  549,  618,   11,  598,  106,  521,
109031  /*   780 */   598,  133,  169,  457,  456,  170,   35,  601,  618,   57,
109032  /*   790 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
109033  /*   800 */    56,   56,  409,   54,   54,   54,   54,   53,   53,   52,
109034  /*   810 */    52,   52,   51,  233,  309,  409,  259,  412,  409,   50,
109035  /*   820 */    47,  146,  357,  318,  355,  598,  134,  527,  352,  337,
109036  /*   830 */   412,  409,  356,  412,  357,  409,  357,  618,  598,   98,
109037  /*   840 */   129,  598,  102,  618,  587,  581,  412,   21,  235,  618,
109038  /*   850 */   412,  618,  211,  143,  598,  101,   30,  167,  598,   93,
109039  /*   860 */   350,  535,  203,   57,   58,   48,  579,  578,  580,  580,
109040  /*   870 */    55,   55,   56,   56,   56,   56,  409,   54,   54,   54,
109041  /*   880 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  409,
109042  /*   890 */   526,  412,  409,  425,  215,  305,  597,  551,  141,  598,
109043  /*   900 */   100,   40,  409,   38,  412,  409,  550,  412,  409,  228,
109044  /*   910 */   220,  314,  598,   77,  500,  598,   96,  412,  587,  581,
109045  /*   920 */   412,  338,  253,  412,  218,  598,  137,  379,  598,  136,
109046  /*   930 */    28,  598,  135,  270,  715,  210,  481,   57,   58,   48,
109047  /*   940 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
109048  /*   950 */   409,   54,   54,   54,   54,   53,   53,   52,   52,   52,
109049  /*   960 */    51,  233,  309,  409,  272,  412,  409,  315,  147,  597,
109050  /*   970 */   272,  626,    2,  598,   76,  209,  409,  127,  412,  618,
109051  /*   980 */   126,  412,  409,  621,  235,  618,  598,   90,  374,  598,
109052  /*   990 */    89,  412,  587,  581,   27,  260,  350,  412,  618,  598,
109053  /*  1000 */    75,  321,  541,  541,  125,  598,   88,  320,  278,  597,
109054  /*  1010 */   618,   57,   46,   48,  579,  578,  580,  580,   55,   55,
109055  /*  1020 */    56,   56,   56,   56,  409,   54,   54,   54,   54,   53,
109056  /*  1030 */    53,   52,   52,   52,   51,  233,  309,  409,  450,  412,
109057  /*  1040 */   164,  284,  282,  272,  609,  424,  304,  598,   87,  370,
109058  /*  1050 */   409,  477,  412,  409,  608,  409,  607,  602,  618,  618,
109059  /*  1060 */   598,   99,  586,  585,  122,  412,  587,  581,  412,  618,
109060  /*  1070 */   412,  618,  618,  598,   86,  366,  598,   17,  598,   85,
109061  /*  1080 */   319,  185,  519,  518,  583,  582,   58,   48,  579,  578,
109062  /*  1090 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
109063  /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
109064  /*  1110 */   309,  584,  409,  412,  409,  260,  260,  260,  408,  591,
109065  /*  1120 */   474,  598,   84,  170,  409,  466,  518,  412,  121,  412,
109066  /*  1130 */   618,  618,  618,  618,  618,  598,   83,  598,   72,  412,
109067  /*  1140 */   587,  581,   51,  233,  625,  329,  470,  598,   71,  257,
109068  /*  1150 */   159,  120,   14,  462,  157,  158,  117,  260,  448,  447,
109069  /*  1160 */   446,   48,  579,  578,  580,  580,   55,   55,   56,   56,
109070  /*  1170 */    56,   56,  618,   54,   54,   54,   54,   53,   53,   52,
109071  /*  1180 */    52,   52,   51,  233,   44,  403,  260,    3,  409,  459,
109072  /*  1190 */   260,  413,  619,  118,  398,   10,   25,   24,  554,  348,
109073  /*  1200 */   217,  618,  406,  412,  409,  618,    4,   44,  403,  618,
109074  /*  1210 */     3,  598,   82,  618,  413,  619,  455,  542,  115,  412,
109075  /*  1220 */   538,  401,  536,  274,  506,  406,  251,  598,   81,  216,
109076  /*  1230 */   273,  563,  618,  243,  453,  618,  154,  618,  618,  618,
109077  /*  1240 */   449,  416,  623,  110,  401,  618,  409,  236,   64,  123,
109078  /*  1250 */   487,   41,   42,  531,  563,  204,  409,  267,   43,  411,
109079  /*  1260 */   410,  412,  265,  592,  108,  618,  107,  434,  332,  598,
109080  /*  1270 */    80,  412,  618,  263,   41,   42,  443,  618,  409,  598,
109081  /*  1280 */    70,   43,  411,  410,  433,  261,  592,  149,  618,  597,
109082  /*  1290 */   256,  237,  188,  412,  590,  590,  590,  589,  588,   13,
109083  /*  1300 */   618,  598,   18,  328,  235,  618,   44,  403,  360,    3,
109084  /*  1310 */   418,  461,  339,  413,  619,  227,  124,  590,  590,  590,
109085  /*  1320 */   589,  588,   13,  618,  406,  409,  618,  409,  139,   34,
109086  /*  1330 */   403,  387,    3,  148,  622,  312,  413,  619,  311,  330,
109087  /*  1340 */   412,  460,  412,  401,  180,  353,  412,  406,  598,   79,
109088  /*  1350 */   598,   78,  250,  563,  598,    9,  618,  612,  611,  610,
109089  /*  1360 */   618,    8,  452,  442,  242,  415,  401,  618,  239,  235,
109090  /*  1370 */   179,  238,  428,   41,   42,  288,  563,  618,  618,  618,
109091  /*  1380 */    43,  411,  410,  618,  144,  592,  618,  618,  177,   61,
109092  /*  1390 */   618,  596,  391,  620,  619,  287,   41,   42,  414,  618,
109093  /*  1400 */   293,   30,  393,   43,  411,  410,  292,  618,  592,   31,
109094  /*  1410 */   618,  395,  291,   60,  230,   37,  590,  590,  590,  589,
109095  /*  1420 */   588,   13,  214,  553,  183,  290,  172,  301,  300,  299,
109096  /*  1430 */   178,  297,  595,  563,  451,   29,  285,  390,  540,  590,
109097  /*  1440 */   590,  590,  589,  588,   13,  283,  520,  534,  150,  533,
109098  /*  1450 */   241,  281,  384,  192,  191,  324,  515,  514,  276,  240,
109099  /*  1460 */   510,  523,  307,  511,  128,  592,  509,  225,  226,  486,
109100  /*  1470 */   485,  224,  152,  491,  464,  306,  484,  163,  153,  371,
109101  /*  1480 */   478,  151,  162,  258,  369,  161,  367,  208,  475,  476,
109102  /*  1490 */    26,  160,  465,  140,  361,  131,  590,  590,  590,  116,
109103  /*  1500 */   119,  454,  343,  155,  114,  342,  113,  112,  445,  111,
109104  /*  1510 */   130,  109,  431,  316,  426,  430,   23,  429,   20,  606,
109105  /*  1520 */   190,  507,  255,  341,  244,   63,  294,  593,  310,  570,
109106  /*  1530 */   277,  402,  354,  235,  567,  496,  495,  492,  494,  302,
109107  /*  1540 */   458,  378,  286,  245,  566,    5,  252,  547,  193,  444,
109108  /*  1550 */   233,  340,  207,  524,  368,  505,  334,  522,  499,  399,
109109  /*  1560 */   295,  498,  956,  488,
109110 };
109111 static const YYCODETYPE yy_lookahead[] = {
109112  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
109113  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
109114  /*    20 */    89,   90,   91,   92,   26,   27,   15,   26,   27,  197,
109115  /*    30 */    49,   50,   77,   78,   79,   80,  204,   82,   83,   84,
109116  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   23,   68,
109117  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
109118  /*    60 */    79,   80,  166,   82,   83,   84,   85,   86,   87,   88,
109119  /*    70 */    89,   90,   91,   92,   19,   94,   19,  105,  106,  107,
109120  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
109121  /*    90 */    91,   92,   94,   95,   96,   94,   95,   99,  100,  101,
109122  /*   100 */   112,  205,  114,  115,   49,   50,   22,   23,  110,   54,
109123  /*   110 */    86,   87,   88,   89,   90,   91,   92,  221,  222,  223,
109124  /*   120 */    23,  120,   25,   68,   69,   70,   71,   72,   73,   74,
109125  /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,
109126  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,
109127  /*   150 */    23,   67,   25,   96,   97,   98,   99,  100,  101,  102,
109128  /*   160 */   150,   32,  150,  118,   26,   27,  109,  150,  150,  150,
109129  /*   170 */    41,  161,  162,  180,  181,  165,  113,  165,   49,   50,
109130  /*   180 */   117,  188,  165,  165,  165,  173,  174,  170,  171,  170,
109131  /*   190 */   171,  173,  174,  118,  184,   16,  186,   68,   69,   70,
109132  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
109133  /*   210 */   118,   82,   83,   84,   85,   86,   87,   88,   89,   90,
109134  /*   220 */    91,   92,   19,   98,   86,   87,   22,   24,  160,   88,
109135  /*   230 */    26,   27,   94,   95,  109,   97,  224,   66,  118,   60,
109136  /*   240 */   150,   62,  104,   23,  106,   25,  229,  230,  229,  230,
109137  /*   250 */   160,  150,   49,   50,  113,  165,   96,   26,  117,   99,
109138  /*   260 */   100,  101,  194,  173,  174,   94,  165,  129,  130,   98,
109139  /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,
109140  /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
109141  /*   290 */    87,   88,   89,   90,   91,   92,   19,   11,   94,   95,
109142  /*   300 */   129,  130,  131,  118,  150,  215,  150,  150,  150,   25,
109143  /*   310 */   220,   26,   27,   22,  213,   26,   27,   26,   27,  165,
109144  /*   320 */    25,  165,  165,  165,   30,   94,   49,   50,   34,  173,
109145  /*   330 */   174,  173,  174,   88,   89,   90,   91,   92,    7,    8,
109146  /*   340 */   160,  187,   48,   57,  187,   68,   69,   70,   71,   72,
109147  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
109148  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
109149  /*   370 */    19,  215,  150,  215,  194,   19,  220,   88,  220,   94,
109150  /*   380 */    95,   23,  160,   94,   95,   94,   95,  165,   26,   27,
109151  /*   390 */    95,  105,  106,  107,  113,  173,  174,  217,   22,  150,
109152  /*   400 */    49,   50,  116,  119,   57,  120,   50,  158,   22,   21,
109153  /*   410 */   161,  162,  232,  136,  165,  120,  194,  237,   23,   68,
109154  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
109155  /*   430 */    79,   80,   22,   82,   83,   84,   85,   86,   87,   88,
109156  /*   440 */    89,   90,   91,   92,   19,   23,   12,  112,   23,  114,
109157  /*   450 */   115,   63,  105,  106,  107,   23,   94,   95,   97,   98,
109158  /*   460 */   104,  150,   28,  116,   25,  109,  150,  150,   23,   23,
109159  /*   470 */   112,   25,  114,  115,   49,   50,  165,  150,   44,   11,
109160  /*   480 */    46,  165,  165,   16,  173,  174,   76,  136,  100,  173,
109161  /*   490 */   174,   57,  165,   68,   69,   70,   71,   72,   73,   74,
109162  /*   500 */    75,   76,   77,   78,   79,   80,  166,   82,   83,   84,
109163  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  169,
109164  /*   520 */   170,  171,   23,   12,   23,  214,  138,   60,  150,   62,
109165  /*   530 */    24,  215,   26,  216,  112,  150,  114,  115,   36,   28,
109166  /*   540 */   213,   95,  103,  165,  112,  205,  114,  115,   49,   50,
109167  /*   550 */   165,  173,  174,   51,   23,   44,   25,   46,  173,  174,
109168  /*   560 */    58,   22,   23,   22,   25,  160,  120,   68,   69,   70,
109169  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
109170  /*   580 */   230,   82,   83,   84,   85,   86,   87,   88,   89,   90,
109171  /*   590 */    91,   92,   19,  215,   22,   23,   23,   25,  163,  194,
109172  /*   600 */    94,  166,  167,  168,   25,  138,   67,    7,    8,    9,
109173  /*   610 */   108,  206,  207,  169,  170,  171,  150,   22,  221,  222,
109174  /*   620 */   223,   26,   49,   50,   86,   87,   23,  161,  162,   23,
109175  /*   630 */    22,  165,   24,  120,   22,   23,   25,  160,  241,   67,
109176  /*   640 */   176,   68,   69,   70,   71,   72,   73,   74,   75,   76,
109177  /*   650 */    77,   78,   79,   80,  160,   82,   83,   84,   85,   86,
109178  /*   660 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  150,
109179  /*   670 */    23,  194,   35,   23,  230,   25,  150,  155,  150,   67,
109180  /*   680 */   150,  105,  106,  107,  165,  221,  222,  223,  194,   94,
109181  /*   690 */    23,  165,   25,  165,  217,  165,   49,   50,   25,  173,
109182  /*   700 */   174,  173,  174,  173,  174,    0,    1,    2,  118,  221,
109183  /*   710 */   222,  223,  193,  219,  237,   68,   69,   70,   71,   72,
109184  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
109185  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
109186  /*   740 */    19,  150,   19,  165,  150,   24,  166,  167,  168,  227,
109187  /*   750 */    27,  173,  174,  231,  150,   25,  165,  150,  172,  165,
109188  /*   760 */   150,  242,  129,  130,  173,  174,  180,  173,  174,  165,
109189  /*   770 */    49,   50,  165,  150,  176,  165,   35,  173,  174,  165,
109190  /*   780 */   173,  174,   35,   23,   23,   25,   25,  173,  165,   68,
109191  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
109192  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
109193  /*   810 */    89,   90,   91,   92,   19,  150,  193,  165,  150,  221,
109194  /*   820 */   222,  223,  150,  213,   19,  173,  174,   23,  150,   97,
109195  /*   830 */   165,  150,   27,  165,  150,  150,  150,  165,  173,  174,
109196  /*   840 */    22,  173,  174,  165,   49,   50,  165,   52,  116,  165,
109197  /*   850 */   165,  165,  206,  207,  173,  174,  126,   50,  173,  174,
109198  /*   860 */   128,   27,  160,   68,   69,   70,   71,   72,   73,   74,
109199  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
109200  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
109201  /*   890 */    23,  165,  150,   23,  216,   25,  194,   32,   39,  173,
109202  /*   900 */   174,  135,  150,  137,  165,  150,   41,  165,  150,   52,
109203  /*   910 */   238,  104,  173,  174,   29,  173,  174,  165,   49,   50,
109204  /*   920 */   165,  219,  238,  165,  238,  173,  174,   52,  173,  174,
109205  /*   930 */    22,  173,  174,   23,   23,  160,   25,   68,   69,   70,
109206  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
109207  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
109208  /*   960 */    91,   92,   19,  150,  150,  165,  150,  245,  246,  194,
109209  /*   970 */   150,  144,  145,  173,  174,  160,  150,   22,  165,  165,
109210  /*   980 */    22,  165,  150,  150,  116,  165,  173,  174,   52,  173,
109211  /*   990 */   174,  165,   49,   50,   22,  150,  128,  165,  165,  173,
109212  /*  1000 */   174,  187,  166,  166,   22,  173,  174,  187,  109,  194,
109213  /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,
109214  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
109215  /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,
109216  /*  1040 */   102,  205,  205,  150,  150,  247,  248,  173,  174,   19,
109217  /*  1050 */   150,   20,  165,  150,  150,  150,  150,  150,  165,  165,
109218  /*  1060 */   173,  174,   49,   50,  104,  165,   49,   50,  165,  165,
109219  /*  1070 */   165,  165,  165,  173,  174,   43,  173,  174,  173,  174,
109220  /*  1080 */   187,   24,  190,  191,   71,   72,   69,   70,   71,   72,
109221  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
109222  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
109223  /*  1110 */    19,   98,  150,  165,  150,  150,  150,  150,  150,  150,
109224  /*  1120 */    59,  173,  174,   25,  150,  190,  191,  165,   53,  165,
109225  /*  1130 */   165,  165,  165,  165,  165,  173,  174,  173,  174,  165,
109226  /*  1140 */    49,   50,   91,   92,    1,    2,   53,  173,  174,  138,
109227  /*  1150 */   104,   22,    5,    1,   35,  118,  127,  150,  193,  193,
109228  /*  1160 */   193,   70,   71,   72,   73,   74,   75,   76,   77,   78,
109229  /*  1170 */    79,   80,  165,   82,   83,   84,   85,   86,   87,   88,
109230  /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,   27,
109231  /*  1190 */   150,   26,   27,  108,  150,   22,   76,   76,  150,   25,
109232  /*  1200 */   193,  165,   37,  165,  150,  165,   22,   19,   20,  165,
109233  /*  1210 */    22,  173,  174,  165,   26,   27,   23,  150,  119,  165,
109234  /*  1220 */   150,   56,  150,  150,  150,   37,   16,  173,  174,  193,
109235  /*  1230 */   150,   66,  165,  193,    1,  165,  121,  165,  165,  165,
109236  /*  1240 */    20,  146,  147,  119,   56,  165,  150,  152,   16,  154,
109237  /*  1250 */   150,   86,   87,   88,   66,  160,  150,  150,   93,   94,
109238  /*  1260 */    95,  165,  150,   98,  108,  165,  127,   23,   65,  173,
109239  /*  1270 */   174,  165,  165,  150,   86,   87,  128,  165,  150,  173,
109240  /*  1280 */   174,   93,   94,   95,   23,  150,   98,   15,  165,  194,
109241  /*  1290 */   150,  140,   22,  165,  129,  130,  131,  132,  133,  134,
109242  /*  1300 */   165,  173,  174,    3,  116,  165,   19,   20,  150,   22,
109243  /*  1310 */     4,  150,  217,   26,   27,  179,  179,  129,  130,  131,
109244  /*  1320 */   132,  133,  134,  165,   37,  150,  165,  150,  164,   19,
109245  /*  1330 */    20,  150,   22,  246,  149,  249,   26,   27,  249,  244,
109246  /*  1340 */   165,  150,  165,   56,    6,  150,  165,   37,  173,  174,
109247  /*  1350 */   173,  174,  150,   66,  173,  174,  165,  149,  149,   13,
109248  /*  1360 */   165,   25,  150,  150,  150,  149,   56,  165,  150,  116,
109249  /*  1370 */   151,  150,  150,   86,   87,  150,   66,  165,  165,  165,
109250  /*  1380 */    93,   94,   95,  165,  150,   98,  165,  165,  151,   22,
109251  /*  1390 */   165,  194,  150,   26,   27,  150,   86,   87,  159,  165,
109252  /*  1400 */   199,  126,  123,   93,   94,   95,  200,  165,   98,  124,
109253  /*  1410 */   165,  122,  201,  125,  225,  135,  129,  130,  131,  132,
109254  /*  1420 */   133,  134,    5,  157,  157,  202,  118,   10,   11,   12,
109255  /*  1430 */    13,   14,  203,   66,   17,  104,  210,  121,  211,  129,
109256  /*  1440 */   130,  131,  132,  133,  134,  210,  175,  211,   31,  211,
109257  /*  1450 */    33,  210,  104,   86,   87,   47,  175,  183,  175,   42,
109258  /*  1460 */   103,   94,  178,  177,   22,   98,  175,   92,  228,  175,
109259  /*  1470 */   175,  228,   55,  183,   57,  178,  175,  156,   61,   18,
109260  /*  1480 */   157,   64,  156,  235,  157,  156,   45,  157,  236,  157,
109261  /*  1490 */   135,  156,  189,   68,  157,  218,  129,  130,  131,   22,
109262  /*  1500 */   189,  199,  157,  156,  192,   18,  192,  192,  199,  192,
109263  /*  1510 */   218,  189,   40,  157,   38,  157,  240,  157,  240,  153,
109264  /*  1520 */   196,  181,  105,  106,  107,  243,  198,  166,  111,  230,
109265  /*  1530 */   176,  226,  239,  116,  230,  176,  166,  166,  176,  148,
109266  /*  1540 */   199,  177,  209,  209,  166,  196,  239,  208,  185,  199,
109267  /*  1550 */    92,  209,  233,  173,  234,  182,  139,  173,  182,  191,
109268  /*  1560 */   195,  182,  250,  186,
109269 };
109270 #define YY_SHIFT_USE_DFLT (-70)
109271 #define YY_SHIFT_COUNT (416)
109272 #define YY_SHIFT_MIN   (-69)
109273 #define YY_SHIFT_MAX   (1487)
109274 static const short yy_shift_ofst[] = {
109275  /*     0 */  1143, 1188, 1417, 1188, 1287, 1287,  138,  138,   -2,  -19,
109276  /*    10 */  1287, 1287, 1287, 1287,  347,  362,  129,  129,  795, 1165,
109277  /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
109278  /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
109279  /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
109280  /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
109281  /*    60 */  1287, 1287,  286,  362,  362,  538,  538,  231, 1253,   55,
109282  /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,
109283  /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,
109284  /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,
109285  /*   100 */   -45,  -45,  -45,  -45,   -1,   24,  245,  362,  362,  362,
109286  /*   110 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
109287  /*   120 */   362,  362,  362,  388,  356,  362,  362,  362,  362,  362,
109288  /*   130 */   732,  868,  231, 1051, 1458,  -70,  -70,  -70, 1367,   57,
109289  /*   140 */   434,  434,  289,  291,  285,    1,  204,  572,  539,  362,
109290  /*   150 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
109291  /*   160 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
109292  /*   170 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
109293  /*   180 */   362,  506,  506,  506,  705, 1253, 1253, 1253,  -70,  -70,
109294  /*   190 */   -70,  171,  171,  160,  502,  502,  502,  446,  432,  511,
109295  /*   200 */   422,  358,  335,  -12,  -12,  -12,  -12,  576,  294,  -12,
109296  /*   210 */   -12,  295,  595,  141,  600,  730,  723,  723,  805,  730,
109297  /*   220 */   805,  439,  911,  231,  865,  231,  865,  807,  865,  723,
109298  /*   230 */   766,  633,  633,  231,  284,   63,  608, 1476, 1308, 1308,
109299  /*   240 */  1472, 1472, 1308, 1477, 1425, 1275, 1487, 1487, 1487, 1487,
109300  /*   250 */  1308, 1461, 1275, 1477, 1425, 1425, 1308, 1461, 1355, 1441,
109301  /*   260 */  1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348, 1348,
109302  /*   270 */  1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408, 1348,
109303  /*   280 */  1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308, 1280,
109304  /*   290 */  1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346, 1338,
109305  /*   300 */  1338, 1338, 1338,  -70,  -70,  -70,  -70,  -70,  -70, 1013,
109306  /*   310 */   467,  612,   84,  179,  -28,  870,  410,  761,  760,  667,
109307  /*   320 */   650,  531,  220,  361,  331,  125,  127,   97, 1306, 1300,
109308  /*   330 */  1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174, 1139,
109309  /*   340 */  1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184, 1174,
109310  /*   350 */  1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152, 1147,
109311  /*   360 */  1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032,  960, 1057,
109312  /*   370 */  1031, 1030,  899,  938,  982,  936,  972,  958,  910,  955,
109313  /*   380 */   875,  885,  908,  857,  859,  867,  804,  590,  834,  747,
109314  /*   390 */   818,  513,  611,  741,  673,  637,  611,  606,  603,  579,
109315  /*   400 */   501,  541,  468,  386,  445,  395,  376,  281,  185,  120,
109316  /*   410 */    92,   75,   45,  114,   25,   11,    5,
109317 };
109318 #define YY_REDUCE_USE_DFLT (-169)
109319 #define YY_REDUCE_COUNT (308)
109320 #define YY_REDUCE_MIN   (-168)
109321 #define YY_REDUCE_MAX   (1391)
109322 static const short yy_reduce_ofst[] = {
109323  /*     0 */  -141,   90, 1095,  222,  158,  156,   19,   17,   10, -104,
109324  /*    10 */   378,  316,  311,   12,  180,  249,  598,  464,  397, 1181,
109325  /*    20 */  1177, 1175, 1128, 1106, 1096, 1054, 1038,  974,  964,  962,
109326  /*    30 */   948,  905,  903,  900,  887,  874,  832,  826,  816,  813,
109327  /*    40 */   800,  758,  755,  752,  742,  739,  726,  685,  681,  668,
109328  /*    50 */   665,  652,  607,  604,  594,  591,  578,  530,  528,  526,
109329  /*    60 */   385,   18,  477,  466,  519,  444,  350,  435,  405,  488,
109330  /*    70 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
109331  /*    80 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
109332  /*    90 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
109333  /*   100 */   488,  488,  488,  488,  488,  488,  488, 1040,  678, 1036,
109334  /*   110 */  1007,  967,  966,  965,  845,  686,  610,  684,  317,  672,
109335  /*   120 */   893,  327,  623,  522,   -7,  820,  814,  157,  154,  101,
109336  /*   130 */   702,  494,  580,  488,  488,  488,  488,  488,  614,  586,
109337  /*   140 */   935,  892,  968, 1245, 1242, 1234, 1225,  798,  798, 1222,
109338  /*   150 */  1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
109339  /*   160 */  1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
109340  /*   170 */  1070, 1067, 1048, 1044,  969,  968,  907,  906,  904,  894,
109341  /*   180 */   833,  837,  836,  340,  827,  815,  775,   68,  722,  646,
109342  /*   190 */  -168, 1384, 1380, 1377, 1379, 1376, 1373, 1339, 1365, 1368,
109343  /*   200 */  1365, 1365, 1365, 1365, 1365, 1365, 1365, 1320, 1319, 1365,
109344  /*   210 */  1365, 1339, 1378, 1349, 1391, 1350, 1342, 1334, 1307, 1341,
109345  /*   220 */  1293, 1364, 1363, 1371, 1362, 1370, 1359, 1340, 1354, 1333,
109346  /*   230 */  1305, 1304, 1299, 1361, 1328, 1324, 1366, 1282, 1360, 1358,
109347  /*   240 */  1278, 1276, 1356, 1292, 1322, 1309, 1317, 1315, 1314, 1312,
109348  /*   250 */  1345, 1347, 1302, 1277, 1311, 1303, 1337, 1335, 1252, 1248,
109349  /*   260 */  1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301, 1295,
109350  /*   270 */  1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274, 1281,
109351  /*   280 */  1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266, 1189,
109352  /*   290 */  1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219, 1216,
109353  /*   300 */  1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
109354 };
109355 static const YYACTIONTYPE yy_default[] = {
109356  /*     0 */   632,  866,  954,  954,  866,  866,  954,  954,  954,  756,
109357  /*    10 */   954,  954,  954,  864,  954,  954,  784,  784,  928,  954,
109358  /*    20 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109359  /*    30 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109360  /*    40 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109361  /*    50 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109362  /*    60 */   954,  954,  954,  954,  954,  954,  954,  671,  760,  790,
109363  /*    70 */   954,  954,  954,  954,  954,  954,  954,  954,  927,  929,
109364  /*    80 */   798,  797,  907,  771,  795,  788,  792,  867,  860,  861,
109365  /*    90 */   859,  863,  868,  954,  791,  827,  844,  826,  838,  843,
109366  /*   100 */   850,  842,  839,  829,  828,  830,  831,  954,  954,  954,
109367  /*   110 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109368  /*   120 */   954,  954,  954,  658,  725,  954,  954,  954,  954,  954,
109369  /*   130 */   954,  954,  954,  832,  833,  847,  846,  845,  954,  663,
109370  /*   140 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109371  /*   150 */   934,  932,  954,  879,  954,  954,  954,  954,  954,  954,
109372  /*   160 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109373  /*   170 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109374  /*   180 */   638,  756,  756,  756,  632,  954,  954,  954,  946,  760,
109375  /*   190 */   750,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109376  /*   200 */   954,  954,  954,  800,  739,  917,  919,  954,  900,  737,
109377  /*   210 */   660,  758,  673,  748,  640,  794,  773,  773,  912,  794,
109378  /*   220 */   912,  696,  719,  954,  784,  954,  784,  693,  784,  773,
109379  /*   230 */   862,  954,  954,  954,  757,  748,  954,  939,  764,  764,
109380  /*   240 */   931,  931,  764,  806,  729,  794,  736,  736,  736,  736,
109381  /*   250 */   764,  655,  794,  806,  729,  729,  764,  655,  906,  904,
109382  /*   260 */   764,  764,  655,  764,  655,  764,  655,  872,  727,  727,
109383  /*   270 */   727,  711,  876,  876,  872,  727,  696,  727,  711,  727,
109384  /*   280 */   727,  777,  772,  777,  772,  777,  772,  764,  764,  954,
109385  /*   290 */   789,  778,  787,  785,  794,  954,  714,  648,  648,  637,
109386  /*   300 */   637,  637,  637,  951,  951,  946,  698,  698,  681,  954,
109387  /*   310 */   954,  954,  954,  954,  954,  954,  881,  954,  954,  954,
109388  /*   320 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  633,
109389  /*   330 */   941,  954,  954,  938,  954,  954,  954,  954,  799,  954,
109390  /*   340 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  916,
109391  /*   350 */   954,  954,  954,  954,  954,  954,  954,  910,  954,  954,
109392  /*   360 */   954,  954,  954,  954,  903,  902,  954,  954,  954,  954,
109393  /*   370 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109394  /*   380 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109395  /*   390 */   954,  954,  786,  954,  779,  954,  865,  954,  954,  954,
109396  /*   400 */   954,  954,  954,  954,  954,  954,  954,  742,  815,  954,
109397  /*   410 */   814,  818,  813,  665,  954,  646,  954,  629,  634,  950,
109398  /*   420 */   953,  952,  949,  948,  947,  942,  940,  937,  936,  935,
109399  /*   430 */   933,  930,  926,  885,  883,  890,  889,  888,  887,  886,
109400  /*   440 */   884,  882,  880,  801,  796,  793,  925,  878,  738,  735,
109401  /*   450 */   734,  654,  943,  909,  918,  805,  804,  807,  915,  914,
109402  /*   460 */   913,  911,  908,  895,  803,  802,  730,  870,  869,  657,
109403  /*   470 */   899,  898,  897,  901,  905,  896,  766,  656,  653,  662,
109404  /*   480 */   717,  718,  726,  724,  723,  722,  721,  720,  716,  664,
109405  /*   490 */   672,  710,  695,  694,  875,  877,  874,  873,  703,  702,
109406  /*   500 */   708,  707,  706,  705,  704,  701,  700,  699,  692,  691,
109407  /*   510 */   697,  690,  713,  712,  709,  689,  733,  732,  731,  728,
109408  /*   520 */   688,  687,  686,  818,  685,  684,  824,  823,  811,  854,
109409  /*   530 */   753,  752,  751,  763,  762,  775,  774,  809,  808,  776,
109410  /*   540 */   761,  755,  754,  770,  769,  768,  767,  759,  749,  781,
109411  /*   550 */   783,  782,  780,  856,  765,  853,  924,  923,  922,  921,
109412  /*   560 */   920,  858,  857,  825,  822,  676,  677,  893,  892,  894,
109413  /*   570 */   891,  679,  678,  675,  674,  855,  744,  743,  851,  848,
109414  /*   580 */   840,  836,  852,  849,  841,  837,  835,  834,  820,  819,
109415  /*   590 */   817,  816,  812,  821,  667,  745,  741,  740,  810,  747,
109416  /*   600 */   746,  683,  682,  680,  661,  659,  652,  650,  649,  651,
109417  /*   610 */   647,  645,  644,  643,  642,  641,  670,  669,  668,  666,
109418  /*   620 */   665,  639,  636,  635,  631,  630,  628,
109419 };
109420
109421 /* The next table maps tokens into fallback tokens.  If a construct
109422 ** like the following:
109423 ** 
109424 **      %fallback ID X Y Z.
109425 **
109426 ** appears in the grammar, then ID becomes a fallback token for X, Y,
109427 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
109428 ** but it does not parse, the type of the token is changed to ID and
109429 ** the parse is retried before an error is thrown.
109430 */
109431 #ifdef YYFALLBACK
109432 static const YYCODETYPE yyFallback[] = {
109433     0,  /*          $ => nothing */
109434     0,  /*       SEMI => nothing */
109435    26,  /*    EXPLAIN => ID */
109436    26,  /*      QUERY => ID */
109437    26,  /*       PLAN => ID */
109438    26,  /*      BEGIN => ID */
109439     0,  /* TRANSACTION => nothing */
109440    26,  /*   DEFERRED => ID */
109441    26,  /*  IMMEDIATE => ID */
109442    26,  /*  EXCLUSIVE => ID */
109443     0,  /*     COMMIT => nothing */
109444    26,  /*        END => ID */
109445    26,  /*   ROLLBACK => ID */
109446    26,  /*  SAVEPOINT => ID */
109447    26,  /*    RELEASE => ID */
109448     0,  /*         TO => nothing */
109449     0,  /*      TABLE => nothing */
109450     0,  /*     CREATE => nothing */
109451    26,  /*         IF => ID */
109452     0,  /*        NOT => nothing */
109453     0,  /*     EXISTS => nothing */
109454    26,  /*       TEMP => ID */
109455     0,  /*         LP => nothing */
109456     0,  /*         RP => nothing */
109457     0,  /*         AS => nothing */
109458     0,  /*      COMMA => nothing */
109459     0,  /*         ID => nothing */
109460     0,  /*    INDEXED => nothing */
109461    26,  /*      ABORT => ID */
109462    26,  /*     ACTION => ID */
109463    26,  /*      AFTER => ID */
109464    26,  /*    ANALYZE => ID */
109465    26,  /*        ASC => ID */
109466    26,  /*     ATTACH => ID */
109467    26,  /*     BEFORE => ID */
109468    26,  /*         BY => ID */
109469    26,  /*    CASCADE => ID */
109470    26,  /*       CAST => ID */
109471    26,  /*   COLUMNKW => ID */
109472    26,  /*   CONFLICT => ID */
109473    26,  /*   DATABASE => ID */
109474    26,  /*       DESC => ID */
109475    26,  /*     DETACH => ID */
109476    26,  /*       EACH => ID */
109477    26,  /*       FAIL => ID */
109478    26,  /*        FOR => ID */
109479    26,  /*     IGNORE => ID */
109480    26,  /*  INITIALLY => ID */
109481    26,  /*    INSTEAD => ID */
109482    26,  /*    LIKE_KW => ID */
109483    26,  /*      MATCH => ID */
109484    26,  /*         NO => ID */
109485    26,  /*        KEY => ID */
109486    26,  /*         OF => ID */
109487    26,  /*     OFFSET => ID */
109488    26,  /*     PRAGMA => ID */
109489    26,  /*      RAISE => ID */
109490    26,  /*    REPLACE => ID */
109491    26,  /*   RESTRICT => ID */
109492    26,  /*        ROW => ID */
109493    26,  /*    TRIGGER => ID */
109494    26,  /*     VACUUM => ID */
109495    26,  /*       VIEW => ID */
109496    26,  /*    VIRTUAL => ID */
109497    26,  /*    REINDEX => ID */
109498    26,  /*     RENAME => ID */
109499    26,  /*   CTIME_KW => ID */
109500 };
109501 #endif /* YYFALLBACK */
109502
109503 /* The following structure represents a single element of the
109504 ** parser's stack.  Information stored includes:
109505 **
109506 **   +  The state number for the parser at this level of the stack.
109507 **
109508 **   +  The value of the token stored at this level of the stack.
109509 **      (In other words, the "major" token.)
109510 **
109511 **   +  The semantic value stored at this level of the stack.  This is
109512 **      the information used by the action routines in the grammar.
109513 **      It is sometimes called the "minor" token.
109514 */
109515 struct yyStackEntry {
109516   YYACTIONTYPE stateno;  /* The state-number */
109517   YYCODETYPE major;      /* The major token value.  This is the code
109518                          ** number for the token at this stack level */
109519   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
109520                          ** is the value of the token  */
109521 };
109522 typedef struct yyStackEntry yyStackEntry;
109523
109524 /* The state of the parser is completely contained in an instance of
109525 ** the following structure */
109526 struct yyParser {
109527   int yyidx;                    /* Index of top element in stack */
109528 #ifdef YYTRACKMAXSTACKDEPTH
109529   int yyidxMax;                 /* Maximum value of yyidx */
109530 #endif
109531   int yyerrcnt;                 /* Shifts left before out of the error */
109532   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
109533 #if YYSTACKDEPTH<=0
109534   int yystksz;                  /* Current side of the stack */
109535   yyStackEntry *yystack;        /* The parser's stack */
109536 #else
109537   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
109538 #endif
109539 };
109540 typedef struct yyParser yyParser;
109541
109542 #ifndef NDEBUG
109543 /* #include <stdio.h> */
109544 static FILE *yyTraceFILE = 0;
109545 static char *yyTracePrompt = 0;
109546 #endif /* NDEBUG */
109547
109548 #ifndef NDEBUG
109549 /* 
109550 ** Turn parser tracing on by giving a stream to which to write the trace
109551 ** and a prompt to preface each trace message.  Tracing is turned off
109552 ** by making either argument NULL 
109553 **
109554 ** Inputs:
109555 ** <ul>
109556 ** <li> A FILE* to which trace output should be written.
109557 **      If NULL, then tracing is turned off.
109558 ** <li> A prefix string written at the beginning of every
109559 **      line of trace output.  If NULL, then tracing is
109560 **      turned off.
109561 ** </ul>
109562 **
109563 ** Outputs:
109564 ** None.
109565 */
109566 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
109567   yyTraceFILE = TraceFILE;
109568   yyTracePrompt = zTracePrompt;
109569   if( yyTraceFILE==0 ) yyTracePrompt = 0;
109570   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
109571 }
109572 #endif /* NDEBUG */
109573
109574 #ifndef NDEBUG
109575 /* For tracing shifts, the names of all terminals and nonterminals
109576 ** are required.  The following table supplies these names */
109577 static const char *const yyTokenName[] = { 
109578   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
109579   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
109580   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
109581   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
109582   "TABLE",         "CREATE",        "IF",            "NOT",         
109583   "EXISTS",        "TEMP",          "LP",            "RP",          
109584   "AS",            "COMMA",         "ID",            "INDEXED",     
109585   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
109586   "ASC",           "ATTACH",        "BEFORE",        "BY",          
109587   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
109588   "DATABASE",      "DESC",          "DETACH",        "EACH",        
109589   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
109590   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
109591   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
109592   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
109593   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
109594   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
109595   "OR",            "AND",           "IS",            "BETWEEN",     
109596   "IN",            "ISNULL",        "NOTNULL",       "NE",          
109597   "EQ",            "GT",            "LE",            "LT",          
109598   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
109599   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
109600   "STAR",          "SLASH",         "REM",           "CONCAT",      
109601   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
109602   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
109603   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
109604   "ON",            "INSERT",        "DELETE",        "UPDATE",      
109605   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
109606   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
109607   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
109608   "JOIN",          "USING",         "ORDER",         "GROUP",       
109609   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
109610   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
109611   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
109612   "THEN",          "ELSE",          "INDEX",         "ALTER",       
109613   "ADD",           "error",         "input",         "cmdlist",     
109614   "ecmd",          "explain",       "cmdx",          "cmd",         
109615   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
109616   "create_table",  "create_table_args",  "createkw",      "temp",        
109617   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
109618   "select",        "column",        "columnid",      "type",        
109619   "carglist",      "id",            "ids",           "typetoken",   
109620   "typename",      "signed",        "plus_num",      "minus_num",   
109621   "ccons",         "term",          "expr",          "onconf",      
109622   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",     
109623   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
109624   "conslist",      "tconscomma",    "tcons",         "idxlist",     
109625   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
109626   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
109627   "distinct",      "selcollist",    "from",          "where_opt",   
109628   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
109629   "sclp",          "as",            "seltablist",    "stl_prefix",  
109630   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
109631   "joinop2",       "inscollist",    "sortlist",      "nexprlist",   
109632   "setlist",       "insert_cmd",    "inscollist_opt",  "valuelist",   
109633   "exprlist",      "likeop",        "between_op",    "in_op",       
109634   "case_operand",  "case_exprlist",  "case_else",     "uniqueflag",  
109635   "collate",       "nmnum",         "number",        "trigger_decl",
109636   "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
109637   "when_clause",   "trigger_cmd",   "trnm",          "tridxby",     
109638   "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
109639   "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
109640   "lp",            "anylist",     
109641 };
109642 #endif /* NDEBUG */
109643
109644 #ifndef NDEBUG
109645 /* For tracing reduce actions, the names of all rules are required.
109646 */
109647 static const char *const yyRuleName[] = {
109648  /*   0 */ "input ::= cmdlist",
109649  /*   1 */ "cmdlist ::= cmdlist ecmd",
109650  /*   2 */ "cmdlist ::= ecmd",
109651  /*   3 */ "ecmd ::= SEMI",
109652  /*   4 */ "ecmd ::= explain cmdx SEMI",
109653  /*   5 */ "explain ::=",
109654  /*   6 */ "explain ::= EXPLAIN",
109655  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
109656  /*   8 */ "cmdx ::= cmd",
109657  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
109658  /*  10 */ "trans_opt ::=",
109659  /*  11 */ "trans_opt ::= TRANSACTION",
109660  /*  12 */ "trans_opt ::= TRANSACTION nm",
109661  /*  13 */ "transtype ::=",
109662  /*  14 */ "transtype ::= DEFERRED",
109663  /*  15 */ "transtype ::= IMMEDIATE",
109664  /*  16 */ "transtype ::= EXCLUSIVE",
109665  /*  17 */ "cmd ::= COMMIT trans_opt",
109666  /*  18 */ "cmd ::= END trans_opt",
109667  /*  19 */ "cmd ::= ROLLBACK trans_opt",
109668  /*  20 */ "savepoint_opt ::= SAVEPOINT",
109669  /*  21 */ "savepoint_opt ::=",
109670  /*  22 */ "cmd ::= SAVEPOINT nm",
109671  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
109672  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
109673  /*  25 */ "cmd ::= create_table create_table_args",
109674  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
109675  /*  27 */ "createkw ::= CREATE",
109676  /*  28 */ "ifnotexists ::=",
109677  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
109678  /*  30 */ "temp ::= TEMP",
109679  /*  31 */ "temp ::=",
109680  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
109681  /*  33 */ "create_table_args ::= AS select",
109682  /*  34 */ "columnlist ::= columnlist COMMA column",
109683  /*  35 */ "columnlist ::= column",
109684  /*  36 */ "column ::= columnid type carglist",
109685  /*  37 */ "columnid ::= nm",
109686  /*  38 */ "id ::= ID",
109687  /*  39 */ "id ::= INDEXED",
109688  /*  40 */ "ids ::= ID|STRING",
109689  /*  41 */ "nm ::= id",
109690  /*  42 */ "nm ::= STRING",
109691  /*  43 */ "nm ::= JOIN_KW",
109692  /*  44 */ "type ::=",
109693  /*  45 */ "type ::= typetoken",
109694  /*  46 */ "typetoken ::= typename",
109695  /*  47 */ "typetoken ::= typename LP signed RP",
109696  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
109697  /*  49 */ "typename ::= ids",
109698  /*  50 */ "typename ::= typename ids",
109699  /*  51 */ "signed ::= plus_num",
109700  /*  52 */ "signed ::= minus_num",
109701  /*  53 */ "carglist ::= carglist ccons",
109702  /*  54 */ "carglist ::=",
109703  /*  55 */ "ccons ::= CONSTRAINT nm",
109704  /*  56 */ "ccons ::= DEFAULT term",
109705  /*  57 */ "ccons ::= DEFAULT LP expr RP",
109706  /*  58 */ "ccons ::= DEFAULT PLUS term",
109707  /*  59 */ "ccons ::= DEFAULT MINUS term",
109708  /*  60 */ "ccons ::= DEFAULT id",
109709  /*  61 */ "ccons ::= NULL onconf",
109710  /*  62 */ "ccons ::= NOT NULL onconf",
109711  /*  63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
109712  /*  64 */ "ccons ::= UNIQUE onconf",
109713  /*  65 */ "ccons ::= CHECK LP expr RP",
109714  /*  66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
109715  /*  67 */ "ccons ::= defer_subclause",
109716  /*  68 */ "ccons ::= COLLATE ids",
109717  /*  69 */ "autoinc ::=",
109718  /*  70 */ "autoinc ::= AUTOINCR",
109719  /*  71 */ "refargs ::=",
109720  /*  72 */ "refargs ::= refargs refarg",
109721  /*  73 */ "refarg ::= MATCH nm",
109722  /*  74 */ "refarg ::= ON INSERT refact",
109723  /*  75 */ "refarg ::= ON DELETE refact",
109724  /*  76 */ "refarg ::= ON UPDATE refact",
109725  /*  77 */ "refact ::= SET NULL",
109726  /*  78 */ "refact ::= SET DEFAULT",
109727  /*  79 */ "refact ::= CASCADE",
109728  /*  80 */ "refact ::= RESTRICT",
109729  /*  81 */ "refact ::= NO ACTION",
109730  /*  82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
109731  /*  83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
109732  /*  84 */ "init_deferred_pred_opt ::=",
109733  /*  85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
109734  /*  86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
109735  /*  87 */ "conslist_opt ::=",
109736  /*  88 */ "conslist_opt ::= COMMA conslist",
109737  /*  89 */ "conslist ::= conslist tconscomma tcons",
109738  /*  90 */ "conslist ::= tcons",
109739  /*  91 */ "tconscomma ::= COMMA",
109740  /*  92 */ "tconscomma ::=",
109741  /*  93 */ "tcons ::= CONSTRAINT nm",
109742  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
109743  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
109744  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
109745  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
109746  /*  98 */ "defer_subclause_opt ::=",
109747  /*  99 */ "defer_subclause_opt ::= defer_subclause",
109748  /* 100 */ "onconf ::=",
109749  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
109750  /* 102 */ "orconf ::=",
109751  /* 103 */ "orconf ::= OR resolvetype",
109752  /* 104 */ "resolvetype ::= raisetype",
109753  /* 105 */ "resolvetype ::= IGNORE",
109754  /* 106 */ "resolvetype ::= REPLACE",
109755  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
109756  /* 108 */ "ifexists ::= IF EXISTS",
109757  /* 109 */ "ifexists ::=",
109758  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
109759  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
109760  /* 112 */ "cmd ::= select",
109761  /* 113 */ "select ::= oneselect",
109762  /* 114 */ "select ::= select multiselect_op oneselect",
109763  /* 115 */ "multiselect_op ::= UNION",
109764  /* 116 */ "multiselect_op ::= UNION ALL",
109765  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
109766  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
109767  /* 119 */ "distinct ::= DISTINCT",
109768  /* 120 */ "distinct ::= ALL",
109769  /* 121 */ "distinct ::=",
109770  /* 122 */ "sclp ::= selcollist COMMA",
109771  /* 123 */ "sclp ::=",
109772  /* 124 */ "selcollist ::= sclp expr as",
109773  /* 125 */ "selcollist ::= sclp STAR",
109774  /* 126 */ "selcollist ::= sclp nm DOT STAR",
109775  /* 127 */ "as ::= AS nm",
109776  /* 128 */ "as ::= ids",
109777  /* 129 */ "as ::=",
109778  /* 130 */ "from ::=",
109779  /* 131 */ "from ::= FROM seltablist",
109780  /* 132 */ "stl_prefix ::= seltablist joinop",
109781  /* 133 */ "stl_prefix ::=",
109782  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
109783  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
109784  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
109785  /* 137 */ "dbnm ::=",
109786  /* 138 */ "dbnm ::= DOT nm",
109787  /* 139 */ "fullname ::= nm dbnm",
109788  /* 140 */ "joinop ::= COMMA|JOIN",
109789  /* 141 */ "joinop ::= JOIN_KW JOIN",
109790  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
109791  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
109792  /* 144 */ "on_opt ::= ON expr",
109793  /* 145 */ "on_opt ::=",
109794  /* 146 */ "indexed_opt ::=",
109795  /* 147 */ "indexed_opt ::= INDEXED BY nm",
109796  /* 148 */ "indexed_opt ::= NOT INDEXED",
109797  /* 149 */ "using_opt ::= USING LP inscollist RP",
109798  /* 150 */ "using_opt ::=",
109799  /* 151 */ "orderby_opt ::=",
109800  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
109801  /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
109802  /* 154 */ "sortlist ::= expr sortorder",
109803  /* 155 */ "sortorder ::= ASC",
109804  /* 156 */ "sortorder ::= DESC",
109805  /* 157 */ "sortorder ::=",
109806  /* 158 */ "groupby_opt ::=",
109807  /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
109808  /* 160 */ "having_opt ::=",
109809  /* 161 */ "having_opt ::= HAVING expr",
109810  /* 162 */ "limit_opt ::=",
109811  /* 163 */ "limit_opt ::= LIMIT expr",
109812  /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
109813  /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
109814  /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
109815  /* 167 */ "where_opt ::=",
109816  /* 168 */ "where_opt ::= WHERE expr",
109817  /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
109818  /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
109819  /* 171 */ "setlist ::= nm EQ expr",
109820  /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
109821  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
109822  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
109823  /* 175 */ "insert_cmd ::= INSERT orconf",
109824  /* 176 */ "insert_cmd ::= REPLACE",
109825  /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
109826  /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
109827  /* 179 */ "inscollist_opt ::=",
109828  /* 180 */ "inscollist_opt ::= LP inscollist RP",
109829  /* 181 */ "inscollist ::= inscollist COMMA nm",
109830  /* 182 */ "inscollist ::= nm",
109831  /* 183 */ "expr ::= term",
109832  /* 184 */ "expr ::= LP expr RP",
109833  /* 185 */ "term ::= NULL",
109834  /* 186 */ "expr ::= id",
109835  /* 187 */ "expr ::= JOIN_KW",
109836  /* 188 */ "expr ::= nm DOT nm",
109837  /* 189 */ "expr ::= nm DOT nm DOT nm",
109838  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
109839  /* 191 */ "term ::= STRING",
109840  /* 192 */ "expr ::= REGISTER",
109841  /* 193 */ "expr ::= VARIABLE",
109842  /* 194 */ "expr ::= expr COLLATE ids",
109843  /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
109844  /* 196 */ "expr ::= ID LP distinct exprlist RP",
109845  /* 197 */ "expr ::= ID LP STAR RP",
109846  /* 198 */ "term ::= CTIME_KW",
109847  /* 199 */ "expr ::= expr AND expr",
109848  /* 200 */ "expr ::= expr OR expr",
109849  /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
109850  /* 202 */ "expr ::= expr EQ|NE expr",
109851  /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
109852  /* 204 */ "expr ::= expr PLUS|MINUS expr",
109853  /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
109854  /* 206 */ "expr ::= expr CONCAT expr",
109855  /* 207 */ "likeop ::= LIKE_KW",
109856  /* 208 */ "likeop ::= NOT LIKE_KW",
109857  /* 209 */ "likeop ::= MATCH",
109858  /* 210 */ "likeop ::= NOT MATCH",
109859  /* 211 */ "expr ::= expr likeop expr",
109860  /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
109861  /* 213 */ "expr ::= expr ISNULL|NOTNULL",
109862  /* 214 */ "expr ::= expr NOT NULL",
109863  /* 215 */ "expr ::= expr IS expr",
109864  /* 216 */ "expr ::= expr IS NOT expr",
109865  /* 217 */ "expr ::= NOT expr",
109866  /* 218 */ "expr ::= BITNOT expr",
109867  /* 219 */ "expr ::= MINUS expr",
109868  /* 220 */ "expr ::= PLUS expr",
109869  /* 221 */ "between_op ::= BETWEEN",
109870  /* 222 */ "between_op ::= NOT BETWEEN",
109871  /* 223 */ "expr ::= expr between_op expr AND expr",
109872  /* 224 */ "in_op ::= IN",
109873  /* 225 */ "in_op ::= NOT IN",
109874  /* 226 */ "expr ::= expr in_op LP exprlist RP",
109875  /* 227 */ "expr ::= LP select RP",
109876  /* 228 */ "expr ::= expr in_op LP select RP",
109877  /* 229 */ "expr ::= expr in_op nm dbnm",
109878  /* 230 */ "expr ::= EXISTS LP select RP",
109879  /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
109880  /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
109881  /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
109882  /* 234 */ "case_else ::= ELSE expr",
109883  /* 235 */ "case_else ::=",
109884  /* 236 */ "case_operand ::= expr",
109885  /* 237 */ "case_operand ::=",
109886  /* 238 */ "exprlist ::= nexprlist",
109887  /* 239 */ "exprlist ::=",
109888  /* 240 */ "nexprlist ::= nexprlist COMMA expr",
109889  /* 241 */ "nexprlist ::= expr",
109890  /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
109891  /* 243 */ "uniqueflag ::= UNIQUE",
109892  /* 244 */ "uniqueflag ::=",
109893  /* 245 */ "idxlist_opt ::=",
109894  /* 246 */ "idxlist_opt ::= LP idxlist RP",
109895  /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
109896  /* 248 */ "idxlist ::= nm collate sortorder",
109897  /* 249 */ "collate ::=",
109898  /* 250 */ "collate ::= COLLATE ids",
109899  /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
109900  /* 252 */ "cmd ::= VACUUM",
109901  /* 253 */ "cmd ::= VACUUM nm",
109902  /* 254 */ "cmd ::= PRAGMA nm dbnm",
109903  /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
109904  /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
109905  /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
109906  /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
109907  /* 259 */ "nmnum ::= plus_num",
109908  /* 260 */ "nmnum ::= nm",
109909  /* 261 */ "nmnum ::= ON",
109910  /* 262 */ "nmnum ::= DELETE",
109911  /* 263 */ "nmnum ::= DEFAULT",
109912  /* 264 */ "plus_num ::= PLUS number",
109913  /* 265 */ "plus_num ::= number",
109914  /* 266 */ "minus_num ::= MINUS number",
109915  /* 267 */ "number ::= INTEGER|FLOAT",
109916  /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
109917  /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
109918  /* 270 */ "trigger_time ::= BEFORE",
109919  /* 271 */ "trigger_time ::= AFTER",
109920  /* 272 */ "trigger_time ::= INSTEAD OF",
109921  /* 273 */ "trigger_time ::=",
109922  /* 274 */ "trigger_event ::= DELETE|INSERT",
109923  /* 275 */ "trigger_event ::= UPDATE",
109924  /* 276 */ "trigger_event ::= UPDATE OF inscollist",
109925  /* 277 */ "foreach_clause ::=",
109926  /* 278 */ "foreach_clause ::= FOR EACH ROW",
109927  /* 279 */ "when_clause ::=",
109928  /* 280 */ "when_clause ::= WHEN expr",
109929  /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
109930  /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
109931  /* 283 */ "trnm ::= nm",
109932  /* 284 */ "trnm ::= nm DOT nm",
109933  /* 285 */ "tridxby ::=",
109934  /* 286 */ "tridxby ::= INDEXED BY nm",
109935  /* 287 */ "tridxby ::= NOT INDEXED",
109936  /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
109937  /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
109938  /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
109939  /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
109940  /* 292 */ "trigger_cmd ::= select",
109941  /* 293 */ "expr ::= RAISE LP IGNORE RP",
109942  /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
109943  /* 295 */ "raisetype ::= ROLLBACK",
109944  /* 296 */ "raisetype ::= ABORT",
109945  /* 297 */ "raisetype ::= FAIL",
109946  /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
109947  /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
109948  /* 300 */ "cmd ::= DETACH database_kw_opt expr",
109949  /* 301 */ "key_opt ::=",
109950  /* 302 */ "key_opt ::= KEY expr",
109951  /* 303 */ "database_kw_opt ::= DATABASE",
109952  /* 304 */ "database_kw_opt ::=",
109953  /* 305 */ "cmd ::= REINDEX",
109954  /* 306 */ "cmd ::= REINDEX nm dbnm",
109955  /* 307 */ "cmd ::= ANALYZE",
109956  /* 308 */ "cmd ::= ANALYZE nm dbnm",
109957  /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
109958  /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
109959  /* 311 */ "add_column_fullname ::= fullname",
109960  /* 312 */ "kwcolumn_opt ::=",
109961  /* 313 */ "kwcolumn_opt ::= COLUMNKW",
109962  /* 314 */ "cmd ::= create_vtab",
109963  /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
109964  /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
109965  /* 317 */ "vtabarglist ::= vtabarg",
109966  /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
109967  /* 319 */ "vtabarg ::=",
109968  /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
109969  /* 321 */ "vtabargtoken ::= ANY",
109970  /* 322 */ "vtabargtoken ::= lp anylist RP",
109971  /* 323 */ "lp ::= LP",
109972  /* 324 */ "anylist ::=",
109973  /* 325 */ "anylist ::= anylist LP anylist RP",
109974  /* 326 */ "anylist ::= anylist ANY",
109975 };
109976 #endif /* NDEBUG */
109977
109978
109979 #if YYSTACKDEPTH<=0
109980 /*
109981 ** Try to increase the size of the parser stack.
109982 */
109983 static void yyGrowStack(yyParser *p){
109984   int newSize;
109985   yyStackEntry *pNew;
109986
109987   newSize = p->yystksz*2 + 100;
109988   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
109989   if( pNew ){
109990     p->yystack = pNew;
109991     p->yystksz = newSize;
109992 #ifndef NDEBUG
109993     if( yyTraceFILE ){
109994       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
109995               yyTracePrompt, p->yystksz);
109996     }
109997 #endif
109998   }
109999 }
110000 #endif
110001
110002 /* 
110003 ** This function allocates a new parser.
110004 ** The only argument is a pointer to a function which works like
110005 ** malloc.
110006 **
110007 ** Inputs:
110008 ** A pointer to the function used to allocate memory.
110009 **
110010 ** Outputs:
110011 ** A pointer to a parser.  This pointer is used in subsequent calls
110012 ** to sqlite3Parser and sqlite3ParserFree.
110013 */
110014 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
110015   yyParser *pParser;
110016   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
110017   if( pParser ){
110018     pParser->yyidx = -1;
110019 #ifdef YYTRACKMAXSTACKDEPTH
110020     pParser->yyidxMax = 0;
110021 #endif
110022 #if YYSTACKDEPTH<=0
110023     pParser->yystack = NULL;
110024     pParser->yystksz = 0;
110025     yyGrowStack(pParser);
110026 #endif
110027   }
110028   return pParser;
110029 }
110030
110031 /* The following function deletes the value associated with a
110032 ** symbol.  The symbol can be either a terminal or nonterminal.
110033 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
110034 ** the value.
110035 */
110036 static void yy_destructor(
110037   yyParser *yypParser,    /* The parser */
110038   YYCODETYPE yymajor,     /* Type code for object to destroy */
110039   YYMINORTYPE *yypminor   /* The object to be destroyed */
110040 ){
110041   sqlite3ParserARG_FETCH;
110042   switch( yymajor ){
110043     /* Here is inserted the actions which take place when a
110044     ** terminal or non-terminal is destroyed.  This can happen
110045     ** when the symbol is popped from the stack during a
110046     ** reduce or during error processing or when a parser is 
110047     ** being destroyed before it is finished parsing.
110048     **
110049     ** Note: during a reduce, the only symbols destroyed are those
110050     ** which appear on the RHS of the rule, but which are not used
110051     ** inside the C code.
110052     */
110053     case 160: /* select */
110054     case 194: /* oneselect */
110055 {
110056 sqlite3SelectDelete(pParse->db, (yypminor->yy159));
110057 }
110058       break;
110059     case 173: /* term */
110060     case 174: /* expr */
110061 {
110062 sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
110063 }
110064       break;
110065     case 178: /* idxlist_opt */
110066     case 187: /* idxlist */
110067     case 197: /* selcollist */
110068     case 200: /* groupby_opt */
110069     case 202: /* orderby_opt */
110070     case 204: /* sclp */
110071     case 214: /* sortlist */
110072     case 215: /* nexprlist */
110073     case 216: /* setlist */
110074     case 220: /* exprlist */
110075     case 225: /* case_exprlist */
110076 {
110077 sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
110078 }
110079       break;
110080     case 193: /* fullname */
110081     case 198: /* from */
110082     case 206: /* seltablist */
110083     case 207: /* stl_prefix */
110084 {
110085 sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
110086 }
110087       break;
110088     case 199: /* where_opt */
110089     case 201: /* having_opt */
110090     case 210: /* on_opt */
110091     case 224: /* case_operand */
110092     case 226: /* case_else */
110093     case 236: /* when_clause */
110094     case 241: /* key_opt */
110095 {
110096 sqlite3ExprDelete(pParse->db, (yypminor->yy122));
110097 }
110098       break;
110099     case 211: /* using_opt */
110100     case 213: /* inscollist */
110101     case 218: /* inscollist_opt */
110102 {
110103 sqlite3IdListDelete(pParse->db, (yypminor->yy180));
110104 }
110105       break;
110106     case 219: /* valuelist */
110107 {
110108
110109   sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
110110   sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
110111
110112 }
110113       break;
110114     case 232: /* trigger_cmd_list */
110115     case 237: /* trigger_cmd */
110116 {
110117 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
110118 }
110119       break;
110120     case 234: /* trigger_event */
110121 {
110122 sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
110123 }
110124       break;
110125     default:  break;   /* If no destructor action specified: do nothing */
110126   }
110127 }
110128
110129 /*
110130 ** Pop the parser's stack once.
110131 **
110132 ** If there is a destructor routine associated with the token which
110133 ** is popped from the stack, then call it.
110134 **
110135 ** Return the major token number for the symbol popped.
110136 */
110137 static int yy_pop_parser_stack(yyParser *pParser){
110138   YYCODETYPE yymajor;
110139   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
110140
110141   /* There is no mechanism by which the parser stack can be popped below
110142   ** empty in SQLite.  */
110143   if( NEVER(pParser->yyidx<0) ) return 0;
110144 #ifndef NDEBUG
110145   if( yyTraceFILE && pParser->yyidx>=0 ){
110146     fprintf(yyTraceFILE,"%sPopping %s\n",
110147       yyTracePrompt,
110148       yyTokenName[yytos->major]);
110149   }
110150 #endif
110151   yymajor = yytos->major;
110152   yy_destructor(pParser, yymajor, &yytos->minor);
110153   pParser->yyidx--;
110154   return yymajor;
110155 }
110156
110157 /* 
110158 ** Deallocate and destroy a parser.  Destructors are all called for
110159 ** all stack elements before shutting the parser down.
110160 **
110161 ** Inputs:
110162 ** <ul>
110163 ** <li>  A pointer to the parser.  This should be a pointer
110164 **       obtained from sqlite3ParserAlloc.
110165 ** <li>  A pointer to a function used to reclaim memory obtained
110166 **       from malloc.
110167 ** </ul>
110168 */
110169 SQLITE_PRIVATE void sqlite3ParserFree(
110170   void *p,                    /* The parser to be deleted */
110171   void (*freeProc)(void*)     /* Function used to reclaim memory */
110172 ){
110173   yyParser *pParser = (yyParser*)p;
110174   /* In SQLite, we never try to destroy a parser that was not successfully
110175   ** created in the first place. */
110176   if( NEVER(pParser==0) ) return;
110177   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
110178 #if YYSTACKDEPTH<=0
110179   free(pParser->yystack);
110180 #endif
110181   (*freeProc)((void*)pParser);
110182 }
110183
110184 /*
110185 ** Return the peak depth of the stack for a parser.
110186 */
110187 #ifdef YYTRACKMAXSTACKDEPTH
110188 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
110189   yyParser *pParser = (yyParser*)p;
110190   return pParser->yyidxMax;
110191 }
110192 #endif
110193
110194 /*
110195 ** Find the appropriate action for a parser given the terminal
110196 ** look-ahead token iLookAhead.
110197 **
110198 ** If the look-ahead token is YYNOCODE, then check to see if the action is
110199 ** independent of the look-ahead.  If it is, return the action, otherwise
110200 ** return YY_NO_ACTION.
110201 */
110202 static int yy_find_shift_action(
110203   yyParser *pParser,        /* The parser */
110204   YYCODETYPE iLookAhead     /* The look-ahead token */
110205 ){
110206   int i;
110207   int stateno = pParser->yystack[pParser->yyidx].stateno;
110208  
110209   if( stateno>YY_SHIFT_COUNT
110210    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
110211     return yy_default[stateno];
110212   }
110213   assert( iLookAhead!=YYNOCODE );
110214   i += iLookAhead;
110215   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
110216     if( iLookAhead>0 ){
110217 #ifdef YYFALLBACK
110218       YYCODETYPE iFallback;            /* Fallback token */
110219       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
110220              && (iFallback = yyFallback[iLookAhead])!=0 ){
110221 #ifndef NDEBUG
110222         if( yyTraceFILE ){
110223           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
110224              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
110225         }
110226 #endif
110227         return yy_find_shift_action(pParser, iFallback);
110228       }
110229 #endif
110230 #ifdef YYWILDCARD
110231       {
110232         int j = i - iLookAhead + YYWILDCARD;
110233         if( 
110234 #if YY_SHIFT_MIN+YYWILDCARD<0
110235           j>=0 &&
110236 #endif
110237 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
110238           j<YY_ACTTAB_COUNT &&
110239 #endif
110240           yy_lookahead[j]==YYWILDCARD
110241         ){
110242 #ifndef NDEBUG
110243           if( yyTraceFILE ){
110244             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
110245                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
110246           }
110247 #endif /* NDEBUG */
110248           return yy_action[j];
110249         }
110250       }
110251 #endif /* YYWILDCARD */
110252     }
110253     return yy_default[stateno];
110254   }else{
110255     return yy_action[i];
110256   }
110257 }
110258
110259 /*
110260 ** Find the appropriate action for a parser given the non-terminal
110261 ** look-ahead token iLookAhead.
110262 **
110263 ** If the look-ahead token is YYNOCODE, then check to see if the action is
110264 ** independent of the look-ahead.  If it is, return the action, otherwise
110265 ** return YY_NO_ACTION.
110266 */
110267 static int yy_find_reduce_action(
110268   int stateno,              /* Current state number */
110269   YYCODETYPE iLookAhead     /* The look-ahead token */
110270 ){
110271   int i;
110272 #ifdef YYERRORSYMBOL
110273   if( stateno>YY_REDUCE_COUNT ){
110274     return yy_default[stateno];
110275   }
110276 #else
110277   assert( stateno<=YY_REDUCE_COUNT );
110278 #endif
110279   i = yy_reduce_ofst[stateno];
110280   assert( i!=YY_REDUCE_USE_DFLT );
110281   assert( iLookAhead!=YYNOCODE );
110282   i += iLookAhead;
110283 #ifdef YYERRORSYMBOL
110284   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
110285     return yy_default[stateno];
110286   }
110287 #else
110288   assert( i>=0 && i<YY_ACTTAB_COUNT );
110289   assert( yy_lookahead[i]==iLookAhead );
110290 #endif
110291   return yy_action[i];
110292 }
110293
110294 /*
110295 ** The following routine is called if the stack overflows.
110296 */
110297 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
110298    sqlite3ParserARG_FETCH;
110299    yypParser->yyidx--;
110300 #ifndef NDEBUG
110301    if( yyTraceFILE ){
110302      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
110303    }
110304 #endif
110305    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
110306    /* Here code is inserted which will execute if the parser
110307    ** stack every overflows */
110308
110309   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
110310   sqlite3ErrorMsg(pParse, "parser stack overflow");
110311    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
110312 }
110313
110314 /*
110315 ** Perform a shift action.
110316 */
110317 static void yy_shift(
110318   yyParser *yypParser,          /* The parser to be shifted */
110319   int yyNewState,               /* The new state to shift in */
110320   int yyMajor,                  /* The major token to shift in */
110321   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
110322 ){
110323   yyStackEntry *yytos;
110324   yypParser->yyidx++;
110325 #ifdef YYTRACKMAXSTACKDEPTH
110326   if( yypParser->yyidx>yypParser->yyidxMax ){
110327     yypParser->yyidxMax = yypParser->yyidx;
110328   }
110329 #endif
110330 #if YYSTACKDEPTH>0 
110331   if( yypParser->yyidx>=YYSTACKDEPTH ){
110332     yyStackOverflow(yypParser, yypMinor);
110333     return;
110334   }
110335 #else
110336   if( yypParser->yyidx>=yypParser->yystksz ){
110337     yyGrowStack(yypParser);
110338     if( yypParser->yyidx>=yypParser->yystksz ){
110339       yyStackOverflow(yypParser, yypMinor);
110340       return;
110341     }
110342   }
110343 #endif
110344   yytos = &yypParser->yystack[yypParser->yyidx];
110345   yytos->stateno = (YYACTIONTYPE)yyNewState;
110346   yytos->major = (YYCODETYPE)yyMajor;
110347   yytos->minor = *yypMinor;
110348 #ifndef NDEBUG
110349   if( yyTraceFILE && yypParser->yyidx>0 ){
110350     int i;
110351     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
110352     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
110353     for(i=1; i<=yypParser->yyidx; i++)
110354       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
110355     fprintf(yyTraceFILE,"\n");
110356   }
110357 #endif
110358 }
110359
110360 /* The following table contains information about every rule that
110361 ** is used during the reduce.
110362 */
110363 static const struct {
110364   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
110365   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
110366 } yyRuleInfo[] = {
110367   { 142, 1 },
110368   { 143, 2 },
110369   { 143, 1 },
110370   { 144, 1 },
110371   { 144, 3 },
110372   { 145, 0 },
110373   { 145, 1 },
110374   { 145, 3 },
110375   { 146, 1 },
110376   { 147, 3 },
110377   { 149, 0 },
110378   { 149, 1 },
110379   { 149, 2 },
110380   { 148, 0 },
110381   { 148, 1 },
110382   { 148, 1 },
110383   { 148, 1 },
110384   { 147, 2 },
110385   { 147, 2 },
110386   { 147, 2 },
110387   { 151, 1 },
110388   { 151, 0 },
110389   { 147, 2 },
110390   { 147, 3 },
110391   { 147, 5 },
110392   { 147, 2 },
110393   { 152, 6 },
110394   { 154, 1 },
110395   { 156, 0 },
110396   { 156, 3 },
110397   { 155, 1 },
110398   { 155, 0 },
110399   { 153, 4 },
110400   { 153, 2 },
110401   { 158, 3 },
110402   { 158, 1 },
110403   { 161, 3 },
110404   { 162, 1 },
110405   { 165, 1 },
110406   { 165, 1 },
110407   { 166, 1 },
110408   { 150, 1 },
110409   { 150, 1 },
110410   { 150, 1 },
110411   { 163, 0 },
110412   { 163, 1 },
110413   { 167, 1 },
110414   { 167, 4 },
110415   { 167, 6 },
110416   { 168, 1 },
110417   { 168, 2 },
110418   { 169, 1 },
110419   { 169, 1 },
110420   { 164, 2 },
110421   { 164, 0 },
110422   { 172, 2 },
110423   { 172, 2 },
110424   { 172, 4 },
110425   { 172, 3 },
110426   { 172, 3 },
110427   { 172, 2 },
110428   { 172, 2 },
110429   { 172, 3 },
110430   { 172, 5 },
110431   { 172, 2 },
110432   { 172, 4 },
110433   { 172, 4 },
110434   { 172, 1 },
110435   { 172, 2 },
110436   { 177, 0 },
110437   { 177, 1 },
110438   { 179, 0 },
110439   { 179, 2 },
110440   { 181, 2 },
110441   { 181, 3 },
110442   { 181, 3 },
110443   { 181, 3 },
110444   { 182, 2 },
110445   { 182, 2 },
110446   { 182, 1 },
110447   { 182, 1 },
110448   { 182, 2 },
110449   { 180, 3 },
110450   { 180, 2 },
110451   { 183, 0 },
110452   { 183, 2 },
110453   { 183, 2 },
110454   { 159, 0 },
110455   { 159, 2 },
110456   { 184, 3 },
110457   { 184, 1 },
110458   { 185, 1 },
110459   { 185, 0 },
110460   { 186, 2 },
110461   { 186, 7 },
110462   { 186, 5 },
110463   { 186, 5 },
110464   { 186, 10 },
110465   { 188, 0 },
110466   { 188, 1 },
110467   { 175, 0 },
110468   { 175, 3 },
110469   { 189, 0 },
110470   { 189, 2 },
110471   { 190, 1 },
110472   { 190, 1 },
110473   { 190, 1 },
110474   { 147, 4 },
110475   { 192, 2 },
110476   { 192, 0 },
110477   { 147, 8 },
110478   { 147, 4 },
110479   { 147, 1 },
110480   { 160, 1 },
110481   { 160, 3 },
110482   { 195, 1 },
110483   { 195, 2 },
110484   { 195, 1 },
110485   { 194, 9 },
110486   { 196, 1 },
110487   { 196, 1 },
110488   { 196, 0 },
110489   { 204, 2 },
110490   { 204, 0 },
110491   { 197, 3 },
110492   { 197, 2 },
110493   { 197, 4 },
110494   { 205, 2 },
110495   { 205, 1 },
110496   { 205, 0 },
110497   { 198, 0 },
110498   { 198, 2 },
110499   { 207, 2 },
110500   { 207, 0 },
110501   { 206, 7 },
110502   { 206, 7 },
110503   { 206, 7 },
110504   { 157, 0 },
110505   { 157, 2 },
110506   { 193, 2 },
110507   { 208, 1 },
110508   { 208, 2 },
110509   { 208, 3 },
110510   { 208, 4 },
110511   { 210, 2 },
110512   { 210, 0 },
110513   { 209, 0 },
110514   { 209, 3 },
110515   { 209, 2 },
110516   { 211, 4 },
110517   { 211, 0 },
110518   { 202, 0 },
110519   { 202, 3 },
110520   { 214, 4 },
110521   { 214, 2 },
110522   { 176, 1 },
110523   { 176, 1 },
110524   { 176, 0 },
110525   { 200, 0 },
110526   { 200, 3 },
110527   { 201, 0 },
110528   { 201, 2 },
110529   { 203, 0 },
110530   { 203, 2 },
110531   { 203, 4 },
110532   { 203, 4 },
110533   { 147, 5 },
110534   { 199, 0 },
110535   { 199, 2 },
110536   { 147, 7 },
110537   { 216, 5 },
110538   { 216, 3 },
110539   { 147, 5 },
110540   { 147, 5 },
110541   { 147, 6 },
110542   { 217, 2 },
110543   { 217, 1 },
110544   { 219, 4 },
110545   { 219, 5 },
110546   { 218, 0 },
110547   { 218, 3 },
110548   { 213, 3 },
110549   { 213, 1 },
110550   { 174, 1 },
110551   { 174, 3 },
110552   { 173, 1 },
110553   { 174, 1 },
110554   { 174, 1 },
110555   { 174, 3 },
110556   { 174, 5 },
110557   { 173, 1 },
110558   { 173, 1 },
110559   { 174, 1 },
110560   { 174, 1 },
110561   { 174, 3 },
110562   { 174, 6 },
110563   { 174, 5 },
110564   { 174, 4 },
110565   { 173, 1 },
110566   { 174, 3 },
110567   { 174, 3 },
110568   { 174, 3 },
110569   { 174, 3 },
110570   { 174, 3 },
110571   { 174, 3 },
110572   { 174, 3 },
110573   { 174, 3 },
110574   { 221, 1 },
110575   { 221, 2 },
110576   { 221, 1 },
110577   { 221, 2 },
110578   { 174, 3 },
110579   { 174, 5 },
110580   { 174, 2 },
110581   { 174, 3 },
110582   { 174, 3 },
110583   { 174, 4 },
110584   { 174, 2 },
110585   { 174, 2 },
110586   { 174, 2 },
110587   { 174, 2 },
110588   { 222, 1 },
110589   { 222, 2 },
110590   { 174, 5 },
110591   { 223, 1 },
110592   { 223, 2 },
110593   { 174, 5 },
110594   { 174, 3 },
110595   { 174, 5 },
110596   { 174, 4 },
110597   { 174, 4 },
110598   { 174, 5 },
110599   { 225, 5 },
110600   { 225, 4 },
110601   { 226, 2 },
110602   { 226, 0 },
110603   { 224, 1 },
110604   { 224, 0 },
110605   { 220, 1 },
110606   { 220, 0 },
110607   { 215, 3 },
110608   { 215, 1 },
110609   { 147, 11 },
110610   { 227, 1 },
110611   { 227, 0 },
110612   { 178, 0 },
110613   { 178, 3 },
110614   { 187, 5 },
110615   { 187, 3 },
110616   { 228, 0 },
110617   { 228, 2 },
110618   { 147, 4 },
110619   { 147, 1 },
110620   { 147, 2 },
110621   { 147, 3 },
110622   { 147, 5 },
110623   { 147, 6 },
110624   { 147, 5 },
110625   { 147, 6 },
110626   { 229, 1 },
110627   { 229, 1 },
110628   { 229, 1 },
110629   { 229, 1 },
110630   { 229, 1 },
110631   { 170, 2 },
110632   { 170, 1 },
110633   { 171, 2 },
110634   { 230, 1 },
110635   { 147, 5 },
110636   { 231, 11 },
110637   { 233, 1 },
110638   { 233, 1 },
110639   { 233, 2 },
110640   { 233, 0 },
110641   { 234, 1 },
110642   { 234, 1 },
110643   { 234, 3 },
110644   { 235, 0 },
110645   { 235, 3 },
110646   { 236, 0 },
110647   { 236, 2 },
110648   { 232, 3 },
110649   { 232, 2 },
110650   { 238, 1 },
110651   { 238, 3 },
110652   { 239, 0 },
110653   { 239, 3 },
110654   { 239, 2 },
110655   { 237, 7 },
110656   { 237, 5 },
110657   { 237, 5 },
110658   { 237, 5 },
110659   { 237, 1 },
110660   { 174, 4 },
110661   { 174, 6 },
110662   { 191, 1 },
110663   { 191, 1 },
110664   { 191, 1 },
110665   { 147, 4 },
110666   { 147, 6 },
110667   { 147, 3 },
110668   { 241, 0 },
110669   { 241, 2 },
110670   { 240, 1 },
110671   { 240, 0 },
110672   { 147, 1 },
110673   { 147, 3 },
110674   { 147, 1 },
110675   { 147, 3 },
110676   { 147, 6 },
110677   { 147, 6 },
110678   { 242, 1 },
110679   { 243, 0 },
110680   { 243, 1 },
110681   { 147, 1 },
110682   { 147, 4 },
110683   { 244, 8 },
110684   { 245, 1 },
110685   { 245, 3 },
110686   { 246, 0 },
110687   { 246, 2 },
110688   { 247, 1 },
110689   { 247, 3 },
110690   { 248, 1 },
110691   { 249, 0 },
110692   { 249, 4 },
110693   { 249, 2 },
110694 };
110695
110696 static void yy_accept(yyParser*);  /* Forward Declaration */
110697
110698 /*
110699 ** Perform a reduce action and the shift that must immediately
110700 ** follow the reduce.
110701 */
110702 static void yy_reduce(
110703   yyParser *yypParser,         /* The parser */
110704   int yyruleno                 /* Number of the rule by which to reduce */
110705 ){
110706   int yygoto;                     /* The next state */
110707   int yyact;                      /* The next action */
110708   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
110709   yyStackEntry *yymsp;            /* The top of the parser's stack */
110710   int yysize;                     /* Amount to pop the stack */
110711   sqlite3ParserARG_FETCH;
110712   yymsp = &yypParser->yystack[yypParser->yyidx];
110713 #ifndef NDEBUG
110714   if( yyTraceFILE && yyruleno>=0 
110715         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
110716     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
110717       yyRuleName[yyruleno]);
110718   }
110719 #endif /* NDEBUG */
110720
110721   /* Silence complaints from purify about yygotominor being uninitialized
110722   ** in some cases when it is copied into the stack after the following
110723   ** switch.  yygotominor is uninitialized when a rule reduces that does
110724   ** not set the value of its left-hand side nonterminal.  Leaving the
110725   ** value of the nonterminal uninitialized is utterly harmless as long
110726   ** as the value is never used.  So really the only thing this code
110727   ** accomplishes is to quieten purify.  
110728   **
110729   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
110730   ** without this code, their parser segfaults.  I'm not sure what there
110731   ** parser is doing to make this happen.  This is the second bug report
110732   ** from wireshark this week.  Clearly they are stressing Lemon in ways
110733   ** that it has not been previously stressed...  (SQLite ticket #2172)
110734   */
110735   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
110736   yygotominor = yyzerominor;
110737
110738
110739   switch( yyruleno ){
110740   /* Beginning here are the reduction cases.  A typical example
110741   ** follows:
110742   **   case 0:
110743   **  #line <lineno> <grammarfile>
110744   **     { ... }           // User supplied code
110745   **  #line <lineno> <thisfile>
110746   **     break;
110747   */
110748       case 5: /* explain ::= */
110749 { sqlite3BeginParse(pParse, 0); }
110750         break;
110751       case 6: /* explain ::= EXPLAIN */
110752 { sqlite3BeginParse(pParse, 1); }
110753         break;
110754       case 7: /* explain ::= EXPLAIN QUERY PLAN */
110755 { sqlite3BeginParse(pParse, 2); }
110756         break;
110757       case 8: /* cmdx ::= cmd */
110758 { sqlite3FinishCoding(pParse); }
110759         break;
110760       case 9: /* cmd ::= BEGIN transtype trans_opt */
110761 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
110762         break;
110763       case 13: /* transtype ::= */
110764 {yygotominor.yy392 = TK_DEFERRED;}
110765         break;
110766       case 14: /* transtype ::= DEFERRED */
110767       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
110768       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
110769       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
110770       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
110771 {yygotominor.yy392 = yymsp[0].major;}
110772         break;
110773       case 17: /* cmd ::= COMMIT trans_opt */
110774       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
110775 {sqlite3CommitTransaction(pParse);}
110776         break;
110777       case 19: /* cmd ::= ROLLBACK trans_opt */
110778 {sqlite3RollbackTransaction(pParse);}
110779         break;
110780       case 22: /* cmd ::= SAVEPOINT nm */
110781 {
110782   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
110783 }
110784         break;
110785       case 23: /* cmd ::= RELEASE savepoint_opt nm */
110786 {
110787   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
110788 }
110789         break;
110790       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
110791 {
110792   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
110793 }
110794         break;
110795       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
110796 {
110797    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
110798 }
110799         break;
110800       case 27: /* createkw ::= CREATE */
110801 {
110802   pParse->db->lookaside.bEnabled = 0;
110803   yygotominor.yy0 = yymsp[0].minor.yy0;
110804 }
110805         break;
110806       case 28: /* ifnotexists ::= */
110807       case 31: /* temp ::= */ yytestcase(yyruleno==31);
110808       case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
110809       case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
110810       case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
110811       case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
110812       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
110813       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
110814       case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
110815       case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
110816 {yygotominor.yy392 = 0;}
110817         break;
110818       case 29: /* ifnotexists ::= IF NOT EXISTS */
110819       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
110820       case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
110821       case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
110822       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
110823       case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
110824       case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
110825 {yygotominor.yy392 = 1;}
110826         break;
110827       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
110828 {
110829   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
110830 }
110831         break;
110832       case 33: /* create_table_args ::= AS select */
110833 {
110834   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
110835   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
110836 }
110837         break;
110838       case 36: /* column ::= columnid type carglist */
110839 {
110840   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
110841   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
110842 }
110843         break;
110844       case 37: /* columnid ::= nm */
110845 {
110846   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
110847   yygotominor.yy0 = yymsp[0].minor.yy0;
110848   pParse->constraintName.n = 0;
110849 }
110850         break;
110851       case 38: /* id ::= ID */
110852       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
110853       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
110854       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
110855       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
110856       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
110857       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
110858       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
110859       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
110860       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
110861       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
110862       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
110863       case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
110864       case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
110865       case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
110866       case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
110867       case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
110868       case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
110869       case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
110870       case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
110871       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
110872       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
110873       case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
110874 {yygotominor.yy0 = yymsp[0].minor.yy0;}
110875         break;
110876       case 45: /* type ::= typetoken */
110877 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
110878         break;
110879       case 47: /* typetoken ::= typename LP signed RP */
110880 {
110881   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
110882   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
110883 }
110884         break;
110885       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
110886 {
110887   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
110888   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
110889 }
110890         break;
110891       case 50: /* typename ::= typename ids */
110892 {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);}
110893         break;
110894       case 55: /* ccons ::= CONSTRAINT nm */
110895       case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
110896 {pParse->constraintName = yymsp[0].minor.yy0;}
110897         break;
110898       case 56: /* ccons ::= DEFAULT term */
110899       case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
110900 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
110901         break;
110902       case 57: /* ccons ::= DEFAULT LP expr RP */
110903 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
110904         break;
110905       case 59: /* ccons ::= DEFAULT MINUS term */
110906 {
110907   ExprSpan v;
110908   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
110909   v.zStart = yymsp[-1].minor.yy0.z;
110910   v.zEnd = yymsp[0].minor.yy342.zEnd;
110911   sqlite3AddDefaultValue(pParse,&v);
110912 }
110913         break;
110914       case 60: /* ccons ::= DEFAULT id */
110915 {
110916   ExprSpan v;
110917   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
110918   sqlite3AddDefaultValue(pParse,&v);
110919 }
110920         break;
110921       case 62: /* ccons ::= NOT NULL onconf */
110922 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
110923         break;
110924       case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
110925 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
110926         break;
110927       case 64: /* ccons ::= UNIQUE onconf */
110928 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
110929         break;
110930       case 65: /* ccons ::= CHECK LP expr RP */
110931 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
110932         break;
110933       case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
110934 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
110935         break;
110936       case 67: /* ccons ::= defer_subclause */
110937 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
110938         break;
110939       case 68: /* ccons ::= COLLATE ids */
110940 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
110941         break;
110942       case 71: /* refargs ::= */
110943 { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
110944         break;
110945       case 72: /* refargs ::= refargs refarg */
110946 { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
110947         break;
110948       case 73: /* refarg ::= MATCH nm */
110949       case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
110950 { yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
110951         break;
110952       case 75: /* refarg ::= ON DELETE refact */
110953 { yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
110954         break;
110955       case 76: /* refarg ::= ON UPDATE refact */
110956 { yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
110957         break;
110958       case 77: /* refact ::= SET NULL */
110959 { yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}
110960         break;
110961       case 78: /* refact ::= SET DEFAULT */
110962 { yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}
110963         break;
110964       case 79: /* refact ::= CASCADE */
110965 { yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}
110966         break;
110967       case 80: /* refact ::= RESTRICT */
110968 { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
110969         break;
110970       case 81: /* refact ::= NO ACTION */
110971 { yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}
110972         break;
110973       case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
110974       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
110975       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
110976       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
110977 {yygotominor.yy392 = yymsp[0].minor.yy392;}
110978         break;
110979       case 87: /* conslist_opt ::= */
110980 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
110981         break;
110982       case 88: /* conslist_opt ::= COMMA conslist */
110983 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
110984         break;
110985       case 91: /* tconscomma ::= COMMA */
110986 {pParse->constraintName.n = 0;}
110987         break;
110988       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
110989 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
110990         break;
110991       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
110992 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
110993         break;
110994       case 96: /* tcons ::= CHECK LP expr RP onconf */
110995 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
110996         break;
110997       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
110998 {
110999     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
111000     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
111001 }
111002         break;
111003       case 100: /* onconf ::= */
111004 {yygotominor.yy392 = OE_Default;}
111005         break;
111006       case 102: /* orconf ::= */
111007 {yygotominor.yy258 = OE_Default;}
111008         break;
111009       case 103: /* orconf ::= OR resolvetype */
111010 {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
111011         break;
111012       case 105: /* resolvetype ::= IGNORE */
111013 {yygotominor.yy392 = OE_Ignore;}
111014         break;
111015       case 106: /* resolvetype ::= REPLACE */
111016 {yygotominor.yy392 = OE_Replace;}
111017         break;
111018       case 107: /* cmd ::= DROP TABLE ifexists fullname */
111019 {
111020   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
111021 }
111022         break;
111023       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
111024 {
111025   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);
111026 }
111027         break;
111028       case 111: /* cmd ::= DROP VIEW ifexists fullname */
111029 {
111030   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
111031 }
111032         break;
111033       case 112: /* cmd ::= select */
111034 {
111035   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
111036   sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
111037   sqlite3ExplainBegin(pParse->pVdbe);
111038   sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
111039   sqlite3ExplainFinish(pParse->pVdbe);
111040   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
111041 }
111042         break;
111043       case 113: /* select ::= oneselect */
111044 {yygotominor.yy159 = yymsp[0].minor.yy159;}
111045         break;
111046       case 114: /* select ::= select multiselect_op oneselect */
111047 {
111048   if( yymsp[0].minor.yy159 ){
111049     yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
111050     yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
111051   }else{
111052     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
111053   }
111054   yygotominor.yy159 = yymsp[0].minor.yy159;
111055 }
111056         break;
111057       case 116: /* multiselect_op ::= UNION ALL */
111058 {yygotominor.yy392 = TK_ALL;}
111059         break;
111060       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
111061 {
111062   yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy305,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
111063 }
111064         break;
111065       case 119: /* distinct ::= DISTINCT */
111066 {yygotominor.yy305 = SF_Distinct;}
111067         break;
111068       case 120: /* distinct ::= ALL */
111069       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
111070 {yygotominor.yy305 = 0;}
111071         break;
111072       case 122: /* sclp ::= selcollist COMMA */
111073       case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
111074 {yygotominor.yy442 = yymsp[-1].minor.yy442;}
111075         break;
111076       case 123: /* sclp ::= */
111077       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
111078       case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
111079       case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
111080       case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
111081 {yygotominor.yy442 = 0;}
111082         break;
111083       case 124: /* selcollist ::= sclp expr as */
111084 {
111085    yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
111086    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
111087    sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
111088 }
111089         break;
111090       case 125: /* selcollist ::= sclp STAR */
111091 {
111092   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
111093   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
111094 }
111095         break;
111096       case 126: /* selcollist ::= sclp nm DOT STAR */
111097 {
111098   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
111099   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
111100   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
111101   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
111102 }
111103         break;
111104       case 129: /* as ::= */
111105 {yygotominor.yy0.n = 0;}
111106         break;
111107       case 130: /* from ::= */
111108 {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
111109         break;
111110       case 131: /* from ::= FROM seltablist */
111111 {
111112   yygotominor.yy347 = yymsp[0].minor.yy347;
111113   sqlite3SrcListShiftJoinType(yygotominor.yy347);
111114 }
111115         break;
111116       case 132: /* stl_prefix ::= seltablist joinop */
111117 {
111118    yygotominor.yy347 = yymsp[-1].minor.yy347;
111119    if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
111120 }
111121         break;
111122       case 133: /* stl_prefix ::= */
111123 {yygotominor.yy347 = 0;}
111124         break;
111125       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
111126 {
111127   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);
111128   sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
111129 }
111130         break;
111131       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
111132 {
111133     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);
111134   }
111135         break;
111136       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
111137 {
111138     if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
111139       yygotominor.yy347 = yymsp[-4].minor.yy347;
111140     }else if( yymsp[-4].minor.yy347->nSrc==1 ){
111141       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
111142       if( yygotominor.yy347 ){
111143         struct SrcList_item *pNew = &yygotominor.yy347->a[yygotominor.yy347->nSrc-1];
111144         struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
111145         pNew->zName = pOld->zName;
111146         pNew->zDatabase = pOld->zDatabase;
111147         pOld->zName = pOld->zDatabase = 0;
111148       }
111149       sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
111150     }else{
111151       Select *pSubquery;
111152       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
111153       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
111154       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
111155     }
111156   }
111157         break;
111158       case 137: /* dbnm ::= */
111159       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
111160 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
111161         break;
111162       case 139: /* fullname ::= nm dbnm */
111163 {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
111164         break;
111165       case 140: /* joinop ::= COMMA|JOIN */
111166 { yygotominor.yy392 = JT_INNER; }
111167         break;
111168       case 141: /* joinop ::= JOIN_KW JOIN */
111169 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
111170         break;
111171       case 142: /* joinop ::= JOIN_KW nm JOIN */
111172 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
111173         break;
111174       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
111175 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
111176         break;
111177       case 144: /* on_opt ::= ON expr */
111178       case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
111179       case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
111180       case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
111181       case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
111182 {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
111183         break;
111184       case 145: /* on_opt ::= */
111185       case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
111186       case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
111187       case 235: /* case_else ::= */ yytestcase(yyruleno==235);
111188       case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
111189 {yygotominor.yy122 = 0;}
111190         break;
111191       case 148: /* indexed_opt ::= NOT INDEXED */
111192 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
111193         break;
111194       case 149: /* using_opt ::= USING LP inscollist RP */
111195       case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
111196 {yygotominor.yy180 = yymsp[-1].minor.yy180;}
111197         break;
111198       case 150: /* using_opt ::= */
111199       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
111200 {yygotominor.yy180 = 0;}
111201         break;
111202       case 152: /* orderby_opt ::= ORDER BY sortlist */
111203       case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
111204       case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
111205 {yygotominor.yy442 = yymsp[0].minor.yy442;}
111206         break;
111207       case 153: /* sortlist ::= sortlist COMMA expr sortorder */
111208 {
111209   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
111210   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
111211 }
111212         break;
111213       case 154: /* sortlist ::= expr sortorder */
111214 {
111215   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
111216   if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
111217 }
111218         break;
111219       case 155: /* sortorder ::= ASC */
111220       case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
111221 {yygotominor.yy392 = SQLITE_SO_ASC;}
111222         break;
111223       case 156: /* sortorder ::= DESC */
111224 {yygotominor.yy392 = SQLITE_SO_DESC;}
111225         break;
111226       case 162: /* limit_opt ::= */
111227 {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
111228         break;
111229       case 163: /* limit_opt ::= LIMIT expr */
111230 {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
111231         break;
111232       case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
111233 {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
111234         break;
111235       case 165: /* limit_opt ::= LIMIT expr COMMA expr */
111236 {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
111237         break;
111238       case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
111239 {
111240   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
111241   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
111242 }
111243         break;
111244       case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
111245 {
111246   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
111247   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list"); 
111248   sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
111249 }
111250         break;
111251       case 170: /* setlist ::= setlist COMMA nm EQ expr */
111252 {
111253   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
111254   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
111255 }
111256         break;
111257       case 171: /* setlist ::= nm EQ expr */
111258 {
111259   yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
111260   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
111261 }
111262         break;
111263       case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
111264 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
111265         break;
111266       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
111267 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
111268         break;
111269       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
111270 {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
111271         break;
111272       case 175: /* insert_cmd ::= INSERT orconf */
111273 {yygotominor.yy258 = yymsp[0].minor.yy258;}
111274         break;
111275       case 176: /* insert_cmd ::= REPLACE */
111276 {yygotominor.yy258 = OE_Replace;}
111277         break;
111278       case 177: /* valuelist ::= VALUES LP nexprlist RP */
111279 {
111280   yygotominor.yy487.pList = yymsp[-1].minor.yy442;
111281   yygotominor.yy487.pSelect = 0;
111282 }
111283         break;
111284       case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
111285 {
111286   Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
111287   if( yymsp[-4].minor.yy487.pList ){
111288     yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
111289     yymsp[-4].minor.yy487.pList = 0;
111290   }
111291   yygotominor.yy487.pList = 0;
111292   if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
111293     sqlite3SelectDelete(pParse->db, pRight);
111294     sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
111295     yygotominor.yy487.pSelect = 0;
111296   }else{
111297     pRight->op = TK_ALL;
111298     pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
111299     pRight->selFlags |= SF_Values;
111300     pRight->pPrior->selFlags |= SF_Values;
111301     yygotominor.yy487.pSelect = pRight;
111302   }
111303 }
111304         break;
111305       case 181: /* inscollist ::= inscollist COMMA nm */
111306 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
111307         break;
111308       case 182: /* inscollist ::= nm */
111309 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
111310         break;
111311       case 183: /* expr ::= term */
111312 {yygotominor.yy342 = yymsp[0].minor.yy342;}
111313         break;
111314       case 184: /* expr ::= LP expr RP */
111315 {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
111316         break;
111317       case 185: /* term ::= NULL */
111318       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
111319       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
111320 {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
111321         break;
111322       case 186: /* expr ::= id */
111323       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
111324 {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
111325         break;
111326       case 188: /* expr ::= nm DOT nm */
111327 {
111328   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
111329   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
111330   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
111331   spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
111332 }
111333         break;
111334       case 189: /* expr ::= nm DOT nm DOT nm */
111335 {
111336   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
111337   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
111338   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
111339   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
111340   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
111341   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
111342 }
111343         break;
111344       case 192: /* expr ::= REGISTER */
111345 {
111346   /* When doing a nested parse, one can include terms in an expression
111347   ** that look like this:   #1 #2 ...  These terms refer to registers
111348   ** in the virtual machine.  #N is the N-th register. */
111349   if( pParse->nested==0 ){
111350     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
111351     yygotominor.yy342.pExpr = 0;
111352   }else{
111353     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
111354     if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
111355   }
111356   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
111357 }
111358         break;
111359       case 193: /* expr ::= VARIABLE */
111360 {
111361   spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
111362   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
111363   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
111364 }
111365         break;
111366       case 194: /* expr ::= expr COLLATE ids */
111367 {
111368   yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
111369   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
111370   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111371 }
111372         break;
111373       case 195: /* expr ::= CAST LP expr AS typetoken RP */
111374 {
111375   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
111376   spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
111377 }
111378         break;
111379       case 196: /* expr ::= ID LP distinct exprlist RP */
111380 {
111381   if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
111382     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
111383   }
111384   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
111385   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
111386   if( yymsp[-2].minor.yy305 && yygotominor.yy342.pExpr ){
111387     yygotominor.yy342.pExpr->flags |= EP_Distinct;
111388   }
111389 }
111390         break;
111391       case 197: /* expr ::= ID LP STAR RP */
111392 {
111393   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
111394   spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
111395 }
111396         break;
111397       case 198: /* term ::= CTIME_KW */
111398 {
111399   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
111400   ** treated as functions that return constants */
111401   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
111402   if( yygotominor.yy342.pExpr ){
111403     yygotominor.yy342.pExpr->op = TK_CONST_FUNC;  
111404   }
111405   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
111406 }
111407         break;
111408       case 199: /* expr ::= expr AND expr */
111409       case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
111410       case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
111411       case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
111412       case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
111413       case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
111414       case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
111415       case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
111416 {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
111417         break;
111418       case 207: /* likeop ::= LIKE_KW */
111419       case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
111420 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
111421         break;
111422       case 208: /* likeop ::= NOT LIKE_KW */
111423       case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
111424 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
111425         break;
111426       case 211: /* expr ::= expr likeop expr */
111427 {
111428   ExprList *pList;
111429   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
111430   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
111431   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
111432   if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111433   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
111434   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
111435   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
111436 }
111437         break;
111438       case 212: /* expr ::= expr likeop expr ESCAPE expr */
111439 {
111440   ExprList *pList;
111441   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
111442   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
111443   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
111444   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
111445   if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111446   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
111447   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
111448   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
111449 }
111450         break;
111451       case 213: /* expr ::= expr ISNULL|NOTNULL */
111452 {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
111453         break;
111454       case 214: /* expr ::= expr NOT NULL */
111455 {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
111456         break;
111457       case 215: /* expr ::= expr IS expr */
111458 {
111459   spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
111460   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
111461 }
111462         break;
111463       case 216: /* expr ::= expr IS NOT expr */
111464 {
111465   spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
111466   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
111467 }
111468         break;
111469       case 217: /* expr ::= NOT expr */
111470       case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
111471 {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
111472         break;
111473       case 219: /* expr ::= MINUS expr */
111474 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
111475         break;
111476       case 220: /* expr ::= PLUS expr */
111477 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
111478         break;
111479       case 223: /* expr ::= expr between_op expr AND expr */
111480 {
111481   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
111482   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
111483   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
111484   if( yygotominor.yy342.pExpr ){
111485     yygotominor.yy342.pExpr->x.pList = pList;
111486   }else{
111487     sqlite3ExprListDelete(pParse->db, pList);
111488   } 
111489   if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111490   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
111491   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
111492 }
111493         break;
111494       case 226: /* expr ::= expr in_op LP exprlist RP */
111495 {
111496     if( yymsp[-1].minor.yy442==0 ){
111497       /* Expressions of the form
111498       **
111499       **      expr1 IN ()
111500       **      expr1 NOT IN ()
111501       **
111502       ** simplify to constants 0 (false) and 1 (true), respectively,
111503       ** regardless of the value of expr1.
111504       */
111505       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
111506       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
111507     }else{
111508       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
111509       if( yygotominor.yy342.pExpr ){
111510         yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
111511         sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111512       }else{
111513         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
111514       }
111515       if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111516     }
111517     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
111518     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111519   }
111520         break;
111521       case 227: /* expr ::= LP select RP */
111522 {
111523     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
111524     if( yygotominor.yy342.pExpr ){
111525       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
111526       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
111527       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111528     }else{
111529       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
111530     }
111531     yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
111532     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111533   }
111534         break;
111535       case 228: /* expr ::= expr in_op LP select RP */
111536 {
111537     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
111538     if( yygotominor.yy342.pExpr ){
111539       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
111540       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
111541       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111542     }else{
111543       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
111544     }
111545     if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111546     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
111547     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111548   }
111549         break;
111550       case 229: /* expr ::= expr in_op nm dbnm */
111551 {
111552     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
111553     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
111554     if( yygotominor.yy342.pExpr ){
111555       yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
111556       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
111557       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111558     }else{
111559       sqlite3SrcListDelete(pParse->db, pSrc);
111560     }
111561     if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111562     yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
111563     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];
111564   }
111565         break;
111566       case 230: /* expr ::= EXISTS LP select RP */
111567 {
111568     Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
111569     if( p ){
111570       p->x.pSelect = yymsp[-1].minor.yy159;
111571       ExprSetProperty(p, EP_xIsSelect);
111572       sqlite3ExprSetHeight(pParse, p);
111573     }else{
111574       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
111575     }
111576     yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
111577     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111578   }
111579         break;
111580       case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
111581 {
111582   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
111583   if( yygotominor.yy342.pExpr ){
111584     yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
111585     sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111586   }else{
111587     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
111588   }
111589   yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
111590   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111591 }
111592         break;
111593       case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
111594 {
111595   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
111596   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
111597 }
111598         break;
111599       case 233: /* case_exprlist ::= WHEN expr THEN expr */
111600 {
111601   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
111602   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
111603 }
111604         break;
111605       case 240: /* nexprlist ::= nexprlist COMMA expr */
111606 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
111607         break;
111608       case 241: /* nexprlist ::= expr */
111609 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
111610         break;
111611       case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
111612 {
111613   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
111614                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
111615                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
111616 }
111617         break;
111618       case 243: /* uniqueflag ::= UNIQUE */
111619       case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
111620 {yygotominor.yy392 = OE_Abort;}
111621         break;
111622       case 244: /* uniqueflag ::= */
111623 {yygotominor.yy392 = OE_None;}
111624         break;
111625       case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
111626 {
111627   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
111628   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
111629   sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
111630   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
111631   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
111632 }
111633         break;
111634       case 248: /* idxlist ::= nm collate sortorder */
111635 {
111636   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
111637   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
111638   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
111639   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
111640   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
111641 }
111642         break;
111643       case 249: /* collate ::= */
111644 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
111645         break;
111646       case 251: /* cmd ::= DROP INDEX ifexists fullname */
111647 {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
111648         break;
111649       case 252: /* cmd ::= VACUUM */
111650       case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
111651 {sqlite3Vacuum(pParse);}
111652         break;
111653       case 254: /* cmd ::= PRAGMA nm dbnm */
111654 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
111655         break;
111656       case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
111657 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
111658         break;
111659       case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
111660 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
111661         break;
111662       case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
111663 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
111664         break;
111665       case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
111666 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
111667         break;
111668       case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
111669 {
111670   Token all;
111671   all.z = yymsp[-3].minor.yy0.z;
111672   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
111673   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
111674 }
111675         break;
111676       case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
111677 {
111678   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);
111679   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
111680 }
111681         break;
111682       case 270: /* trigger_time ::= BEFORE */
111683       case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
111684 { yygotominor.yy392 = TK_BEFORE; }
111685         break;
111686       case 271: /* trigger_time ::= AFTER */
111687 { yygotominor.yy392 = TK_AFTER;  }
111688         break;
111689       case 272: /* trigger_time ::= INSTEAD OF */
111690 { yygotominor.yy392 = TK_INSTEAD;}
111691         break;
111692       case 274: /* trigger_event ::= DELETE|INSERT */
111693       case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
111694 {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
111695         break;
111696       case 276: /* trigger_event ::= UPDATE OF inscollist */
111697 {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
111698         break;
111699       case 279: /* when_clause ::= */
111700       case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
111701 { yygotominor.yy122 = 0; }
111702         break;
111703       case 280: /* when_clause ::= WHEN expr */
111704       case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
111705 { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
111706         break;
111707       case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
111708 {
111709   assert( yymsp[-2].minor.yy327!=0 );
111710   yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
111711   yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
111712   yygotominor.yy327 = yymsp[-2].minor.yy327;
111713 }
111714         break;
111715       case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
111716
111717   assert( yymsp[-1].minor.yy327!=0 );
111718   yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
111719   yygotominor.yy327 = yymsp[-1].minor.yy327;
111720 }
111721         break;
111722       case 284: /* trnm ::= nm DOT nm */
111723 {
111724   yygotominor.yy0 = yymsp[0].minor.yy0;
111725   sqlite3ErrorMsg(pParse, 
111726         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
111727         "statements within triggers");
111728 }
111729         break;
111730       case 286: /* tridxby ::= INDEXED BY nm */
111731 {
111732   sqlite3ErrorMsg(pParse,
111733         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
111734         "within triggers");
111735 }
111736         break;
111737       case 287: /* tridxby ::= NOT INDEXED */
111738 {
111739   sqlite3ErrorMsg(pParse,
111740         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
111741         "within triggers");
111742 }
111743         break;
111744       case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
111745 { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
111746         break;
111747       case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
111748 {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);}
111749         break;
111750       case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
111751 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
111752         break;
111753       case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
111754 {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
111755         break;
111756       case 292: /* trigger_cmd ::= select */
111757 {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
111758         break;
111759       case 293: /* expr ::= RAISE LP IGNORE RP */
111760 {
111761   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
111762   if( yygotominor.yy342.pExpr ){
111763     yygotominor.yy342.pExpr->affinity = OE_Ignore;
111764   }
111765   yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
111766   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111767 }
111768         break;
111769       case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
111770 {
111771   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
111772   if( yygotominor.yy342.pExpr ) {
111773     yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
111774   }
111775   yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
111776   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111777 }
111778         break;
111779       case 295: /* raisetype ::= ROLLBACK */
111780 {yygotominor.yy392 = OE_Rollback;}
111781         break;
111782       case 297: /* raisetype ::= FAIL */
111783 {yygotominor.yy392 = OE_Fail;}
111784         break;
111785       case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
111786 {
111787   sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
111788 }
111789         break;
111790       case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
111791 {
111792   sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
111793 }
111794         break;
111795       case 300: /* cmd ::= DETACH database_kw_opt expr */
111796 {
111797   sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
111798 }
111799         break;
111800       case 305: /* cmd ::= REINDEX */
111801 {sqlite3Reindex(pParse, 0, 0);}
111802         break;
111803       case 306: /* cmd ::= REINDEX nm dbnm */
111804 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
111805         break;
111806       case 307: /* cmd ::= ANALYZE */
111807 {sqlite3Analyze(pParse, 0, 0);}
111808         break;
111809       case 308: /* cmd ::= ANALYZE nm dbnm */
111810 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
111811         break;
111812       case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
111813 {
111814   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
111815 }
111816         break;
111817       case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
111818 {
111819   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
111820 }
111821         break;
111822       case 311: /* add_column_fullname ::= fullname */
111823 {
111824   pParse->db->lookaside.bEnabled = 0;
111825   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
111826 }
111827         break;
111828       case 314: /* cmd ::= create_vtab */
111829 {sqlite3VtabFinishParse(pParse,0);}
111830         break;
111831       case 315: /* cmd ::= create_vtab LP vtabarglist RP */
111832 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
111833         break;
111834       case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
111835 {
111836     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
111837 }
111838         break;
111839       case 319: /* vtabarg ::= */
111840 {sqlite3VtabArgInit(pParse);}
111841         break;
111842       case 321: /* vtabargtoken ::= ANY */
111843       case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
111844       case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
111845 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
111846         break;
111847       default:
111848       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
111849       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
111850       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
111851       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
111852       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
111853       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
111854       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
111855       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
111856       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
111857       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
111858       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
111859       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
111860       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
111861       /* (44) type ::= */ yytestcase(yyruleno==44);
111862       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
111863       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
111864       /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
111865       /* (54) carglist ::= */ yytestcase(yyruleno==54);
111866       /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
111867       /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
111868       /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
111869       /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
111870       /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
111871       /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
111872       /* (285) tridxby ::= */ yytestcase(yyruleno==285);
111873       /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
111874       /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
111875       /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
111876       /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
111877       /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
111878       /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
111879       /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
111880       /* (324) anylist ::= */ yytestcase(yyruleno==324);
111881       /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
111882       /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
111883         break;
111884   };
111885   assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
111886   yygoto = yyRuleInfo[yyruleno].lhs;
111887   yysize = yyRuleInfo[yyruleno].nrhs;
111888   yypParser->yyidx -= yysize;
111889   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
111890   if( yyact < YYNSTATE ){
111891 #ifdef NDEBUG
111892     /* If we are not debugging and the reduce action popped at least
111893     ** one element off the stack, then we can push the new element back
111894     ** onto the stack here, and skip the stack overflow test in yy_shift().
111895     ** That gives a significant speed improvement. */
111896     if( yysize ){
111897       yypParser->yyidx++;
111898       yymsp -= yysize-1;
111899       yymsp->stateno = (YYACTIONTYPE)yyact;
111900       yymsp->major = (YYCODETYPE)yygoto;
111901       yymsp->minor = yygotominor;
111902     }else
111903 #endif
111904     {
111905       yy_shift(yypParser,yyact,yygoto,&yygotominor);
111906     }
111907   }else{
111908     assert( yyact == YYNSTATE + YYNRULE + 1 );
111909     yy_accept(yypParser);
111910   }
111911 }
111912
111913 /*
111914 ** The following code executes when the parse fails
111915 */
111916 #ifndef YYNOERRORRECOVERY
111917 static void yy_parse_failed(
111918   yyParser *yypParser           /* The parser */
111919 ){
111920   sqlite3ParserARG_FETCH;
111921 #ifndef NDEBUG
111922   if( yyTraceFILE ){
111923     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
111924   }
111925 #endif
111926   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111927   /* Here code is inserted which will be executed whenever the
111928   ** parser fails */
111929   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111930 }
111931 #endif /* YYNOERRORRECOVERY */
111932
111933 /*
111934 ** The following code executes when a syntax error first occurs.
111935 */
111936 static void yy_syntax_error(
111937   yyParser *yypParser,           /* The parser */
111938   int yymajor,                   /* The major type of the error token */
111939   YYMINORTYPE yyminor            /* The minor type of the error token */
111940 ){
111941   sqlite3ParserARG_FETCH;
111942 #define TOKEN (yyminor.yy0)
111943
111944   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
111945   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
111946   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
111947   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111948 }
111949
111950 /*
111951 ** The following is executed when the parser accepts
111952 */
111953 static void yy_accept(
111954   yyParser *yypParser           /* The parser */
111955 ){
111956   sqlite3ParserARG_FETCH;
111957 #ifndef NDEBUG
111958   if( yyTraceFILE ){
111959     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
111960   }
111961 #endif
111962   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111963   /* Here code is inserted which will be executed whenever the
111964   ** parser accepts */
111965   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111966 }
111967
111968 /* The main parser program.
111969 ** The first argument is a pointer to a structure obtained from
111970 ** "sqlite3ParserAlloc" which describes the current state of the parser.
111971 ** The second argument is the major token number.  The third is
111972 ** the minor token.  The fourth optional argument is whatever the
111973 ** user wants (and specified in the grammar) and is available for
111974 ** use by the action routines.
111975 **
111976 ** Inputs:
111977 ** <ul>
111978 ** <li> A pointer to the parser (an opaque structure.)
111979 ** <li> The major token number.
111980 ** <li> The minor token number.
111981 ** <li> An option argument of a grammar-specified type.
111982 ** </ul>
111983 **
111984 ** Outputs:
111985 ** None.
111986 */
111987 SQLITE_PRIVATE void sqlite3Parser(
111988   void *yyp,                   /* The parser */
111989   int yymajor,                 /* The major token code number */
111990   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
111991   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
111992 ){
111993   YYMINORTYPE yyminorunion;
111994   int yyact;            /* The parser action. */
111995 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
111996   int yyendofinput;     /* True if we are at the end of input */
111997 #endif
111998 #ifdef YYERRORSYMBOL
111999   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
112000 #endif
112001   yyParser *yypParser;  /* The parser */
112002
112003   /* (re)initialize the parser, if necessary */
112004   yypParser = (yyParser*)yyp;
112005   if( yypParser->yyidx<0 ){
112006 #if YYSTACKDEPTH<=0
112007     if( yypParser->yystksz <=0 ){
112008       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
112009       yyminorunion = yyzerominor;
112010       yyStackOverflow(yypParser, &yyminorunion);
112011       return;
112012     }
112013 #endif
112014     yypParser->yyidx = 0;
112015     yypParser->yyerrcnt = -1;
112016     yypParser->yystack[0].stateno = 0;
112017     yypParser->yystack[0].major = 0;
112018   }
112019   yyminorunion.yy0 = yyminor;
112020 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
112021   yyendofinput = (yymajor==0);
112022 #endif
112023   sqlite3ParserARG_STORE;
112024
112025 #ifndef NDEBUG
112026   if( yyTraceFILE ){
112027     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
112028   }
112029 #endif
112030
112031   do{
112032     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
112033     if( yyact<YYNSTATE ){
112034       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
112035       yypParser->yyerrcnt--;
112036       yymajor = YYNOCODE;
112037     }else if( yyact < YYNSTATE + YYNRULE ){
112038       yy_reduce(yypParser,yyact-YYNSTATE);
112039     }else{
112040       assert( yyact == YY_ERROR_ACTION );
112041 #ifdef YYERRORSYMBOL
112042       int yymx;
112043 #endif
112044 #ifndef NDEBUG
112045       if( yyTraceFILE ){
112046         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
112047       }
112048 #endif
112049 #ifdef YYERRORSYMBOL
112050       /* A syntax error has occurred.
112051       ** The response to an error depends upon whether or not the
112052       ** grammar defines an error token "ERROR".  
112053       **
112054       ** This is what we do if the grammar does define ERROR:
112055       **
112056       **  * Call the %syntax_error function.
112057       **
112058       **  * Begin popping the stack until we enter a state where
112059       **    it is legal to shift the error symbol, then shift
112060       **    the error symbol.
112061       **
112062       **  * Set the error count to three.
112063       **
112064       **  * Begin accepting and shifting new tokens.  No new error
112065       **    processing will occur until three tokens have been
112066       **    shifted successfully.
112067       **
112068       */
112069       if( yypParser->yyerrcnt<0 ){
112070         yy_syntax_error(yypParser,yymajor,yyminorunion);
112071       }
112072       yymx = yypParser->yystack[yypParser->yyidx].major;
112073       if( yymx==YYERRORSYMBOL || yyerrorhit ){
112074 #ifndef NDEBUG
112075         if( yyTraceFILE ){
112076           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
112077              yyTracePrompt,yyTokenName[yymajor]);
112078         }
112079 #endif
112080         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
112081         yymajor = YYNOCODE;
112082       }else{
112083          while(
112084           yypParser->yyidx >= 0 &&
112085           yymx != YYERRORSYMBOL &&
112086           (yyact = yy_find_reduce_action(
112087                         yypParser->yystack[yypParser->yyidx].stateno,
112088                         YYERRORSYMBOL)) >= YYNSTATE
112089         ){
112090           yy_pop_parser_stack(yypParser);
112091         }
112092         if( yypParser->yyidx < 0 || yymajor==0 ){
112093           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
112094           yy_parse_failed(yypParser);
112095           yymajor = YYNOCODE;
112096         }else if( yymx!=YYERRORSYMBOL ){
112097           YYMINORTYPE u2;
112098           u2.YYERRSYMDT = 0;
112099           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
112100         }
112101       }
112102       yypParser->yyerrcnt = 3;
112103       yyerrorhit = 1;
112104 #elif defined(YYNOERRORRECOVERY)
112105       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
112106       ** do any kind of error recovery.  Instead, simply invoke the syntax
112107       ** error routine and continue going as if nothing had happened.
112108       **
112109       ** Applications can set this macro (for example inside %include) if
112110       ** they intend to abandon the parse upon the first syntax error seen.
112111       */
112112       yy_syntax_error(yypParser,yymajor,yyminorunion);
112113       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
112114       yymajor = YYNOCODE;
112115       
112116 #else  /* YYERRORSYMBOL is not defined */
112117       /* This is what we do if the grammar does not define ERROR:
112118       **
112119       **  * Report an error message, and throw away the input token.
112120       **
112121       **  * If the input token is $, then fail the parse.
112122       **
112123       ** As before, subsequent error messages are suppressed until
112124       ** three input tokens have been successfully shifted.
112125       */
112126       if( yypParser->yyerrcnt<=0 ){
112127         yy_syntax_error(yypParser,yymajor,yyminorunion);
112128       }
112129       yypParser->yyerrcnt = 3;
112130       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
112131       if( yyendofinput ){
112132         yy_parse_failed(yypParser);
112133       }
112134       yymajor = YYNOCODE;
112135 #endif
112136     }
112137   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
112138   return;
112139 }
112140
112141 /************** End of parse.c ***********************************************/
112142 /************** Begin file tokenize.c ****************************************/
112143 /*
112144 ** 2001 September 15
112145 **
112146 ** The author disclaims copyright to this source code.  In place of
112147 ** a legal notice, here is a blessing:
112148 **
112149 **    May you do good and not evil.
112150 **    May you find forgiveness for yourself and forgive others.
112151 **    May you share freely, never taking more than you give.
112152 **
112153 *************************************************************************
112154 ** An tokenizer for SQL
112155 **
112156 ** This file contains C code that splits an SQL input string up into
112157 ** individual tokens and sends those tokens one-by-one over to the
112158 ** parser for analysis.
112159 */
112160 /* #include <stdlib.h> */
112161
112162 /*
112163 ** The charMap() macro maps alphabetic characters into their
112164 ** lower-case ASCII equivalent.  On ASCII machines, this is just
112165 ** an upper-to-lower case map.  On EBCDIC machines we also need
112166 ** to adjust the encoding.  Only alphabetic characters and underscores
112167 ** need to be translated.
112168 */
112169 #ifdef SQLITE_ASCII
112170 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
112171 #endif
112172 #ifdef SQLITE_EBCDIC
112173 # define charMap(X) ebcdicToAscii[(unsigned char)X]
112174 const unsigned char ebcdicToAscii[] = {
112175 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
112176    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
112177    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
112178    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
112179    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
112180    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
112181    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
112182    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
112183    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
112184    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
112185    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
112186    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
112187    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
112188    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
112189    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
112190    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
112191    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
112192 };
112193 #endif
112194
112195 /*
112196 ** The sqlite3KeywordCode function looks up an identifier to determine if
112197 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
112198 ** returned.  If the input is not a keyword, TK_ID is returned.
112199 **
112200 ** The implementation of this routine was generated by a program,
112201 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
112202 ** The output of the mkkeywordhash.c program is written into a file
112203 ** named keywordhash.h and then included into this source file by
112204 ** the #include below.
112205 */
112206 /************** Include keywordhash.h in the middle of tokenize.c ************/
112207 /************** Begin file keywordhash.h *************************************/
112208 /***** This file contains automatically generated code ******
112209 **
112210 ** The code in this file has been automatically generated by
112211 **
112212 **   sqlite/tool/mkkeywordhash.c
112213 **
112214 ** The code in this file implements a function that determines whether
112215 ** or not a given identifier is really an SQL keyword.  The same thing
112216 ** might be implemented more directly using a hand-written hash table.
112217 ** But by using this automatically generated code, the size of the code
112218 ** is substantially reduced.  This is important for embedded applications
112219 ** on platforms with limited memory.
112220 */
112221 /* Hash score: 175 */
112222 static int keywordCode(const char *z, int n){
112223   /* zText[] encodes 811 bytes of keywords in 541 bytes */
112224   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
112225   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
112226   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
112227   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
112228   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
112229   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
112230   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
112231   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
112232   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
112233   /*   INITIALLY                                                          */
112234   static const char zText[540] = {
112235     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
112236     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
112237     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
112238     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
112239     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
112240     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
112241     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
112242     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
112243     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
112244     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
112245     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
112246     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
112247     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
112248     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
112249     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
112250     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
112251     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
112252     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
112253     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
112254     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
112255     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
112256     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
112257     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
112258     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
112259     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
112260     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
112261     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
112262     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
112263     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
112264     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
112265   };
112266   static const unsigned char aHash[127] = {
112267       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
112268       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
112269      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
112270        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
112271        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
112272       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
112273       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
112274       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
112275       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
112276       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
112277   };
112278   static const unsigned char aNext[121] = {
112279        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
112280        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
112281        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
112282        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
112283        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
112284       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
112285       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
112286        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
112287      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
112288       35,  64,   0,   0,
112289   };
112290   static const unsigned char aLen[121] = {
112291        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
112292        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
112293       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
112294        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
112295        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
112296        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
112297        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
112298        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
112299        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
112300        6,   4,   9,   3,
112301   };
112302   static const unsigned short int aOffset[121] = {
112303        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
112304       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
112305       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
112306      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
112307      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
112308      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
112309      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
112310      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
112311      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
112312      521, 527, 531, 536,
112313   };
112314   static const unsigned char aCode[121] = {
112315     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
112316     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
112317     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
112318     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
112319     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
112320     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
112321     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
112322     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
112323     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
112324     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
112325     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
112326     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
112327     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
112328     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
112329     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
112330     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
112331     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
112332     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
112333     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
112334     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
112335     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
112336     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
112337     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
112338     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
112339     TK_ALL,        
112340   };
112341   int h, i;
112342   if( n<2 ) return TK_ID;
112343   h = ((charMap(z[0])*4) ^
112344       (charMap(z[n-1])*3) ^
112345       n) % 127;
112346   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
112347     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
112348       testcase( i==0 ); /* REINDEX */
112349       testcase( i==1 ); /* INDEXED */
112350       testcase( i==2 ); /* INDEX */
112351       testcase( i==3 ); /* DESC */
112352       testcase( i==4 ); /* ESCAPE */
112353       testcase( i==5 ); /* EACH */
112354       testcase( i==6 ); /* CHECK */
112355       testcase( i==7 ); /* KEY */
112356       testcase( i==8 ); /* BEFORE */
112357       testcase( i==9 ); /* FOREIGN */
112358       testcase( i==10 ); /* FOR */
112359       testcase( i==11 ); /* IGNORE */
112360       testcase( i==12 ); /* REGEXP */
112361       testcase( i==13 ); /* EXPLAIN */
112362       testcase( i==14 ); /* INSTEAD */
112363       testcase( i==15 ); /* ADD */
112364       testcase( i==16 ); /* DATABASE */
112365       testcase( i==17 ); /* AS */
112366       testcase( i==18 ); /* SELECT */
112367       testcase( i==19 ); /* TABLE */
112368       testcase( i==20 ); /* LEFT */
112369       testcase( i==21 ); /* THEN */
112370       testcase( i==22 ); /* END */
112371       testcase( i==23 ); /* DEFERRABLE */
112372       testcase( i==24 ); /* ELSE */
112373       testcase( i==25 ); /* EXCEPT */
112374       testcase( i==26 ); /* TRANSACTION */
112375       testcase( i==27 ); /* ACTION */
112376       testcase( i==28 ); /* ON */
112377       testcase( i==29 ); /* NATURAL */
112378       testcase( i==30 ); /* ALTER */
112379       testcase( i==31 ); /* RAISE */
112380       testcase( i==32 ); /* EXCLUSIVE */
112381       testcase( i==33 ); /* EXISTS */
112382       testcase( i==34 ); /* SAVEPOINT */
112383       testcase( i==35 ); /* INTERSECT */
112384       testcase( i==36 ); /* TRIGGER */
112385       testcase( i==37 ); /* REFERENCES */
112386       testcase( i==38 ); /* CONSTRAINT */
112387       testcase( i==39 ); /* INTO */
112388       testcase( i==40 ); /* OFFSET */
112389       testcase( i==41 ); /* OF */
112390       testcase( i==42 ); /* SET */
112391       testcase( i==43 ); /* TEMPORARY */
112392       testcase( i==44 ); /* TEMP */
112393       testcase( i==45 ); /* OR */
112394       testcase( i==46 ); /* UNIQUE */
112395       testcase( i==47 ); /* QUERY */
112396       testcase( i==48 ); /* ATTACH */
112397       testcase( i==49 ); /* HAVING */
112398       testcase( i==50 ); /* GROUP */
112399       testcase( i==51 ); /* UPDATE */
112400       testcase( i==52 ); /* BEGIN */
112401       testcase( i==53 ); /* INNER */
112402       testcase( i==54 ); /* RELEASE */
112403       testcase( i==55 ); /* BETWEEN */
112404       testcase( i==56 ); /* NOTNULL */
112405       testcase( i==57 ); /* NOT */
112406       testcase( i==58 ); /* NO */
112407       testcase( i==59 ); /* NULL */
112408       testcase( i==60 ); /* LIKE */
112409       testcase( i==61 ); /* CASCADE */
112410       testcase( i==62 ); /* ASC */
112411       testcase( i==63 ); /* DELETE */
112412       testcase( i==64 ); /* CASE */
112413       testcase( i==65 ); /* COLLATE */
112414       testcase( i==66 ); /* CREATE */
112415       testcase( i==67 ); /* CURRENT_DATE */
112416       testcase( i==68 ); /* DETACH */
112417       testcase( i==69 ); /* IMMEDIATE */
112418       testcase( i==70 ); /* JOIN */
112419       testcase( i==71 ); /* INSERT */
112420       testcase( i==72 ); /* MATCH */
112421       testcase( i==73 ); /* PLAN */
112422       testcase( i==74 ); /* ANALYZE */
112423       testcase( i==75 ); /* PRAGMA */
112424       testcase( i==76 ); /* ABORT */
112425       testcase( i==77 ); /* VALUES */
112426       testcase( i==78 ); /* VIRTUAL */
112427       testcase( i==79 ); /* LIMIT */
112428       testcase( i==80 ); /* WHEN */
112429       testcase( i==81 ); /* WHERE */
112430       testcase( i==82 ); /* RENAME */
112431       testcase( i==83 ); /* AFTER */
112432       testcase( i==84 ); /* REPLACE */
112433       testcase( i==85 ); /* AND */
112434       testcase( i==86 ); /* DEFAULT */
112435       testcase( i==87 ); /* AUTOINCREMENT */
112436       testcase( i==88 ); /* TO */
112437       testcase( i==89 ); /* IN */
112438       testcase( i==90 ); /* CAST */
112439       testcase( i==91 ); /* COLUMN */
112440       testcase( i==92 ); /* COMMIT */
112441       testcase( i==93 ); /* CONFLICT */
112442       testcase( i==94 ); /* CROSS */
112443       testcase( i==95 ); /* CURRENT_TIMESTAMP */
112444       testcase( i==96 ); /* CURRENT_TIME */
112445       testcase( i==97 ); /* PRIMARY */
112446       testcase( i==98 ); /* DEFERRED */
112447       testcase( i==99 ); /* DISTINCT */
112448       testcase( i==100 ); /* IS */
112449       testcase( i==101 ); /* DROP */
112450       testcase( i==102 ); /* FAIL */
112451       testcase( i==103 ); /* FROM */
112452       testcase( i==104 ); /* FULL */
112453       testcase( i==105 ); /* GLOB */
112454       testcase( i==106 ); /* BY */
112455       testcase( i==107 ); /* IF */
112456       testcase( i==108 ); /* ISNULL */
112457       testcase( i==109 ); /* ORDER */
112458       testcase( i==110 ); /* RESTRICT */
112459       testcase( i==111 ); /* OUTER */
112460       testcase( i==112 ); /* RIGHT */
112461       testcase( i==113 ); /* ROLLBACK */
112462       testcase( i==114 ); /* ROW */
112463       testcase( i==115 ); /* UNION */
112464       testcase( i==116 ); /* USING */
112465       testcase( i==117 ); /* VACUUM */
112466       testcase( i==118 ); /* VIEW */
112467       testcase( i==119 ); /* INITIALLY */
112468       testcase( i==120 ); /* ALL */
112469       return aCode[i];
112470     }
112471   }
112472   return TK_ID;
112473 }
112474 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
112475   return keywordCode((char*)z, n);
112476 }
112477 #define SQLITE_N_KEYWORD 121
112478
112479 /************** End of keywordhash.h *****************************************/
112480 /************** Continuing where we left off in tokenize.c *******************/
112481
112482
112483 /*
112484 ** If X is a character that can be used in an identifier then
112485 ** IdChar(X) will be true.  Otherwise it is false.
112486 **
112487 ** For ASCII, any character with the high-order bit set is
112488 ** allowed in an identifier.  For 7-bit characters, 
112489 ** sqlite3IsIdChar[X] must be 1.
112490 **
112491 ** For EBCDIC, the rules are more complex but have the same
112492 ** end result.
112493 **
112494 ** Ticket #1066.  the SQL standard does not allow '$' in the
112495 ** middle of identfiers.  But many SQL implementations do. 
112496 ** SQLite will allow '$' in identifiers for compatibility.
112497 ** But the feature is undocumented.
112498 */
112499 #ifdef SQLITE_ASCII
112500 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
112501 #endif
112502 #ifdef SQLITE_EBCDIC
112503 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
112504 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
112505     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
112506     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
112507     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
112508     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
112509     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
112510     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
112511     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
112512     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
112513     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
112514     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
112515     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
112516     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
112517 };
112518 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
112519 #endif
112520
112521
112522 /*
112523 ** Return the length of the token that begins at z[0]. 
112524 ** Store the token type in *tokenType before returning.
112525 */
112526 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
112527   int i, c;
112528   switch( *z ){
112529     case ' ': case '\t': case '\n': case '\f': case '\r': {
112530       testcase( z[0]==' ' );
112531       testcase( z[0]=='\t' );
112532       testcase( z[0]=='\n' );
112533       testcase( z[0]=='\f' );
112534       testcase( z[0]=='\r' );
112535       for(i=1; sqlite3Isspace(z[i]); i++){}
112536       *tokenType = TK_SPACE;
112537       return i;
112538     }
112539     case '-': {
112540       if( z[1]=='-' ){
112541         /* IMP: R-50417-27976 -- syntax diagram for comments */
112542         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
112543         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
112544         return i;
112545       }
112546       *tokenType = TK_MINUS;
112547       return 1;
112548     }
112549     case '(': {
112550       *tokenType = TK_LP;
112551       return 1;
112552     }
112553     case ')': {
112554       *tokenType = TK_RP;
112555       return 1;
112556     }
112557     case ';': {
112558       *tokenType = TK_SEMI;
112559       return 1;
112560     }
112561     case '+': {
112562       *tokenType = TK_PLUS;
112563       return 1;
112564     }
112565     case '*': {
112566       *tokenType = TK_STAR;
112567       return 1;
112568     }
112569     case '/': {
112570       if( z[1]!='*' || z[2]==0 ){
112571         *tokenType = TK_SLASH;
112572         return 1;
112573       }
112574       /* IMP: R-50417-27976 -- syntax diagram for comments */
112575       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
112576       if( c ) i++;
112577       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
112578       return i;
112579     }
112580     case '%': {
112581       *tokenType = TK_REM;
112582       return 1;
112583     }
112584     case '=': {
112585       *tokenType = TK_EQ;
112586       return 1 + (z[1]=='=');
112587     }
112588     case '<': {
112589       if( (c=z[1])=='=' ){
112590         *tokenType = TK_LE;
112591         return 2;
112592       }else if( c=='>' ){
112593         *tokenType = TK_NE;
112594         return 2;
112595       }else if( c=='<' ){
112596         *tokenType = TK_LSHIFT;
112597         return 2;
112598       }else{
112599         *tokenType = TK_LT;
112600         return 1;
112601       }
112602     }
112603     case '>': {
112604       if( (c=z[1])=='=' ){
112605         *tokenType = TK_GE;
112606         return 2;
112607       }else if( c=='>' ){
112608         *tokenType = TK_RSHIFT;
112609         return 2;
112610       }else{
112611         *tokenType = TK_GT;
112612         return 1;
112613       }
112614     }
112615     case '!': {
112616       if( z[1]!='=' ){
112617         *tokenType = TK_ILLEGAL;
112618         return 2;
112619       }else{
112620         *tokenType = TK_NE;
112621         return 2;
112622       }
112623     }
112624     case '|': {
112625       if( z[1]!='|' ){
112626         *tokenType = TK_BITOR;
112627         return 1;
112628       }else{
112629         *tokenType = TK_CONCAT;
112630         return 2;
112631       }
112632     }
112633     case ',': {
112634       *tokenType = TK_COMMA;
112635       return 1;
112636     }
112637     case '&': {
112638       *tokenType = TK_BITAND;
112639       return 1;
112640     }
112641     case '~': {
112642       *tokenType = TK_BITNOT;
112643       return 1;
112644     }
112645     case '`':
112646     case '\'':
112647     case '"': {
112648       int delim = z[0];
112649       testcase( delim=='`' );
112650       testcase( delim=='\'' );
112651       testcase( delim=='"' );
112652       for(i=1; (c=z[i])!=0; i++){
112653         if( c==delim ){
112654           if( z[i+1]==delim ){
112655             i++;
112656           }else{
112657             break;
112658           }
112659         }
112660       }
112661       if( c=='\'' ){
112662         *tokenType = TK_STRING;
112663         return i+1;
112664       }else if( c!=0 ){
112665         *tokenType = TK_ID;
112666         return i+1;
112667       }else{
112668         *tokenType = TK_ILLEGAL;
112669         return i;
112670       }
112671     }
112672     case '.': {
112673 #ifndef SQLITE_OMIT_FLOATING_POINT
112674       if( !sqlite3Isdigit(z[1]) )
112675 #endif
112676       {
112677         *tokenType = TK_DOT;
112678         return 1;
112679       }
112680       /* If the next character is a digit, this is a floating point
112681       ** number that begins with ".".  Fall thru into the next case */
112682     }
112683     case '0': case '1': case '2': case '3': case '4':
112684     case '5': case '6': case '7': case '8': case '9': {
112685       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
112686       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
112687       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
112688       testcase( z[0]=='9' );
112689       *tokenType = TK_INTEGER;
112690       for(i=0; sqlite3Isdigit(z[i]); i++){}
112691 #ifndef SQLITE_OMIT_FLOATING_POINT
112692       if( z[i]=='.' ){
112693         i++;
112694         while( sqlite3Isdigit(z[i]) ){ i++; }
112695         *tokenType = TK_FLOAT;
112696       }
112697       if( (z[i]=='e' || z[i]=='E') &&
112698            ( sqlite3Isdigit(z[i+1]) 
112699             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
112700            )
112701       ){
112702         i += 2;
112703         while( sqlite3Isdigit(z[i]) ){ i++; }
112704         *tokenType = TK_FLOAT;
112705       }
112706 #endif
112707       while( IdChar(z[i]) ){
112708         *tokenType = TK_ILLEGAL;
112709         i++;
112710       }
112711       return i;
112712     }
112713     case '[': {
112714       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
112715       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
112716       return i;
112717     }
112718     case '?': {
112719       *tokenType = TK_VARIABLE;
112720       for(i=1; sqlite3Isdigit(z[i]); i++){}
112721       return i;
112722     }
112723     case '#': {
112724       for(i=1; sqlite3Isdigit(z[i]); i++){}
112725       if( i>1 ){
112726         /* Parameters of the form #NNN (where NNN is a number) are used
112727         ** internally by sqlite3NestedParse.  */
112728         *tokenType = TK_REGISTER;
112729         return i;
112730       }
112731       /* Fall through into the next case if the '#' is not followed by
112732       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
112733     }
112734 #ifndef SQLITE_OMIT_TCL_VARIABLE
112735     case '$':
112736 #endif
112737     case '@':  /* For compatibility with MS SQL Server */
112738     case ':': {
112739       int n = 0;
112740       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
112741       *tokenType = TK_VARIABLE;
112742       for(i=1; (c=z[i])!=0; i++){
112743         if( IdChar(c) ){
112744           n++;
112745 #ifndef SQLITE_OMIT_TCL_VARIABLE
112746         }else if( c=='(' && n>0 ){
112747           do{
112748             i++;
112749           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
112750           if( c==')' ){
112751             i++;
112752           }else{
112753             *tokenType = TK_ILLEGAL;
112754           }
112755           break;
112756         }else if( c==':' && z[i+1]==':' ){
112757           i++;
112758 #endif
112759         }else{
112760           break;
112761         }
112762       }
112763       if( n==0 ) *tokenType = TK_ILLEGAL;
112764       return i;
112765     }
112766 #ifndef SQLITE_OMIT_BLOB_LITERAL
112767     case 'x': case 'X': {
112768       testcase( z[0]=='x' ); testcase( z[0]=='X' );
112769       if( z[1]=='\'' ){
112770         *tokenType = TK_BLOB;
112771         for(i=2; sqlite3Isxdigit(z[i]); i++){}
112772         if( z[i]!='\'' || i%2 ){
112773           *tokenType = TK_ILLEGAL;
112774           while( z[i] && z[i]!='\'' ){ i++; }
112775         }
112776         if( z[i] ) i++;
112777         return i;
112778       }
112779       /* Otherwise fall through to the next case */
112780     }
112781 #endif
112782     default: {
112783       if( !IdChar(*z) ){
112784         break;
112785       }
112786       for(i=1; IdChar(z[i]); i++){}
112787       *tokenType = keywordCode((char*)z, i);
112788       return i;
112789     }
112790   }
112791   *tokenType = TK_ILLEGAL;
112792   return 1;
112793 }
112794
112795 /*
112796 ** Run the parser on the given SQL string.  The parser structure is
112797 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
112798 ** then an and attempt is made to write an error message into 
112799 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
112800 ** error message.
112801 */
112802 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
112803   int nErr = 0;                   /* Number of errors encountered */
112804   int i;                          /* Loop counter */
112805   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
112806   int tokenType;                  /* type of the next token */
112807   int lastTokenParsed = -1;       /* type of the previous token */
112808   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
112809   sqlite3 *db = pParse->db;       /* The database connection */
112810   int mxSqlLen;                   /* Max length of an SQL string */
112811
112812
112813   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
112814   if( db->activeVdbeCnt==0 ){
112815     db->u1.isInterrupted = 0;
112816   }
112817   pParse->rc = SQLITE_OK;
112818   pParse->zTail = zSql;
112819   i = 0;
112820   assert( pzErrMsg!=0 );
112821   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
112822   if( pEngine==0 ){
112823     db->mallocFailed = 1;
112824     return SQLITE_NOMEM;
112825   }
112826   assert( pParse->pNewTable==0 );
112827   assert( pParse->pNewTrigger==0 );
112828   assert( pParse->nVar==0 );
112829   assert( pParse->nzVar==0 );
112830   assert( pParse->azVar==0 );
112831   enableLookaside = db->lookaside.bEnabled;
112832   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
112833   while( !db->mallocFailed && zSql[i]!=0 ){
112834     assert( i>=0 );
112835     pParse->sLastToken.z = &zSql[i];
112836     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
112837     i += pParse->sLastToken.n;
112838     if( i>mxSqlLen ){
112839       pParse->rc = SQLITE_TOOBIG;
112840       break;
112841     }
112842     switch( tokenType ){
112843       case TK_SPACE: {
112844         if( db->u1.isInterrupted ){
112845           sqlite3ErrorMsg(pParse, "interrupt");
112846           pParse->rc = SQLITE_INTERRUPT;
112847           goto abort_parse;
112848         }
112849         break;
112850       }
112851       case TK_ILLEGAL: {
112852         sqlite3DbFree(db, *pzErrMsg);
112853         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
112854                         &pParse->sLastToken);
112855         nErr++;
112856         goto abort_parse;
112857       }
112858       case TK_SEMI: {
112859         pParse->zTail = &zSql[i];
112860         /* Fall thru into the default case */
112861       }
112862       default: {
112863         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
112864         lastTokenParsed = tokenType;
112865         if( pParse->rc!=SQLITE_OK ){
112866           goto abort_parse;
112867         }
112868         break;
112869       }
112870     }
112871   }
112872 abort_parse:
112873   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
112874     if( lastTokenParsed!=TK_SEMI ){
112875       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
112876       pParse->zTail = &zSql[i];
112877     }
112878     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
112879   }
112880 #ifdef YYTRACKMAXSTACKDEPTH
112881   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
112882       sqlite3ParserStackPeak(pEngine)
112883   );
112884 #endif /* YYDEBUG */
112885   sqlite3ParserFree(pEngine, sqlite3_free);
112886   db->lookaside.bEnabled = enableLookaside;
112887   if( db->mallocFailed ){
112888     pParse->rc = SQLITE_NOMEM;
112889   }
112890   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
112891     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
112892   }
112893   assert( pzErrMsg!=0 );
112894   if( pParse->zErrMsg ){
112895     *pzErrMsg = pParse->zErrMsg;
112896     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
112897     pParse->zErrMsg = 0;
112898     nErr++;
112899   }
112900   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
112901     sqlite3VdbeDelete(pParse->pVdbe);
112902     pParse->pVdbe = 0;
112903   }
112904 #ifndef SQLITE_OMIT_SHARED_CACHE
112905   if( pParse->nested==0 ){
112906     sqlite3DbFree(db, pParse->aTableLock);
112907     pParse->aTableLock = 0;
112908     pParse->nTableLock = 0;
112909   }
112910 #endif
112911 #ifndef SQLITE_OMIT_VIRTUALTABLE
112912   sqlite3_free(pParse->apVtabLock);
112913 #endif
112914
112915   if( !IN_DECLARE_VTAB ){
112916     /* If the pParse->declareVtab flag is set, do not delete any table 
112917     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
112918     ** will take responsibility for freeing the Table structure.
112919     */
112920     sqlite3DeleteTable(db, pParse->pNewTable);
112921   }
112922
112923   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
112924   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
112925   sqlite3DbFree(db, pParse->azVar);
112926   sqlite3DbFree(db, pParse->aAlias);
112927   while( pParse->pAinc ){
112928     AutoincInfo *p = pParse->pAinc;
112929     pParse->pAinc = p->pNext;
112930     sqlite3DbFree(db, p);
112931   }
112932   while( pParse->pZombieTab ){
112933     Table *p = pParse->pZombieTab;
112934     pParse->pZombieTab = p->pNextZombie;
112935     sqlite3DeleteTable(db, p);
112936   }
112937   if( nErr>0 && pParse->rc==SQLITE_OK ){
112938     pParse->rc = SQLITE_ERROR;
112939   }
112940   return nErr;
112941 }
112942
112943 /************** End of tokenize.c ********************************************/
112944 /************** Begin file complete.c ****************************************/
112945 /*
112946 ** 2001 September 15
112947 **
112948 ** The author disclaims copyright to this source code.  In place of
112949 ** a legal notice, here is a blessing:
112950 **
112951 **    May you do good and not evil.
112952 **    May you find forgiveness for yourself and forgive others.
112953 **    May you share freely, never taking more than you give.
112954 **
112955 *************************************************************************
112956 ** An tokenizer for SQL
112957 **
112958 ** This file contains C code that implements the sqlite3_complete() API.
112959 ** This code used to be part of the tokenizer.c source file.  But by
112960 ** separating it out, the code will be automatically omitted from
112961 ** static links that do not use it.
112962 */
112963 #ifndef SQLITE_OMIT_COMPLETE
112964
112965 /*
112966 ** This is defined in tokenize.c.  We just have to import the definition.
112967 */
112968 #ifndef SQLITE_AMALGAMATION
112969 #ifdef SQLITE_ASCII
112970 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
112971 #endif
112972 #ifdef SQLITE_EBCDIC
112973 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
112974 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
112975 #endif
112976 #endif /* SQLITE_AMALGAMATION */
112977
112978
112979 /*
112980 ** Token types used by the sqlite3_complete() routine.  See the header
112981 ** comments on that procedure for additional information.
112982 */
112983 #define tkSEMI    0
112984 #define tkWS      1
112985 #define tkOTHER   2
112986 #ifndef SQLITE_OMIT_TRIGGER
112987 #define tkEXPLAIN 3
112988 #define tkCREATE  4
112989 #define tkTEMP    5
112990 #define tkTRIGGER 6
112991 #define tkEND     7
112992 #endif
112993
112994 /*
112995 ** Return TRUE if the given SQL string ends in a semicolon.
112996 **
112997 ** Special handling is require for CREATE TRIGGER statements.
112998 ** Whenever the CREATE TRIGGER keywords are seen, the statement
112999 ** must end with ";END;".
113000 **
113001 ** This implementation uses a state machine with 8 states:
113002 **
113003 **   (0) INVALID   We have not yet seen a non-whitespace character.
113004 **
113005 **   (1) START     At the beginning or end of an SQL statement.  This routine
113006 **                 returns 1 if it ends in the START state and 0 if it ends
113007 **                 in any other state.
113008 **
113009 **   (2) NORMAL    We are in the middle of statement which ends with a single
113010 **                 semicolon.
113011 **
113012 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
113013 **                 a statement.
113014 **
113015 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
113016 **                 statement, possibly preceeded by EXPLAIN and/or followed by
113017 **                 TEMP or TEMPORARY
113018 **
113019 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
113020 **                 ended by a semicolon, the keyword END, and another semicolon.
113021 **
113022 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
113023 **                 the end of a trigger definition.
113024 **
113025 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
113026 **                 of a trigger difinition.
113027 **
113028 ** Transitions between states above are determined by tokens extracted
113029 ** from the input.  The following tokens are significant:
113030 **
113031 **   (0) tkSEMI      A semicolon.
113032 **   (1) tkWS        Whitespace.
113033 **   (2) tkOTHER     Any other SQL token.
113034 **   (3) tkEXPLAIN   The "explain" keyword.
113035 **   (4) tkCREATE    The "create" keyword.
113036 **   (5) tkTEMP      The "temp" or "temporary" keyword.
113037 **   (6) tkTRIGGER   The "trigger" keyword.
113038 **   (7) tkEND       The "end" keyword.
113039 **
113040 ** Whitespace never causes a state transition and is always ignored.
113041 ** This means that a SQL string of all whitespace is invalid.
113042 **
113043 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
113044 ** to recognize the end of a trigger can be omitted.  All we have to do
113045 ** is look for a semicolon that is not part of an string or comment.
113046 */
113047 SQLITE_API int sqlite3_complete(const char *zSql){
113048   u8 state = 0;   /* Current state, using numbers defined in header comment */
113049   u8 token;       /* Value of the next token */
113050
113051 #ifndef SQLITE_OMIT_TRIGGER
113052   /* A complex statement machine used to detect the end of a CREATE TRIGGER
113053   ** statement.  This is the normal case.
113054   */
113055   static const u8 trans[8][8] = {
113056                      /* Token:                                                */
113057      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
113058      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
113059      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
113060      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
113061      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
113062      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
113063      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
113064      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
113065      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
113066   };
113067 #else
113068   /* If triggers are not supported by this compile then the statement machine
113069   ** used to detect the end of a statement is much simplier
113070   */
113071   static const u8 trans[3][3] = {
113072                      /* Token:           */
113073      /* State:       **  SEMI  WS  OTHER */
113074      /* 0 INVALID: */ {    1,  0,     2, },
113075      /* 1   START: */ {    1,  1,     2, },
113076      /* 2  NORMAL: */ {    1,  2,     2, },
113077   };
113078 #endif /* SQLITE_OMIT_TRIGGER */
113079
113080   while( *zSql ){
113081     switch( *zSql ){
113082       case ';': {  /* A semicolon */
113083         token = tkSEMI;
113084         break;
113085       }
113086       case ' ':
113087       case '\r':
113088       case '\t':
113089       case '\n':
113090       case '\f': {  /* White space is ignored */
113091         token = tkWS;
113092         break;
113093       }
113094       case '/': {   /* C-style comments */
113095         if( zSql[1]!='*' ){
113096           token = tkOTHER;
113097           break;
113098         }
113099         zSql += 2;
113100         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
113101         if( zSql[0]==0 ) return 0;
113102         zSql++;
113103         token = tkWS;
113104         break;
113105       }
113106       case '-': {   /* SQL-style comments from "--" to end of line */
113107         if( zSql[1]!='-' ){
113108           token = tkOTHER;
113109           break;
113110         }
113111         while( *zSql && *zSql!='\n' ){ zSql++; }
113112         if( *zSql==0 ) return state==1;
113113         token = tkWS;
113114         break;
113115       }
113116       case '[': {   /* Microsoft-style identifiers in [...] */
113117         zSql++;
113118         while( *zSql && *zSql!=']' ){ zSql++; }
113119         if( *zSql==0 ) return 0;
113120         token = tkOTHER;
113121         break;
113122       }
113123       case '`':     /* Grave-accent quoted symbols used by MySQL */
113124       case '"':     /* single- and double-quoted strings */
113125       case '\'': {
113126         int c = *zSql;
113127         zSql++;
113128         while( *zSql && *zSql!=c ){ zSql++; }
113129         if( *zSql==0 ) return 0;
113130         token = tkOTHER;
113131         break;
113132       }
113133       default: {
113134 #ifdef SQLITE_EBCDIC
113135         unsigned char c;
113136 #endif
113137         if( IdChar((u8)*zSql) ){
113138           /* Keywords and unquoted identifiers */
113139           int nId;
113140           for(nId=1; IdChar(zSql[nId]); nId++){}
113141 #ifdef SQLITE_OMIT_TRIGGER
113142           token = tkOTHER;
113143 #else
113144           switch( *zSql ){
113145             case 'c': case 'C': {
113146               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
113147                 token = tkCREATE;
113148               }else{
113149                 token = tkOTHER;
113150               }
113151               break;
113152             }
113153             case 't': case 'T': {
113154               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
113155                 token = tkTRIGGER;
113156               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
113157                 token = tkTEMP;
113158               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
113159                 token = tkTEMP;
113160               }else{
113161                 token = tkOTHER;
113162               }
113163               break;
113164             }
113165             case 'e':  case 'E': {
113166               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
113167                 token = tkEND;
113168               }else
113169 #ifndef SQLITE_OMIT_EXPLAIN
113170               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
113171                 token = tkEXPLAIN;
113172               }else
113173 #endif
113174               {
113175                 token = tkOTHER;
113176               }
113177               break;
113178             }
113179             default: {
113180               token = tkOTHER;
113181               break;
113182             }
113183           }
113184 #endif /* SQLITE_OMIT_TRIGGER */
113185           zSql += nId-1;
113186         }else{
113187           /* Operators and special symbols */
113188           token = tkOTHER;
113189         }
113190         break;
113191       }
113192     }
113193     state = trans[state][token];
113194     zSql++;
113195   }
113196   return state==1;
113197 }
113198
113199 #ifndef SQLITE_OMIT_UTF16
113200 /*
113201 ** This routine is the same as the sqlite3_complete() routine described
113202 ** above, except that the parameter is required to be UTF-16 encoded, not
113203 ** UTF-8.
113204 */
113205 SQLITE_API int sqlite3_complete16(const void *zSql){
113206   sqlite3_value *pVal;
113207   char const *zSql8;
113208   int rc = SQLITE_NOMEM;
113209
113210 #ifndef SQLITE_OMIT_AUTOINIT
113211   rc = sqlite3_initialize();
113212   if( rc ) return rc;
113213 #endif
113214   pVal = sqlite3ValueNew(0);
113215   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
113216   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
113217   if( zSql8 ){
113218     rc = sqlite3_complete(zSql8);
113219   }else{
113220     rc = SQLITE_NOMEM;
113221   }
113222   sqlite3ValueFree(pVal);
113223   return sqlite3ApiExit(0, rc);
113224 }
113225 #endif /* SQLITE_OMIT_UTF16 */
113226 #endif /* SQLITE_OMIT_COMPLETE */
113227
113228 /************** End of complete.c ********************************************/
113229 /************** Begin file main.c ********************************************/
113230 /*
113231 ** 2001 September 15
113232 **
113233 ** The author disclaims copyright to this source code.  In place of
113234 ** a legal notice, here is a blessing:
113235 **
113236 **    May you do good and not evil.
113237 **    May you find forgiveness for yourself and forgive others.
113238 **    May you share freely, never taking more than you give.
113239 **
113240 *************************************************************************
113241 ** Main file for the SQLite library.  The routines in this file
113242 ** implement the programmer interface to the library.  Routines in
113243 ** other files are for internal use by SQLite and should not be
113244 ** accessed by users of the library.
113245 */
113246
113247 #ifdef SQLITE_ENABLE_FTS3
113248 /************** Include fts3.h in the middle of main.c ***********************/
113249 /************** Begin file fts3.h ********************************************/
113250 /*
113251 ** 2006 Oct 10
113252 **
113253 ** The author disclaims copyright to this source code.  In place of
113254 ** a legal notice, here is a blessing:
113255 **
113256 **    May you do good and not evil.
113257 **    May you find forgiveness for yourself and forgive others.
113258 **    May you share freely, never taking more than you give.
113259 **
113260 ******************************************************************************
113261 **
113262 ** This header file is used by programs that want to link against the
113263 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
113264 */
113265
113266 #if 0
113267 extern "C" {
113268 #endif  /* __cplusplus */
113269
113270 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
113271
113272 #if 0
113273 }  /* extern "C" */
113274 #endif  /* __cplusplus */
113275
113276 /************** End of fts3.h ************************************************/
113277 /************** Continuing where we left off in main.c ***********************/
113278 #endif
113279 #ifdef SQLITE_ENABLE_RTREE
113280 /************** Include rtree.h in the middle of main.c **********************/
113281 /************** Begin file rtree.h *******************************************/
113282 /*
113283 ** 2008 May 26
113284 **
113285 ** The author disclaims copyright to this source code.  In place of
113286 ** a legal notice, here is a blessing:
113287 **
113288 **    May you do good and not evil.
113289 **    May you find forgiveness for yourself and forgive others.
113290 **    May you share freely, never taking more than you give.
113291 **
113292 ******************************************************************************
113293 **
113294 ** This header file is used by programs that want to link against the
113295 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
113296 */
113297
113298 #if 0
113299 extern "C" {
113300 #endif  /* __cplusplus */
113301
113302 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
113303
113304 #if 0
113305 }  /* extern "C" */
113306 #endif  /* __cplusplus */
113307
113308 /************** End of rtree.h ***********************************************/
113309 /************** Continuing where we left off in main.c ***********************/
113310 #endif
113311 #ifdef SQLITE_ENABLE_ICU
113312 /************** Include sqliteicu.h in the middle of main.c ******************/
113313 /************** Begin file sqliteicu.h ***************************************/
113314 /*
113315 ** 2008 May 26
113316 **
113317 ** The author disclaims copyright to this source code.  In place of
113318 ** a legal notice, here is a blessing:
113319 **
113320 **    May you do good and not evil.
113321 **    May you find forgiveness for yourself and forgive others.
113322 **    May you share freely, never taking more than you give.
113323 **
113324 ******************************************************************************
113325 **
113326 ** This header file is used by programs that want to link against the
113327 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
113328 */
113329
113330 #if 0
113331 extern "C" {
113332 #endif  /* __cplusplus */
113333
113334 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
113335
113336 #if 0
113337 }  /* extern "C" */
113338 #endif  /* __cplusplus */
113339
113340
113341 /************** End of sqliteicu.h *******************************************/
113342 /************** Continuing where we left off in main.c ***********************/
113343 #endif
113344
113345 #ifndef SQLITE_AMALGAMATION
113346 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
113347 ** contains the text of SQLITE_VERSION macro. 
113348 */
113349 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
113350 #endif
113351
113352 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
113353 ** a pointer to the to the sqlite3_version[] string constant. 
113354 */
113355 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
113356
113357 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
113358 ** pointer to a string constant whose value is the same as the
113359 ** SQLITE_SOURCE_ID C preprocessor macro. 
113360 */
113361 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
113362
113363 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
113364 ** returns an integer equal to SQLITE_VERSION_NUMBER.
113365 */
113366 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
113367
113368 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
113369 ** zero if and only if SQLite was compiled with mutexing code omitted due to
113370 ** the SQLITE_THREADSAFE compile-time option being set to 0.
113371 */
113372 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
113373
113374 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
113375 /*
113376 ** If the following function pointer is not NULL and if
113377 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
113378 ** I/O active are written using this function.  These messages
113379 ** are intended for debugging activity only.
113380 */
113381 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
113382 #endif
113383
113384 /*
113385 ** If the following global variable points to a string which is the
113386 ** name of a directory, then that directory will be used to store
113387 ** temporary files.
113388 **
113389 ** See also the "PRAGMA temp_store_directory" SQL command.
113390 */
113391 SQLITE_API char *sqlite3_temp_directory = 0;
113392
113393 /*
113394 ** If the following global variable points to a string which is the
113395 ** name of a directory, then that directory will be used to store
113396 ** all database files specified with a relative pathname.
113397 **
113398 ** See also the "PRAGMA data_store_directory" SQL command.
113399 */
113400 SQLITE_API char *sqlite3_data_directory = 0;
113401
113402 /*
113403 ** Initialize SQLite.  
113404 **
113405 ** This routine must be called to initialize the memory allocation,
113406 ** VFS, and mutex subsystems prior to doing any serious work with
113407 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
113408 ** this routine will be called automatically by key routines such as
113409 ** sqlite3_open().  
113410 **
113411 ** This routine is a no-op except on its very first call for the process,
113412 ** or for the first call after a call to sqlite3_shutdown.
113413 **
113414 ** The first thread to call this routine runs the initialization to
113415 ** completion.  If subsequent threads call this routine before the first
113416 ** thread has finished the initialization process, then the subsequent
113417 ** threads must block until the first thread finishes with the initialization.
113418 **
113419 ** The first thread might call this routine recursively.  Recursive
113420 ** calls to this routine should not block, of course.  Otherwise the
113421 ** initialization process would never complete.
113422 **
113423 ** Let X be the first thread to enter this routine.  Let Y be some other
113424 ** thread.  Then while the initial invocation of this routine by X is
113425 ** incomplete, it is required that:
113426 **
113427 **    *  Calls to this routine from Y must block until the outer-most
113428 **       call by X completes.
113429 **
113430 **    *  Recursive calls to this routine from thread X return immediately
113431 **       without blocking.
113432 */
113433 SQLITE_API int sqlite3_initialize(void){
113434   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
113435   int rc;                                      /* Result code */
113436
113437 #ifdef SQLITE_OMIT_WSD
113438   rc = sqlite3_wsd_init(4096, 24);
113439   if( rc!=SQLITE_OK ){
113440     return rc;
113441   }
113442 #endif
113443
113444   /* If SQLite is already completely initialized, then this call
113445   ** to sqlite3_initialize() should be a no-op.  But the initialization
113446   ** must be complete.  So isInit must not be set until the very end
113447   ** of this routine.
113448   */
113449   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
113450
113451 #ifdef SQLITE_ENABLE_SQLLOG
113452   {
113453     extern void sqlite3_init_sqllog(void);
113454     sqlite3_init_sqllog();
113455   }
113456 #endif
113457
113458   /* Make sure the mutex subsystem is initialized.  If unable to 
113459   ** initialize the mutex subsystem, return early with the error.
113460   ** If the system is so sick that we are unable to allocate a mutex,
113461   ** there is not much SQLite is going to be able to do.
113462   **
113463   ** The mutex subsystem must take care of serializing its own
113464   ** initialization.
113465   */
113466   rc = sqlite3MutexInit();
113467   if( rc ) return rc;
113468
113469   /* Initialize the malloc() system and the recursive pInitMutex mutex.
113470   ** This operation is protected by the STATIC_MASTER mutex.  Note that
113471   ** MutexAlloc() is called for a static mutex prior to initializing the
113472   ** malloc subsystem - this implies that the allocation of a static
113473   ** mutex must not require support from the malloc subsystem.
113474   */
113475   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
113476   sqlite3_mutex_enter(pMaster);
113477   sqlite3GlobalConfig.isMutexInit = 1;
113478   if( !sqlite3GlobalConfig.isMallocInit ){
113479     rc = sqlite3MallocInit();
113480   }
113481   if( rc==SQLITE_OK ){
113482     sqlite3GlobalConfig.isMallocInit = 1;
113483     if( !sqlite3GlobalConfig.pInitMutex ){
113484       sqlite3GlobalConfig.pInitMutex =
113485            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
113486       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
113487         rc = SQLITE_NOMEM;
113488       }
113489     }
113490   }
113491   if( rc==SQLITE_OK ){
113492     sqlite3GlobalConfig.nRefInitMutex++;
113493   }
113494   sqlite3_mutex_leave(pMaster);
113495
113496   /* If rc is not SQLITE_OK at this point, then either the malloc
113497   ** subsystem could not be initialized or the system failed to allocate
113498   ** the pInitMutex mutex. Return an error in either case.  */
113499   if( rc!=SQLITE_OK ){
113500     return rc;
113501   }
113502
113503   /* Do the rest of the initialization under the recursive mutex so
113504   ** that we will be able to handle recursive calls into
113505   ** sqlite3_initialize().  The recursive calls normally come through
113506   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
113507   ** recursive calls might also be possible.
113508   **
113509   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
113510   ** to the xInit method, so the xInit method need not be threadsafe.
113511   **
113512   ** The following mutex is what serializes access to the appdef pcache xInit
113513   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
113514   ** call to sqlite3PcacheInitialize().
113515   */
113516   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
113517   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
113518     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
113519     sqlite3GlobalConfig.inProgress = 1;
113520     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
113521     sqlite3RegisterGlobalFunctions();
113522     if( sqlite3GlobalConfig.isPCacheInit==0 ){
113523       rc = sqlite3PcacheInitialize();
113524     }
113525     if( rc==SQLITE_OK ){
113526       sqlite3GlobalConfig.isPCacheInit = 1;
113527       rc = sqlite3OsInit();
113528     }
113529     if( rc==SQLITE_OK ){
113530       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
113531           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
113532       sqlite3GlobalConfig.isInit = 1;
113533     }
113534     sqlite3GlobalConfig.inProgress = 0;
113535   }
113536   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
113537
113538   /* Go back under the static mutex and clean up the recursive
113539   ** mutex to prevent a resource leak.
113540   */
113541   sqlite3_mutex_enter(pMaster);
113542   sqlite3GlobalConfig.nRefInitMutex--;
113543   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
113544     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
113545     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
113546     sqlite3GlobalConfig.pInitMutex = 0;
113547   }
113548   sqlite3_mutex_leave(pMaster);
113549
113550   /* The following is just a sanity check to make sure SQLite has
113551   ** been compiled correctly.  It is important to run this code, but
113552   ** we don't want to run it too often and soak up CPU cycles for no
113553   ** reason.  So we run it once during initialization.
113554   */
113555 #ifndef NDEBUG
113556 #ifndef SQLITE_OMIT_FLOATING_POINT
113557   /* This section of code's only "output" is via assert() statements. */
113558   if ( rc==SQLITE_OK ){
113559     u64 x = (((u64)1)<<63)-1;
113560     double y;
113561     assert(sizeof(x)==8);
113562     assert(sizeof(x)==sizeof(y));
113563     memcpy(&y, &x, 8);
113564     assert( sqlite3IsNaN(y) );
113565   }
113566 #endif
113567 #endif
113568
113569   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
113570   ** compile-time option.
113571   */
113572 #ifdef SQLITE_EXTRA_INIT
113573   if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
113574     int SQLITE_EXTRA_INIT(const char*);
113575     rc = SQLITE_EXTRA_INIT(0);
113576   }
113577 #endif
113578
113579   return rc;
113580 }
113581
113582 /*
113583 ** Undo the effects of sqlite3_initialize().  Must not be called while
113584 ** there are outstanding database connections or memory allocations or
113585 ** while any part of SQLite is otherwise in use in any thread.  This
113586 ** routine is not threadsafe.  But it is safe to invoke this routine
113587 ** on when SQLite is already shut down.  If SQLite is already shut down
113588 ** when this routine is invoked, then this routine is a harmless no-op.
113589 */
113590 SQLITE_API int sqlite3_shutdown(void){
113591   if( sqlite3GlobalConfig.isInit ){
113592 #ifdef SQLITE_EXTRA_SHUTDOWN
113593     void SQLITE_EXTRA_SHUTDOWN(void);
113594     SQLITE_EXTRA_SHUTDOWN();
113595 #endif
113596     sqlite3_os_end();
113597     sqlite3_reset_auto_extension();
113598     sqlite3GlobalConfig.isInit = 0;
113599   }
113600   if( sqlite3GlobalConfig.isPCacheInit ){
113601     sqlite3PcacheShutdown();
113602     sqlite3GlobalConfig.isPCacheInit = 0;
113603   }
113604   if( sqlite3GlobalConfig.isMallocInit ){
113605     sqlite3MallocEnd();
113606     sqlite3GlobalConfig.isMallocInit = 0;
113607
113608 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
113609     /* The heap subsystem has now been shutdown and these values are supposed
113610     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
113611     ** which would rely on that heap subsystem; therefore, make sure these
113612     ** values cannot refer to heap memory that was just invalidated when the
113613     ** heap subsystem was shutdown.  This is only done if the current call to
113614     ** this function resulted in the heap subsystem actually being shutdown.
113615     */
113616     sqlite3_data_directory = 0;
113617     sqlite3_temp_directory = 0;
113618 #endif
113619   }
113620   if( sqlite3GlobalConfig.isMutexInit ){
113621     sqlite3MutexEnd();
113622     sqlite3GlobalConfig.isMutexInit = 0;
113623   }
113624
113625   return SQLITE_OK;
113626 }
113627
113628 /*
113629 ** This API allows applications to modify the global configuration of
113630 ** the SQLite library at run-time.
113631 **
113632 ** This routine should only be called when there are no outstanding
113633 ** database connections or memory allocations.  This routine is not
113634 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
113635 ** behavior.
113636 */
113637 SQLITE_API int sqlite3_config(int op, ...){
113638   va_list ap;
113639   int rc = SQLITE_OK;
113640
113641   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
113642   ** the SQLite library is in use. */
113643   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
113644
113645   va_start(ap, op);
113646   switch( op ){
113647
113648     /* Mutex configuration options are only available in a threadsafe
113649     ** compile. 
113650     */
113651 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
113652     case SQLITE_CONFIG_SINGLETHREAD: {
113653       /* Disable all mutexing */
113654       sqlite3GlobalConfig.bCoreMutex = 0;
113655       sqlite3GlobalConfig.bFullMutex = 0;
113656       break;
113657     }
113658     case SQLITE_CONFIG_MULTITHREAD: {
113659       /* Disable mutexing of database connections */
113660       /* Enable mutexing of core data structures */
113661       sqlite3GlobalConfig.bCoreMutex = 1;
113662       sqlite3GlobalConfig.bFullMutex = 0;
113663       break;
113664     }
113665     case SQLITE_CONFIG_SERIALIZED: {
113666       /* Enable all mutexing */
113667       sqlite3GlobalConfig.bCoreMutex = 1;
113668       sqlite3GlobalConfig.bFullMutex = 1;
113669       break;
113670     }
113671     case SQLITE_CONFIG_MUTEX: {
113672       /* Specify an alternative mutex implementation */
113673       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
113674       break;
113675     }
113676     case SQLITE_CONFIG_GETMUTEX: {
113677       /* Retrieve the current mutex implementation */
113678       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
113679       break;
113680     }
113681 #endif
113682
113683
113684     case SQLITE_CONFIG_MALLOC: {
113685       /* Specify an alternative malloc implementation */
113686       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
113687       break;
113688     }
113689     case SQLITE_CONFIG_GETMALLOC: {
113690       /* Retrieve the current malloc() implementation */
113691       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
113692       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
113693       break;
113694     }
113695     case SQLITE_CONFIG_MEMSTATUS: {
113696       /* Enable or disable the malloc status collection */
113697       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
113698       break;
113699     }
113700     case SQLITE_CONFIG_SCRATCH: {
113701       /* Designate a buffer for scratch memory space */
113702       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
113703       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
113704       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
113705       break;
113706     }
113707     case SQLITE_CONFIG_PAGECACHE: {
113708       /* Designate a buffer for page cache memory space */
113709       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
113710       sqlite3GlobalConfig.szPage = va_arg(ap, int);
113711       sqlite3GlobalConfig.nPage = va_arg(ap, int);
113712       break;
113713     }
113714
113715     case SQLITE_CONFIG_PCACHE: {
113716       /* no-op */
113717       break;
113718     }
113719     case SQLITE_CONFIG_GETPCACHE: {
113720       /* now an error */
113721       rc = SQLITE_ERROR;
113722       break;
113723     }
113724
113725     case SQLITE_CONFIG_PCACHE2: {
113726       /* Specify an alternative page cache implementation */
113727       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
113728       break;
113729     }
113730     case SQLITE_CONFIG_GETPCACHE2: {
113731       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
113732         sqlite3PCacheSetDefault();
113733       }
113734       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
113735       break;
113736     }
113737
113738 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
113739     case SQLITE_CONFIG_HEAP: {
113740       /* Designate a buffer for heap memory space */
113741       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
113742       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
113743       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
113744
113745       if( sqlite3GlobalConfig.mnReq<1 ){
113746         sqlite3GlobalConfig.mnReq = 1;
113747       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
113748         /* cap min request size at 2^12 */
113749         sqlite3GlobalConfig.mnReq = (1<<12);
113750       }
113751
113752       if( sqlite3GlobalConfig.pHeap==0 ){
113753         /* If the heap pointer is NULL, then restore the malloc implementation
113754         ** back to NULL pointers too.  This will cause the malloc to go
113755         ** back to its default implementation when sqlite3_initialize() is
113756         ** run.
113757         */
113758         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
113759       }else{
113760         /* The heap pointer is not NULL, then install one of the
113761         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
113762         ** ENABLE_MEMSYS5 is defined, return an error.
113763         */
113764 #ifdef SQLITE_ENABLE_MEMSYS3
113765         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
113766 #endif
113767 #ifdef SQLITE_ENABLE_MEMSYS5
113768         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
113769 #endif
113770       }
113771       break;
113772     }
113773 #endif
113774
113775     case SQLITE_CONFIG_LOOKASIDE: {
113776       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
113777       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
113778       break;
113779     }
113780     
113781     /* Record a pointer to the logger funcction and its first argument.
113782     ** The default is NULL.  Logging is disabled if the function pointer is
113783     ** NULL.
113784     */
113785     case SQLITE_CONFIG_LOG: {
113786       /* MSVC is picky about pulling func ptrs from va lists.
113787       ** http://support.microsoft.com/kb/47961
113788       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
113789       */
113790       typedef void(*LOGFUNC_t)(void*,int,const char*);
113791       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
113792       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
113793       break;
113794     }
113795
113796     case SQLITE_CONFIG_URI: {
113797       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
113798       break;
113799     }
113800
113801     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
113802       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
113803       break;
113804     }
113805
113806 #ifdef SQLITE_ENABLE_SQLLOG
113807     case SQLITE_CONFIG_SQLLOG: {
113808       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
113809       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
113810       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
113811       break;
113812     }
113813 #endif
113814
113815     default: {
113816       rc = SQLITE_ERROR;
113817       break;
113818     }
113819   }
113820   va_end(ap);
113821   return rc;
113822 }
113823
113824 /*
113825 ** Set up the lookaside buffers for a database connection.
113826 ** Return SQLITE_OK on success.  
113827 ** If lookaside is already active, return SQLITE_BUSY.
113828 **
113829 ** The sz parameter is the number of bytes in each lookaside slot.
113830 ** The cnt parameter is the number of slots.  If pStart is NULL the
113831 ** space for the lookaside memory is obtained from sqlite3_malloc().
113832 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
113833 ** the lookaside memory.
113834 */
113835 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
113836   void *pStart;
113837   if( db->lookaside.nOut ){
113838     return SQLITE_BUSY;
113839   }
113840   /* Free any existing lookaside buffer for this handle before
113841   ** allocating a new one so we don't have to have space for 
113842   ** both at the same time.
113843   */
113844   if( db->lookaside.bMalloced ){
113845     sqlite3_free(db->lookaside.pStart);
113846   }
113847   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
113848   ** than a pointer to be useful.
113849   */
113850   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
113851   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
113852   if( cnt<0 ) cnt = 0;
113853   if( sz==0 || cnt==0 ){
113854     sz = 0;
113855     pStart = 0;
113856   }else if( pBuf==0 ){
113857     sqlite3BeginBenignMalloc();
113858     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
113859     sqlite3EndBenignMalloc();
113860     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
113861   }else{
113862     pStart = pBuf;
113863   }
113864   db->lookaside.pStart = pStart;
113865   db->lookaside.pFree = 0;
113866   db->lookaside.sz = (u16)sz;
113867   if( pStart ){
113868     int i;
113869     LookasideSlot *p;
113870     assert( sz > (int)sizeof(LookasideSlot*) );
113871     p = (LookasideSlot*)pStart;
113872     for(i=cnt-1; i>=0; i--){
113873       p->pNext = db->lookaside.pFree;
113874       db->lookaside.pFree = p;
113875       p = (LookasideSlot*)&((u8*)p)[sz];
113876     }
113877     db->lookaside.pEnd = p;
113878     db->lookaside.bEnabled = 1;
113879     db->lookaside.bMalloced = pBuf==0 ?1:0;
113880   }else{
113881     db->lookaside.pEnd = 0;
113882     db->lookaside.bEnabled = 0;
113883     db->lookaside.bMalloced = 0;
113884   }
113885   return SQLITE_OK;
113886 }
113887
113888 /*
113889 ** Return the mutex associated with a database connection.
113890 */
113891 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
113892   return db->mutex;
113893 }
113894
113895 /*
113896 ** Free up as much memory as we can from the given database
113897 ** connection.
113898 */
113899 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
113900   int i;
113901   sqlite3_mutex_enter(db->mutex);
113902   sqlite3BtreeEnterAll(db);
113903   for(i=0; i<db->nDb; i++){
113904     Btree *pBt = db->aDb[i].pBt;
113905     if( pBt ){
113906       Pager *pPager = sqlite3BtreePager(pBt);
113907       sqlite3PagerShrink(pPager);
113908     }
113909   }
113910   sqlite3BtreeLeaveAll(db);
113911   sqlite3_mutex_leave(db->mutex);
113912   return SQLITE_OK;
113913 }
113914
113915 /*
113916 ** Configuration settings for an individual database connection
113917 */
113918 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
113919   va_list ap;
113920   int rc;
113921   va_start(ap, op);
113922   switch( op ){
113923     case SQLITE_DBCONFIG_LOOKASIDE: {
113924       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
113925       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
113926       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
113927       rc = setupLookaside(db, pBuf, sz, cnt);
113928       break;
113929     }
113930     default: {
113931       static const struct {
113932         int op;      /* The opcode */
113933         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
113934       } aFlagOp[] = {
113935         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
113936         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
113937       };
113938       unsigned int i;
113939       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
113940       for(i=0; i<ArraySize(aFlagOp); i++){
113941         if( aFlagOp[i].op==op ){
113942           int onoff = va_arg(ap, int);
113943           int *pRes = va_arg(ap, int*);
113944           int oldFlags = db->flags;
113945           if( onoff>0 ){
113946             db->flags |= aFlagOp[i].mask;
113947           }else if( onoff==0 ){
113948             db->flags &= ~aFlagOp[i].mask;
113949           }
113950           if( oldFlags!=db->flags ){
113951             sqlite3ExpirePreparedStatements(db);
113952           }
113953           if( pRes ){
113954             *pRes = (db->flags & aFlagOp[i].mask)!=0;
113955           }
113956           rc = SQLITE_OK;
113957           break;
113958         }
113959       }
113960       break;
113961     }
113962   }
113963   va_end(ap);
113964   return rc;
113965 }
113966
113967
113968 /*
113969 ** Return true if the buffer z[0..n-1] contains all spaces.
113970 */
113971 static int allSpaces(const char *z, int n){
113972   while( n>0 && z[n-1]==' ' ){ n--; }
113973   return n==0;
113974 }
113975
113976 /*
113977 ** This is the default collating function named "BINARY" which is always
113978 ** available.
113979 **
113980 ** If the padFlag argument is not NULL then space padding at the end
113981 ** of strings is ignored.  This implements the RTRIM collation.
113982 */
113983 static int binCollFunc(
113984   void *padFlag,
113985   int nKey1, const void *pKey1,
113986   int nKey2, const void *pKey2
113987 ){
113988   int rc, n;
113989   n = nKey1<nKey2 ? nKey1 : nKey2;
113990   rc = memcmp(pKey1, pKey2, n);
113991   if( rc==0 ){
113992     if( padFlag
113993      && allSpaces(((char*)pKey1)+n, nKey1-n)
113994      && allSpaces(((char*)pKey2)+n, nKey2-n)
113995     ){
113996       /* Leave rc unchanged at 0 */
113997     }else{
113998       rc = nKey1 - nKey2;
113999     }
114000   }
114001   return rc;
114002 }
114003
114004 /*
114005 ** Another built-in collating sequence: NOCASE. 
114006 **
114007 ** This collating sequence is intended to be used for "case independant
114008 ** comparison". SQLite's knowledge of upper and lower case equivalents
114009 ** extends only to the 26 characters used in the English language.
114010 **
114011 ** At the moment there is only a UTF-8 implementation.
114012 */
114013 static int nocaseCollatingFunc(
114014   void *NotUsed,
114015   int nKey1, const void *pKey1,
114016   int nKey2, const void *pKey2
114017 ){
114018   int r = sqlite3StrNICmp(
114019       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
114020   UNUSED_PARAMETER(NotUsed);
114021   if( 0==r ){
114022     r = nKey1-nKey2;
114023   }
114024   return r;
114025 }
114026
114027 /*
114028 ** Return the ROWID of the most recent insert
114029 */
114030 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
114031   return db->lastRowid;
114032 }
114033
114034 /*
114035 ** Return the number of changes in the most recent call to sqlite3_exec().
114036 */
114037 SQLITE_API int sqlite3_changes(sqlite3 *db){
114038   return db->nChange;
114039 }
114040
114041 /*
114042 ** Return the number of changes since the database handle was opened.
114043 */
114044 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
114045   return db->nTotalChange;
114046 }
114047
114048 /*
114049 ** Close all open savepoints. This function only manipulates fields of the
114050 ** database handle object, it does not close any savepoints that may be open
114051 ** at the b-tree/pager level.
114052 */
114053 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
114054   while( db->pSavepoint ){
114055     Savepoint *pTmp = db->pSavepoint;
114056     db->pSavepoint = pTmp->pNext;
114057     sqlite3DbFree(db, pTmp);
114058   }
114059   db->nSavepoint = 0;
114060   db->nStatement = 0;
114061   db->isTransactionSavepoint = 0;
114062 }
114063
114064 /*
114065 ** Invoke the destructor function associated with FuncDef p, if any. Except,
114066 ** if this is not the last copy of the function, do not invoke it. Multiple
114067 ** copies of a single function are created when create_function() is called
114068 ** with SQLITE_ANY as the encoding.
114069 */
114070 static void functionDestroy(sqlite3 *db, FuncDef *p){
114071   FuncDestructor *pDestructor = p->pDestructor;
114072   if( pDestructor ){
114073     pDestructor->nRef--;
114074     if( pDestructor->nRef==0 ){
114075       pDestructor->xDestroy(pDestructor->pUserData);
114076       sqlite3DbFree(db, pDestructor);
114077     }
114078   }
114079 }
114080
114081 /*
114082 ** Disconnect all sqlite3_vtab objects that belong to database connection
114083 ** db. This is called when db is being closed.
114084 */
114085 static void disconnectAllVtab(sqlite3 *db){
114086 #ifndef SQLITE_OMIT_VIRTUALTABLE
114087   int i;
114088   sqlite3BtreeEnterAll(db);
114089   for(i=0; i<db->nDb; i++){
114090     Schema *pSchema = db->aDb[i].pSchema;
114091     if( db->aDb[i].pSchema ){
114092       HashElem *p;
114093       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
114094         Table *pTab = (Table *)sqliteHashData(p);
114095         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
114096       }
114097     }
114098   }
114099   sqlite3BtreeLeaveAll(db);
114100 #else
114101   UNUSED_PARAMETER(db);
114102 #endif
114103 }
114104
114105 /*
114106 ** Return TRUE if database connection db has unfinalized prepared
114107 ** statements or unfinished sqlite3_backup objects.  
114108 */
114109 static int connectionIsBusy(sqlite3 *db){
114110   int j;
114111   assert( sqlite3_mutex_held(db->mutex) );
114112   if( db->pVdbe ) return 1;
114113   for(j=0; j<db->nDb; j++){
114114     Btree *pBt = db->aDb[j].pBt;
114115     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
114116   }
114117   return 0;
114118 }
114119
114120 /*
114121 ** Close an existing SQLite database
114122 */
114123 static int sqlite3Close(sqlite3 *db, int forceZombie){
114124   if( !db ){
114125     return SQLITE_OK;
114126   }
114127   if( !sqlite3SafetyCheckSickOrOk(db) ){
114128     return SQLITE_MISUSE_BKPT;
114129   }
114130   sqlite3_mutex_enter(db->mutex);
114131
114132   /* Force xDisconnect calls on all virtual tables */
114133   disconnectAllVtab(db);
114134
114135   /* If a transaction is open, the disconnectAllVtab() call above
114136   ** will not have called the xDisconnect() method on any virtual
114137   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
114138   ** call will do so. We need to do this before the check for active
114139   ** SQL statements below, as the v-table implementation may be storing
114140   ** some prepared statements internally.
114141   */
114142   sqlite3VtabRollback(db);
114143
114144   /* Legacy behavior (sqlite3_close() behavior) is to return
114145   ** SQLITE_BUSY if the connection can not be closed immediately.
114146   */
114147   if( !forceZombie && connectionIsBusy(db) ){
114148     sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
114149        "statements or unfinished backups");
114150     sqlite3_mutex_leave(db->mutex);
114151     return SQLITE_BUSY;
114152   }
114153
114154 #ifdef SQLITE_ENABLE_SQLLOG
114155   if( sqlite3GlobalConfig.xSqllog ){
114156     /* Closing the handle. Fourth parameter is passed the value 2. */
114157     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
114158   }
114159 #endif
114160
114161   /* Convert the connection into a zombie and then close it.
114162   */
114163   db->magic = SQLITE_MAGIC_ZOMBIE;
114164   sqlite3LeaveMutexAndCloseZombie(db);
114165   return SQLITE_OK;
114166 }
114167
114168 /*
114169 ** Two variations on the public interface for closing a database
114170 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
114171 ** leaves the connection option if there are unfinalized prepared
114172 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
114173 ** version forces the connection to become a zombie if there are
114174 ** unclosed resources, and arranges for deallocation when the last
114175 ** prepare statement or sqlite3_backup closes.
114176 */
114177 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
114178 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
114179
114180
114181 /*
114182 ** Close the mutex on database connection db.
114183 **
114184 ** Furthermore, if database connection db is a zombie (meaning that there
114185 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
114186 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
114187 ** finished, then free all resources.
114188 */
114189 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
114190   HashElem *i;                    /* Hash table iterator */
114191   int j;
114192
114193   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
114194   ** or if the connection has not yet been closed by sqlite3_close_v2(),
114195   ** then just leave the mutex and return.
114196   */
114197   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
114198     sqlite3_mutex_leave(db->mutex);
114199     return;
114200   }
114201
114202   /* If we reach this point, it means that the database connection has
114203   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
114204   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
114205   ** go ahead and free all resources.
114206   */
114207
114208   /* Free any outstanding Savepoint structures. */
114209   sqlite3CloseSavepoints(db);
114210
114211   /* Close all database connections */
114212   for(j=0; j<db->nDb; j++){
114213     struct Db *pDb = &db->aDb[j];
114214     if( pDb->pBt ){
114215       sqlite3BtreeClose(pDb->pBt);
114216       pDb->pBt = 0;
114217       if( j!=1 ){
114218         pDb->pSchema = 0;
114219       }
114220     }
114221   }
114222   /* Clear the TEMP schema separately and last */
114223   if( db->aDb[1].pSchema ){
114224     sqlite3SchemaClear(db->aDb[1].pSchema);
114225   }
114226   sqlite3VtabUnlockList(db);
114227
114228   /* Free up the array of auxiliary databases */
114229   sqlite3CollapseDatabaseArray(db);
114230   assert( db->nDb<=2 );
114231   assert( db->aDb==db->aDbStatic );
114232
114233   /* Tell the code in notify.c that the connection no longer holds any
114234   ** locks and does not require any further unlock-notify callbacks.
114235   */
114236   sqlite3ConnectionClosed(db);
114237
114238   for(j=0; j<ArraySize(db->aFunc.a); j++){
114239     FuncDef *pNext, *pHash, *p;
114240     for(p=db->aFunc.a[j]; p; p=pHash){
114241       pHash = p->pHash;
114242       while( p ){
114243         functionDestroy(db, p);
114244         pNext = p->pNext;
114245         sqlite3DbFree(db, p);
114246         p = pNext;
114247       }
114248     }
114249   }
114250   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
114251     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
114252     /* Invoke any destructors registered for collation sequence user data. */
114253     for(j=0; j<3; j++){
114254       if( pColl[j].xDel ){
114255         pColl[j].xDel(pColl[j].pUser);
114256       }
114257     }
114258     sqlite3DbFree(db, pColl);
114259   }
114260   sqlite3HashClear(&db->aCollSeq);
114261 #ifndef SQLITE_OMIT_VIRTUALTABLE
114262   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
114263     Module *pMod = (Module *)sqliteHashData(i);
114264     if( pMod->xDestroy ){
114265       pMod->xDestroy(pMod->pAux);
114266     }
114267     sqlite3DbFree(db, pMod);
114268   }
114269   sqlite3HashClear(&db->aModule);
114270 #endif
114271
114272   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
114273   if( db->pErr ){
114274     sqlite3ValueFree(db->pErr);
114275   }
114276   sqlite3CloseExtensions(db);
114277
114278   db->magic = SQLITE_MAGIC_ERROR;
114279
114280   /* The temp-database schema is allocated differently from the other schema
114281   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
114282   ** So it needs to be freed here. Todo: Why not roll the temp schema into
114283   ** the same sqliteMalloc() as the one that allocates the database 
114284   ** structure?
114285   */
114286   sqlite3DbFree(db, db->aDb[1].pSchema);
114287   sqlite3_mutex_leave(db->mutex);
114288   db->magic = SQLITE_MAGIC_CLOSED;
114289   sqlite3_mutex_free(db->mutex);
114290   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
114291   if( db->lookaside.bMalloced ){
114292     sqlite3_free(db->lookaside.pStart);
114293   }
114294   sqlite3_free(db);
114295 }
114296
114297 /*
114298 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
114299 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
114300 ** breaker") and made to return tripCode if there are any further
114301 ** attempts to use that cursor.
114302 */
114303 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
114304   int i;
114305   int inTrans = 0;
114306   assert( sqlite3_mutex_held(db->mutex) );
114307   sqlite3BeginBenignMalloc();
114308   for(i=0; i<db->nDb; i++){
114309     Btree *p = db->aDb[i].pBt;
114310     if( p ){
114311       if( sqlite3BtreeIsInTrans(p) ){
114312         inTrans = 1;
114313       }
114314       sqlite3BtreeRollback(p, tripCode);
114315       db->aDb[i].inTrans = 0;
114316     }
114317   }
114318   sqlite3VtabRollback(db);
114319   sqlite3EndBenignMalloc();
114320
114321   if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
114322     sqlite3ExpirePreparedStatements(db);
114323     sqlite3ResetAllSchemasOfConnection(db);
114324   }
114325
114326   /* Any deferred constraint violations have now been resolved. */
114327   db->nDeferredCons = 0;
114328
114329   /* If one has been configured, invoke the rollback-hook callback */
114330   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
114331     db->xRollbackCallback(db->pRollbackArg);
114332   }
114333 }
114334
114335 /*
114336 ** Return a static string that describes the kind of error specified in the
114337 ** argument.
114338 */
114339 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
114340   static const char* const aMsg[] = {
114341     /* SQLITE_OK          */ "not an error",
114342     /* SQLITE_ERROR       */ "SQL logic error or missing database",
114343     /* SQLITE_INTERNAL    */ 0,
114344     /* SQLITE_PERM        */ "access permission denied",
114345     /* SQLITE_ABORT       */ "callback requested query abort",
114346     /* SQLITE_BUSY        */ "database is locked",
114347     /* SQLITE_LOCKED      */ "database table is locked",
114348     /* SQLITE_NOMEM       */ "out of memory",
114349     /* SQLITE_READONLY    */ "attempt to write a readonly database",
114350     /* SQLITE_INTERRUPT   */ "interrupted",
114351     /* SQLITE_IOERR       */ "disk I/O error",
114352     /* SQLITE_CORRUPT     */ "database disk image is malformed",
114353     /* SQLITE_NOTFOUND    */ "unknown operation",
114354     /* SQLITE_FULL        */ "database or disk is full",
114355     /* SQLITE_CANTOPEN    */ "unable to open database file",
114356     /* SQLITE_PROTOCOL    */ "locking protocol",
114357     /* SQLITE_EMPTY       */ "table contains no data",
114358     /* SQLITE_SCHEMA      */ "database schema has changed",
114359     /* SQLITE_TOOBIG      */ "string or blob too big",
114360     /* SQLITE_CONSTRAINT  */ "constraint failed",
114361     /* SQLITE_MISMATCH    */ "datatype mismatch",
114362     /* SQLITE_MISUSE      */ "library routine called out of sequence",
114363     /* SQLITE_NOLFS       */ "large file support is disabled",
114364     /* SQLITE_AUTH        */ "authorization denied",
114365     /* SQLITE_FORMAT      */ "auxiliary database format error",
114366     /* SQLITE_RANGE       */ "bind or column index out of range",
114367     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
114368   };
114369   const char *zErr = "unknown error";
114370   switch( rc ){
114371     case SQLITE_ABORT_ROLLBACK: {
114372       zErr = "abort due to ROLLBACK";
114373       break;
114374     }
114375     default: {
114376       rc &= 0xff;
114377       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
114378         zErr = aMsg[rc];
114379       }
114380       break;
114381     }
114382   }
114383   return zErr;
114384 }
114385
114386 /*
114387 ** This routine implements a busy callback that sleeps and tries
114388 ** again until a timeout value is reached.  The timeout value is
114389 ** an integer number of milliseconds passed in as the first
114390 ** argument.
114391 */
114392 static int sqliteDefaultBusyCallback(
114393  void *ptr,               /* Database connection */
114394  int count                /* Number of times table has been busy */
114395 ){
114396 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
114397   static const u8 delays[] =
114398      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
114399   static const u8 totals[] =
114400      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
114401 # define NDELAY ArraySize(delays)
114402   sqlite3 *db = (sqlite3 *)ptr;
114403   int timeout = db->busyTimeout;
114404   int delay, prior;
114405
114406   assert( count>=0 );
114407   if( count < NDELAY ){
114408     delay = delays[count];
114409     prior = totals[count];
114410   }else{
114411     delay = delays[NDELAY-1];
114412     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
114413   }
114414   if( prior + delay > timeout ){
114415     delay = timeout - prior;
114416     if( delay<=0 ) return 0;
114417   }
114418   sqlite3OsSleep(db->pVfs, delay*1000);
114419   return 1;
114420 #else
114421   sqlite3 *db = (sqlite3 *)ptr;
114422   int timeout = ((sqlite3 *)ptr)->busyTimeout;
114423   if( (count+1)*1000 > timeout ){
114424     return 0;
114425   }
114426   sqlite3OsSleep(db->pVfs, 1000000);
114427   return 1;
114428 #endif
114429 }
114430
114431 /*
114432 ** Invoke the given busy handler.
114433 **
114434 ** This routine is called when an operation failed with a lock.
114435 ** If this routine returns non-zero, the lock is retried.  If it
114436 ** returns 0, the operation aborts with an SQLITE_BUSY error.
114437 */
114438 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
114439   int rc;
114440   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
114441   rc = p->xFunc(p->pArg, p->nBusy);
114442   if( rc==0 ){
114443     p->nBusy = -1;
114444   }else{
114445     p->nBusy++;
114446   }
114447   return rc; 
114448 }
114449
114450 /*
114451 ** This routine sets the busy callback for an Sqlite database to the
114452 ** given callback function with the given argument.
114453 */
114454 SQLITE_API int sqlite3_busy_handler(
114455   sqlite3 *db,
114456   int (*xBusy)(void*,int),
114457   void *pArg
114458 ){
114459   sqlite3_mutex_enter(db->mutex);
114460   db->busyHandler.xFunc = xBusy;
114461   db->busyHandler.pArg = pArg;
114462   db->busyHandler.nBusy = 0;
114463   db->busyTimeout = 0;
114464   sqlite3_mutex_leave(db->mutex);
114465   return SQLITE_OK;
114466 }
114467
114468 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
114469 /*
114470 ** This routine sets the progress callback for an Sqlite database to the
114471 ** given callback function with the given argument. The progress callback will
114472 ** be invoked every nOps opcodes.
114473 */
114474 SQLITE_API void sqlite3_progress_handler(
114475   sqlite3 *db, 
114476   int nOps,
114477   int (*xProgress)(void*), 
114478   void *pArg
114479 ){
114480   sqlite3_mutex_enter(db->mutex);
114481   if( nOps>0 ){
114482     db->xProgress = xProgress;
114483     db->nProgressOps = nOps;
114484     db->pProgressArg = pArg;
114485   }else{
114486     db->xProgress = 0;
114487     db->nProgressOps = 0;
114488     db->pProgressArg = 0;
114489   }
114490   sqlite3_mutex_leave(db->mutex);
114491 }
114492 #endif
114493
114494
114495 /*
114496 ** This routine installs a default busy handler that waits for the
114497 ** specified number of milliseconds before returning 0.
114498 */
114499 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
114500   if( ms>0 ){
114501     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
114502     db->busyTimeout = ms;
114503   }else{
114504     sqlite3_busy_handler(db, 0, 0);
114505   }
114506   return SQLITE_OK;
114507 }
114508
114509 /*
114510 ** Cause any pending operation to stop at its earliest opportunity.
114511 */
114512 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
114513   db->u1.isInterrupted = 1;
114514 }
114515
114516
114517 /*
114518 ** This function is exactly the same as sqlite3_create_function(), except
114519 ** that it is designed to be called by internal code. The difference is
114520 ** that if a malloc() fails in sqlite3_create_function(), an error code
114521 ** is returned and the mallocFailed flag cleared. 
114522 */
114523 SQLITE_PRIVATE int sqlite3CreateFunc(
114524   sqlite3 *db,
114525   const char *zFunctionName,
114526   int nArg,
114527   int enc,
114528   void *pUserData,
114529   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
114530   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
114531   void (*xFinal)(sqlite3_context*),
114532   FuncDestructor *pDestructor
114533 ){
114534   FuncDef *p;
114535   int nName;
114536
114537   assert( sqlite3_mutex_held(db->mutex) );
114538   if( zFunctionName==0 ||
114539       (xFunc && (xFinal || xStep)) || 
114540       (!xFunc && (xFinal && !xStep)) ||
114541       (!xFunc && (!xFinal && xStep)) ||
114542       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
114543       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
114544     return SQLITE_MISUSE_BKPT;
114545   }
114546   
114547 #ifndef SQLITE_OMIT_UTF16
114548   /* If SQLITE_UTF16 is specified as the encoding type, transform this
114549   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
114550   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
114551   **
114552   ** If SQLITE_ANY is specified, add three versions of the function
114553   ** to the hash table.
114554   */
114555   if( enc==SQLITE_UTF16 ){
114556     enc = SQLITE_UTF16NATIVE;
114557   }else if( enc==SQLITE_ANY ){
114558     int rc;
114559     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
114560          pUserData, xFunc, xStep, xFinal, pDestructor);
114561     if( rc==SQLITE_OK ){
114562       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
114563           pUserData, xFunc, xStep, xFinal, pDestructor);
114564     }
114565     if( rc!=SQLITE_OK ){
114566       return rc;
114567     }
114568     enc = SQLITE_UTF16BE;
114569   }
114570 #else
114571   enc = SQLITE_UTF8;
114572 #endif
114573   
114574   /* Check if an existing function is being overridden or deleted. If so,
114575   ** and there are active VMs, then return SQLITE_BUSY. If a function
114576   ** is being overridden/deleted but there are no active VMs, allow the
114577   ** operation to continue but invalidate all precompiled statements.
114578   */
114579   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
114580   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
114581     if( db->activeVdbeCnt ){
114582       sqlite3Error(db, SQLITE_BUSY, 
114583         "unable to delete/modify user-function due to active statements");
114584       assert( !db->mallocFailed );
114585       return SQLITE_BUSY;
114586     }else{
114587       sqlite3ExpirePreparedStatements(db);
114588     }
114589   }
114590
114591   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
114592   assert(p || db->mallocFailed);
114593   if( !p ){
114594     return SQLITE_NOMEM;
114595   }
114596
114597   /* If an older version of the function with a configured destructor is
114598   ** being replaced invoke the destructor function here. */
114599   functionDestroy(db, p);
114600
114601   if( pDestructor ){
114602     pDestructor->nRef++;
114603   }
114604   p->pDestructor = pDestructor;
114605   p->flags = 0;
114606   p->xFunc = xFunc;
114607   p->xStep = xStep;
114608   p->xFinalize = xFinal;
114609   p->pUserData = pUserData;
114610   p->nArg = (u16)nArg;
114611   return SQLITE_OK;
114612 }
114613
114614 /*
114615 ** Create new user functions.
114616 */
114617 SQLITE_API int sqlite3_create_function(
114618   sqlite3 *db,
114619   const char *zFunc,
114620   int nArg,
114621   int enc,
114622   void *p,
114623   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
114624   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
114625   void (*xFinal)(sqlite3_context*)
114626 ){
114627   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
114628                                     xFinal, 0);
114629 }
114630
114631 SQLITE_API int sqlite3_create_function_v2(
114632   sqlite3 *db,
114633   const char *zFunc,
114634   int nArg,
114635   int enc,
114636   void *p,
114637   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
114638   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
114639   void (*xFinal)(sqlite3_context*),
114640   void (*xDestroy)(void *)
114641 ){
114642   int rc = SQLITE_ERROR;
114643   FuncDestructor *pArg = 0;
114644   sqlite3_mutex_enter(db->mutex);
114645   if( xDestroy ){
114646     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
114647     if( !pArg ){
114648       xDestroy(p);
114649       goto out;
114650     }
114651     pArg->xDestroy = xDestroy;
114652     pArg->pUserData = p;
114653   }
114654   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
114655   if( pArg && pArg->nRef==0 ){
114656     assert( rc!=SQLITE_OK );
114657     xDestroy(p);
114658     sqlite3DbFree(db, pArg);
114659   }
114660
114661  out:
114662   rc = sqlite3ApiExit(db, rc);
114663   sqlite3_mutex_leave(db->mutex);
114664   return rc;
114665 }
114666
114667 #ifndef SQLITE_OMIT_UTF16
114668 SQLITE_API int sqlite3_create_function16(
114669   sqlite3 *db,
114670   const void *zFunctionName,
114671   int nArg,
114672   int eTextRep,
114673   void *p,
114674   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
114675   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
114676   void (*xFinal)(sqlite3_context*)
114677 ){
114678   int rc;
114679   char *zFunc8;
114680   sqlite3_mutex_enter(db->mutex);
114681   assert( !db->mallocFailed );
114682   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
114683   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
114684   sqlite3DbFree(db, zFunc8);
114685   rc = sqlite3ApiExit(db, rc);
114686   sqlite3_mutex_leave(db->mutex);
114687   return rc;
114688 }
114689 #endif
114690
114691
114692 /*
114693 ** Declare that a function has been overloaded by a virtual table.
114694 **
114695 ** If the function already exists as a regular global function, then
114696 ** this routine is a no-op.  If the function does not exist, then create
114697 ** a new one that always throws a run-time error.  
114698 **
114699 ** When virtual tables intend to provide an overloaded function, they
114700 ** should call this routine to make sure the global function exists.
114701 ** A global function must exist in order for name resolution to work
114702 ** properly.
114703 */
114704 SQLITE_API int sqlite3_overload_function(
114705   sqlite3 *db,
114706   const char *zName,
114707   int nArg
114708 ){
114709   int nName = sqlite3Strlen30(zName);
114710   int rc = SQLITE_OK;
114711   sqlite3_mutex_enter(db->mutex);
114712   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
114713     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
114714                            0, sqlite3InvalidFunction, 0, 0, 0);
114715   }
114716   rc = sqlite3ApiExit(db, rc);
114717   sqlite3_mutex_leave(db->mutex);
114718   return rc;
114719 }
114720
114721 #ifndef SQLITE_OMIT_TRACE
114722 /*
114723 ** Register a trace function.  The pArg from the previously registered trace
114724 ** is returned.  
114725 **
114726 ** A NULL trace function means that no tracing is executes.  A non-NULL
114727 ** trace is a pointer to a function that is invoked at the start of each
114728 ** SQL statement.
114729 */
114730 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
114731   void *pOld;
114732   sqlite3_mutex_enter(db->mutex);
114733   pOld = db->pTraceArg;
114734   db->xTrace = xTrace;
114735   db->pTraceArg = pArg;
114736   sqlite3_mutex_leave(db->mutex);
114737   return pOld;
114738 }
114739 /*
114740 ** Register a profile function.  The pArg from the previously registered 
114741 ** profile function is returned.  
114742 **
114743 ** A NULL profile function means that no profiling is executes.  A non-NULL
114744 ** profile is a pointer to a function that is invoked at the conclusion of
114745 ** each SQL statement that is run.
114746 */
114747 SQLITE_API void *sqlite3_profile(
114748   sqlite3 *db,
114749   void (*xProfile)(void*,const char*,sqlite_uint64),
114750   void *pArg
114751 ){
114752   void *pOld;
114753   sqlite3_mutex_enter(db->mutex);
114754   pOld = db->pProfileArg;
114755   db->xProfile = xProfile;
114756   db->pProfileArg = pArg;
114757   sqlite3_mutex_leave(db->mutex);
114758   return pOld;
114759 }
114760 #endif /* SQLITE_OMIT_TRACE */
114761
114762 /*
114763 ** Register a function to be invoked when a transaction commits.
114764 ** If the invoked function returns non-zero, then the commit becomes a
114765 ** rollback.
114766 */
114767 SQLITE_API void *sqlite3_commit_hook(
114768   sqlite3 *db,              /* Attach the hook to this database */
114769   int (*xCallback)(void*),  /* Function to invoke on each commit */
114770   void *pArg                /* Argument to the function */
114771 ){
114772   void *pOld;
114773   sqlite3_mutex_enter(db->mutex);
114774   pOld = db->pCommitArg;
114775   db->xCommitCallback = xCallback;
114776   db->pCommitArg = pArg;
114777   sqlite3_mutex_leave(db->mutex);
114778   return pOld;
114779 }
114780
114781 /*
114782 ** Register a callback to be invoked each time a row is updated,
114783 ** inserted or deleted using this database connection.
114784 */
114785 SQLITE_API void *sqlite3_update_hook(
114786   sqlite3 *db,              /* Attach the hook to this database */
114787   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
114788   void *pArg                /* Argument to the function */
114789 ){
114790   void *pRet;
114791   sqlite3_mutex_enter(db->mutex);
114792   pRet = db->pUpdateArg;
114793   db->xUpdateCallback = xCallback;
114794   db->pUpdateArg = pArg;
114795   sqlite3_mutex_leave(db->mutex);
114796   return pRet;
114797 }
114798
114799 /*
114800 ** Register a callback to be invoked each time a transaction is rolled
114801 ** back by this database connection.
114802 */
114803 SQLITE_API void *sqlite3_rollback_hook(
114804   sqlite3 *db,              /* Attach the hook to this database */
114805   void (*xCallback)(void*), /* Callback function */
114806   void *pArg                /* Argument to the function */
114807 ){
114808   void *pRet;
114809   sqlite3_mutex_enter(db->mutex);
114810   pRet = db->pRollbackArg;
114811   db->xRollbackCallback = xCallback;
114812   db->pRollbackArg = pArg;
114813   sqlite3_mutex_leave(db->mutex);
114814   return pRet;
114815 }
114816
114817 #ifndef SQLITE_OMIT_WAL
114818 /*
114819 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
114820 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
114821 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
114822 ** wal_autocheckpoint()).
114823 */ 
114824 SQLITE_PRIVATE int sqlite3WalDefaultHook(
114825   void *pClientData,     /* Argument */
114826   sqlite3 *db,           /* Connection */
114827   const char *zDb,       /* Database */
114828   int nFrame             /* Size of WAL */
114829 ){
114830   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
114831     sqlite3BeginBenignMalloc();
114832     sqlite3_wal_checkpoint(db, zDb);
114833     sqlite3EndBenignMalloc();
114834   }
114835   return SQLITE_OK;
114836 }
114837 #endif /* SQLITE_OMIT_WAL */
114838
114839 /*
114840 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
114841 ** a database after committing a transaction if there are nFrame or
114842 ** more frames in the log file. Passing zero or a negative value as the
114843 ** nFrame parameter disables automatic checkpoints entirely.
114844 **
114845 ** The callback registered by this function replaces any existing callback
114846 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
114847 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
114848 ** configured by this function.
114849 */
114850 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
114851 #ifdef SQLITE_OMIT_WAL
114852   UNUSED_PARAMETER(db);
114853   UNUSED_PARAMETER(nFrame);
114854 #else
114855   if( nFrame>0 ){
114856     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
114857   }else{
114858     sqlite3_wal_hook(db, 0, 0);
114859   }
114860 #endif
114861   return SQLITE_OK;
114862 }
114863
114864 /*
114865 ** Register a callback to be invoked each time a transaction is written
114866 ** into the write-ahead-log by this database connection.
114867 */
114868 SQLITE_API void *sqlite3_wal_hook(
114869   sqlite3 *db,                    /* Attach the hook to this db handle */
114870   int(*xCallback)(void *, sqlite3*, const char*, int),
114871   void *pArg                      /* First argument passed to xCallback() */
114872 ){
114873 #ifndef SQLITE_OMIT_WAL
114874   void *pRet;
114875   sqlite3_mutex_enter(db->mutex);
114876   pRet = db->pWalArg;
114877   db->xWalCallback = xCallback;
114878   db->pWalArg = pArg;
114879   sqlite3_mutex_leave(db->mutex);
114880   return pRet;
114881 #else
114882   return 0;
114883 #endif
114884 }
114885
114886 /*
114887 ** Checkpoint database zDb.
114888 */
114889 SQLITE_API int sqlite3_wal_checkpoint_v2(
114890   sqlite3 *db,                    /* Database handle */
114891   const char *zDb,                /* Name of attached database (or NULL) */
114892   int eMode,                      /* SQLITE_CHECKPOINT_* value */
114893   int *pnLog,                     /* OUT: Size of WAL log in frames */
114894   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
114895 ){
114896 #ifdef SQLITE_OMIT_WAL
114897   return SQLITE_OK;
114898 #else
114899   int rc;                         /* Return code */
114900   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
114901
114902   /* Initialize the output variables to -1 in case an error occurs. */
114903   if( pnLog ) *pnLog = -1;
114904   if( pnCkpt ) *pnCkpt = -1;
114905
114906   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
114907   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
114908   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
114909   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
114910     return SQLITE_MISUSE;
114911   }
114912
114913   sqlite3_mutex_enter(db->mutex);
114914   if( zDb && zDb[0] ){
114915     iDb = sqlite3FindDbName(db, zDb);
114916   }
114917   if( iDb<0 ){
114918     rc = SQLITE_ERROR;
114919     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
114920   }else{
114921     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
114922     sqlite3Error(db, rc, 0);
114923   }
114924   rc = sqlite3ApiExit(db, rc);
114925   sqlite3_mutex_leave(db->mutex);
114926   return rc;
114927 #endif
114928 }
114929
114930
114931 /*
114932 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
114933 ** to contains a zero-length string, all attached databases are 
114934 ** checkpointed.
114935 */
114936 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
114937   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
114938 }
114939
114940 #ifndef SQLITE_OMIT_WAL
114941 /*
114942 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
114943 ** not currently open in WAL mode.
114944 **
114945 ** If a transaction is open on the database being checkpointed, this 
114946 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
114947 ** an error occurs while running the checkpoint, an SQLite error code is 
114948 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
114949 **
114950 ** The mutex on database handle db should be held by the caller. The mutex
114951 ** associated with the specific b-tree being checkpointed is taken by
114952 ** this function while the checkpoint is running.
114953 **
114954 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
114955 ** checkpointed. If an error is encountered it is returned immediately -
114956 ** no attempt is made to checkpoint any remaining databases.
114957 **
114958 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
114959 */
114960 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
114961   int rc = SQLITE_OK;             /* Return code */
114962   int i;                          /* Used to iterate through attached dbs */
114963   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
114964
114965   assert( sqlite3_mutex_held(db->mutex) );
114966   assert( !pnLog || *pnLog==-1 );
114967   assert( !pnCkpt || *pnCkpt==-1 );
114968
114969   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
114970     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
114971       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
114972       pnLog = 0;
114973       pnCkpt = 0;
114974       if( rc==SQLITE_BUSY ){
114975         bBusy = 1;
114976         rc = SQLITE_OK;
114977       }
114978     }
114979   }
114980
114981   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
114982 }
114983 #endif /* SQLITE_OMIT_WAL */
114984
114985 /*
114986 ** This function returns true if main-memory should be used instead of
114987 ** a temporary file for transient pager files and statement journals.
114988 ** The value returned depends on the value of db->temp_store (runtime
114989 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
114990 ** following table describes the relationship between these two values
114991 ** and this functions return value.
114992 **
114993 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
114994 **   -----------------     --------------     ------------------------------
114995 **   0                     any                file      (return 0)
114996 **   1                     1                  file      (return 0)
114997 **   1                     2                  memory    (return 1)
114998 **   1                     0                  file      (return 0)
114999 **   2                     1                  file      (return 0)
115000 **   2                     2                  memory    (return 1)
115001 **   2                     0                  memory    (return 1)
115002 **   3                     any                memory    (return 1)
115003 */
115004 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
115005 #if SQLITE_TEMP_STORE==1
115006   return ( db->temp_store==2 );
115007 #endif
115008 #if SQLITE_TEMP_STORE==2
115009   return ( db->temp_store!=1 );
115010 #endif
115011 #if SQLITE_TEMP_STORE==3
115012   return 1;
115013 #endif
115014 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
115015   return 0;
115016 #endif
115017 }
115018
115019 /*
115020 ** Return UTF-8 encoded English language explanation of the most recent
115021 ** error.
115022 */
115023 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
115024   const char *z;
115025   if( !db ){
115026     return sqlite3ErrStr(SQLITE_NOMEM);
115027   }
115028   if( !sqlite3SafetyCheckSickOrOk(db) ){
115029     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
115030   }
115031   sqlite3_mutex_enter(db->mutex);
115032   if( db->mallocFailed ){
115033     z = sqlite3ErrStr(SQLITE_NOMEM);
115034   }else{
115035     z = (char*)sqlite3_value_text(db->pErr);
115036     assert( !db->mallocFailed );
115037     if( z==0 ){
115038       z = sqlite3ErrStr(db->errCode);
115039     }
115040   }
115041   sqlite3_mutex_leave(db->mutex);
115042   return z;
115043 }
115044
115045 #ifndef SQLITE_OMIT_UTF16
115046 /*
115047 ** Return UTF-16 encoded English language explanation of the most recent
115048 ** error.
115049 */
115050 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
115051   static const u16 outOfMem[] = {
115052     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
115053   };
115054   static const u16 misuse[] = {
115055     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
115056     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
115057     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
115058     'o', 'u', 't', ' ', 
115059     'o', 'f', ' ', 
115060     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
115061   };
115062
115063   const void *z;
115064   if( !db ){
115065     return (void *)outOfMem;
115066   }
115067   if( !sqlite3SafetyCheckSickOrOk(db) ){
115068     return (void *)misuse;
115069   }
115070   sqlite3_mutex_enter(db->mutex);
115071   if( db->mallocFailed ){
115072     z = (void *)outOfMem;
115073   }else{
115074     z = sqlite3_value_text16(db->pErr);
115075     if( z==0 ){
115076       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
115077            SQLITE_UTF8, SQLITE_STATIC);
115078       z = sqlite3_value_text16(db->pErr);
115079     }
115080     /* A malloc() may have failed within the call to sqlite3_value_text16()
115081     ** above. If this is the case, then the db->mallocFailed flag needs to
115082     ** be cleared before returning. Do this directly, instead of via
115083     ** sqlite3ApiExit(), to avoid setting the database handle error message.
115084     */
115085     db->mallocFailed = 0;
115086   }
115087   sqlite3_mutex_leave(db->mutex);
115088   return z;
115089 }
115090 #endif /* SQLITE_OMIT_UTF16 */
115091
115092 /*
115093 ** Return the most recent error code generated by an SQLite routine. If NULL is
115094 ** passed to this function, we assume a malloc() failed during sqlite3_open().
115095 */
115096 SQLITE_API int sqlite3_errcode(sqlite3 *db){
115097   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
115098     return SQLITE_MISUSE_BKPT;
115099   }
115100   if( !db || db->mallocFailed ){
115101     return SQLITE_NOMEM;
115102   }
115103   return db->errCode & db->errMask;
115104 }
115105 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
115106   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
115107     return SQLITE_MISUSE_BKPT;
115108   }
115109   if( !db || db->mallocFailed ){
115110     return SQLITE_NOMEM;
115111   }
115112   return db->errCode;
115113 }
115114
115115 /*
115116 ** Return a string that describes the kind of error specified in the
115117 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
115118 ** function.
115119 */
115120 SQLITE_API const char *sqlite3_errstr(int rc){
115121   return sqlite3ErrStr(rc);
115122 }
115123
115124 /*
115125 ** Create a new collating function for database "db".  The name is zName
115126 ** and the encoding is enc.
115127 */
115128 static int createCollation(
115129   sqlite3* db,
115130   const char *zName, 
115131   u8 enc,
115132   void* pCtx,
115133   int(*xCompare)(void*,int,const void*,int,const void*),
115134   void(*xDel)(void*)
115135 ){
115136   CollSeq *pColl;
115137   int enc2;
115138   int nName = sqlite3Strlen30(zName);
115139   
115140   assert( sqlite3_mutex_held(db->mutex) );
115141
115142   /* If SQLITE_UTF16 is specified as the encoding type, transform this
115143   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
115144   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
115145   */
115146   enc2 = enc;
115147   testcase( enc2==SQLITE_UTF16 );
115148   testcase( enc2==SQLITE_UTF16_ALIGNED );
115149   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
115150     enc2 = SQLITE_UTF16NATIVE;
115151   }
115152   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
115153     return SQLITE_MISUSE_BKPT;
115154   }
115155
115156   /* Check if this call is removing or replacing an existing collation 
115157   ** sequence. If so, and there are active VMs, return busy. If there
115158   ** are no active VMs, invalidate any pre-compiled statements.
115159   */
115160   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
115161   if( pColl && pColl->xCmp ){
115162     if( db->activeVdbeCnt ){
115163       sqlite3Error(db, SQLITE_BUSY, 
115164         "unable to delete/modify collation sequence due to active statements");
115165       return SQLITE_BUSY;
115166     }
115167     sqlite3ExpirePreparedStatements(db);
115168
115169     /* If collation sequence pColl was created directly by a call to
115170     ** sqlite3_create_collation, and not generated by synthCollSeq(),
115171     ** then any copies made by synthCollSeq() need to be invalidated.
115172     ** Also, collation destructor - CollSeq.xDel() - function may need
115173     ** to be called.
115174     */ 
115175     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
115176       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
115177       int j;
115178       for(j=0; j<3; j++){
115179         CollSeq *p = &aColl[j];
115180         if( p->enc==pColl->enc ){
115181           if( p->xDel ){
115182             p->xDel(p->pUser);
115183           }
115184           p->xCmp = 0;
115185         }
115186       }
115187     }
115188   }
115189
115190   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
115191   if( pColl==0 ) return SQLITE_NOMEM;
115192   pColl->xCmp = xCompare;
115193   pColl->pUser = pCtx;
115194   pColl->xDel = xDel;
115195   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
115196   sqlite3Error(db, SQLITE_OK, 0);
115197   return SQLITE_OK;
115198 }
115199
115200
115201 /*
115202 ** This array defines hard upper bounds on limit values.  The
115203 ** initializer must be kept in sync with the SQLITE_LIMIT_*
115204 ** #defines in sqlite3.h.
115205 */
115206 static const int aHardLimit[] = {
115207   SQLITE_MAX_LENGTH,
115208   SQLITE_MAX_SQL_LENGTH,
115209   SQLITE_MAX_COLUMN,
115210   SQLITE_MAX_EXPR_DEPTH,
115211   SQLITE_MAX_COMPOUND_SELECT,
115212   SQLITE_MAX_VDBE_OP,
115213   SQLITE_MAX_FUNCTION_ARG,
115214   SQLITE_MAX_ATTACHED,
115215   SQLITE_MAX_LIKE_PATTERN_LENGTH,
115216   SQLITE_MAX_VARIABLE_NUMBER,
115217   SQLITE_MAX_TRIGGER_DEPTH,
115218 };
115219
115220 /*
115221 ** Make sure the hard limits are set to reasonable values
115222 */
115223 #if SQLITE_MAX_LENGTH<100
115224 # error SQLITE_MAX_LENGTH must be at least 100
115225 #endif
115226 #if SQLITE_MAX_SQL_LENGTH<100
115227 # error SQLITE_MAX_SQL_LENGTH must be at least 100
115228 #endif
115229 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
115230 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
115231 #endif
115232 #if SQLITE_MAX_COMPOUND_SELECT<2
115233 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
115234 #endif
115235 #if SQLITE_MAX_VDBE_OP<40
115236 # error SQLITE_MAX_VDBE_OP must be at least 40
115237 #endif
115238 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
115239 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
115240 #endif
115241 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
115242 # error SQLITE_MAX_ATTACHED must be between 0 and 62
115243 #endif
115244 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
115245 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
115246 #endif
115247 #if SQLITE_MAX_COLUMN>32767
115248 # error SQLITE_MAX_COLUMN must not exceed 32767
115249 #endif
115250 #if SQLITE_MAX_TRIGGER_DEPTH<1
115251 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
115252 #endif
115253
115254
115255 /*
115256 ** Change the value of a limit.  Report the old value.
115257 ** If an invalid limit index is supplied, report -1.
115258 ** Make no changes but still report the old value if the
115259 ** new limit is negative.
115260 **
115261 ** A new lower limit does not shrink existing constructs.
115262 ** It merely prevents new constructs that exceed the limit
115263 ** from forming.
115264 */
115265 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
115266   int oldLimit;
115267
115268
115269   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
115270   ** there is a hard upper bound set at compile-time by a C preprocessor
115271   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
115272   ** "_MAX_".)
115273   */
115274   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
115275   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
115276   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
115277   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
115278   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
115279   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
115280   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
115281   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
115282   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
115283                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
115284   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
115285   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
115286   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
115287
115288
115289   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
115290     return -1;
115291   }
115292   oldLimit = db->aLimit[limitId];
115293   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
115294     if( newLimit>aHardLimit[limitId] ){
115295       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
115296     }
115297     db->aLimit[limitId] = newLimit;
115298   }
115299   return oldLimit;                     /* IMP: R-53341-35419 */
115300 }
115301
115302 /*
115303 ** This function is used to parse both URIs and non-URI filenames passed by the
115304 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
115305 ** URIs specified as part of ATTACH statements.
115306 **
115307 ** The first argument to this function is the name of the VFS to use (or
115308 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
115309 ** query parameter. The second argument contains the URI (or non-URI filename)
115310 ** itself. When this function is called the *pFlags variable should contain
115311 ** the default flags to open the database handle with. The value stored in
115312 ** *pFlags may be updated before returning if the URI filename contains 
115313 ** "cache=xxx" or "mode=xxx" query parameters.
115314 **
115315 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
115316 ** the VFS that should be used to open the database file. *pzFile is set to
115317 ** point to a buffer containing the name of the file to open. It is the 
115318 ** responsibility of the caller to eventually call sqlite3_free() to release
115319 ** this buffer.
115320 **
115321 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
115322 ** may be set to point to a buffer containing an English language error 
115323 ** message. It is the responsibility of the caller to eventually release
115324 ** this buffer by calling sqlite3_free().
115325 */
115326 SQLITE_PRIVATE int sqlite3ParseUri(
115327   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
115328   const char *zUri,               /* Nul-terminated URI to parse */
115329   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
115330   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
115331   char **pzFile,                  /* OUT: Filename component of URI */
115332   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
115333 ){
115334   int rc = SQLITE_OK;
115335   unsigned int flags = *pFlags;
115336   const char *zVfs = zDefaultVfs;
115337   char *zFile;
115338   char c;
115339   int nUri = sqlite3Strlen30(zUri);
115340
115341   assert( *pzErrMsg==0 );
115342
115343   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri) 
115344    && nUri>=5 && memcmp(zUri, "file:", 5)==0 
115345   ){
115346     char *zOpt;
115347     int eState;                   /* Parser state when parsing URI */
115348     int iIn;                      /* Input character index */
115349     int iOut = 0;                 /* Output character index */
115350     int nByte = nUri+2;           /* Bytes of space to allocate */
115351
115352     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
115353     ** method that there may be extra parameters following the file-name.  */
115354     flags |= SQLITE_OPEN_URI;
115355
115356     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
115357     zFile = sqlite3_malloc(nByte);
115358     if( !zFile ) return SQLITE_NOMEM;
115359
115360     /* Discard the scheme and authority segments of the URI. */
115361     if( zUri[5]=='/' && zUri[6]=='/' ){
115362       iIn = 7;
115363       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
115364
115365       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
115366         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
115367             iIn-7, &zUri[7]);
115368         rc = SQLITE_ERROR;
115369         goto parse_uri_out;
115370       }
115371     }else{
115372       iIn = 5;
115373     }
115374
115375     /* Copy the filename and any query parameters into the zFile buffer. 
115376     ** Decode %HH escape codes along the way. 
115377     **
115378     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
115379     ** on the parsing context. As follows:
115380     **
115381     **   0: Parsing file-name.
115382     **   1: Parsing name section of a name=value query parameter.
115383     **   2: Parsing value section of a name=value query parameter.
115384     */
115385     eState = 0;
115386     while( (c = zUri[iIn])!=0 && c!='#' ){
115387       iIn++;
115388       if( c=='%' 
115389        && sqlite3Isxdigit(zUri[iIn]) 
115390        && sqlite3Isxdigit(zUri[iIn+1]) 
115391       ){
115392         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
115393         octet += sqlite3HexToInt(zUri[iIn++]);
115394
115395         assert( octet>=0 && octet<256 );
115396         if( octet==0 ){
115397           /* This branch is taken when "%00" appears within the URI. In this
115398           ** case we ignore all text in the remainder of the path, name or
115399           ** value currently being parsed. So ignore the current character
115400           ** and skip to the next "?", "=" or "&", as appropriate. */
115401           while( (c = zUri[iIn])!=0 && c!='#' 
115402               && (eState!=0 || c!='?')
115403               && (eState!=1 || (c!='=' && c!='&'))
115404               && (eState!=2 || c!='&')
115405           ){
115406             iIn++;
115407           }
115408           continue;
115409         }
115410         c = octet;
115411       }else if( eState==1 && (c=='&' || c=='=') ){
115412         if( zFile[iOut-1]==0 ){
115413           /* An empty option name. Ignore this option altogether. */
115414           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
115415           continue;
115416         }
115417         if( c=='&' ){
115418           zFile[iOut++] = '\0';
115419         }else{
115420           eState = 2;
115421         }
115422         c = 0;
115423       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
115424         c = 0;
115425         eState = 1;
115426       }
115427       zFile[iOut++] = c;
115428     }
115429     if( eState==1 ) zFile[iOut++] = '\0';
115430     zFile[iOut++] = '\0';
115431     zFile[iOut++] = '\0';
115432
115433     /* Check if there were any options specified that should be interpreted 
115434     ** here. Options that are interpreted here include "vfs" and those that
115435     ** correspond to flags that may be passed to the sqlite3_open_v2()
115436     ** method. */
115437     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
115438     while( zOpt[0] ){
115439       int nOpt = sqlite3Strlen30(zOpt);
115440       char *zVal = &zOpt[nOpt+1];
115441       int nVal = sqlite3Strlen30(zVal);
115442
115443       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
115444         zVfs = zVal;
115445       }else{
115446         struct OpenMode {
115447           const char *z;
115448           int mode;
115449         } *aMode = 0;
115450         char *zModeType = 0;
115451         int mask = 0;
115452         int limit = 0;
115453
115454         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
115455           static struct OpenMode aCacheMode[] = {
115456             { "shared",  SQLITE_OPEN_SHAREDCACHE },
115457             { "private", SQLITE_OPEN_PRIVATECACHE },
115458             { 0, 0 }
115459           };
115460
115461           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
115462           aMode = aCacheMode;
115463           limit = mask;
115464           zModeType = "cache";
115465         }
115466         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
115467           static struct OpenMode aOpenMode[] = {
115468             { "ro",  SQLITE_OPEN_READONLY },
115469             { "rw",  SQLITE_OPEN_READWRITE }, 
115470             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
115471             { "memory", SQLITE_OPEN_MEMORY },
115472             { 0, 0 }
115473           };
115474
115475           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
115476                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
115477           aMode = aOpenMode;
115478           limit = mask & flags;
115479           zModeType = "access";
115480         }
115481
115482         if( aMode ){
115483           int i;
115484           int mode = 0;
115485           for(i=0; aMode[i].z; i++){
115486             const char *z = aMode[i].z;
115487             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
115488               mode = aMode[i].mode;
115489               break;
115490             }
115491           }
115492           if( mode==0 ){
115493             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
115494             rc = SQLITE_ERROR;
115495             goto parse_uri_out;
115496           }
115497           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
115498             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
115499                                         zModeType, zVal);
115500             rc = SQLITE_PERM;
115501             goto parse_uri_out;
115502           }
115503           flags = (flags & ~mask) | mode;
115504         }
115505       }
115506
115507       zOpt = &zVal[nVal+1];
115508     }
115509
115510   }else{
115511     zFile = sqlite3_malloc(nUri+2);
115512     if( !zFile ) return SQLITE_NOMEM;
115513     memcpy(zFile, zUri, nUri);
115514     zFile[nUri] = '\0';
115515     zFile[nUri+1] = '\0';
115516     flags &= ~SQLITE_OPEN_URI;
115517   }
115518
115519   *ppVfs = sqlite3_vfs_find(zVfs);
115520   if( *ppVfs==0 ){
115521     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
115522     rc = SQLITE_ERROR;
115523   }
115524  parse_uri_out:
115525   if( rc!=SQLITE_OK ){
115526     sqlite3_free(zFile);
115527     zFile = 0;
115528   }
115529   *pFlags = flags;
115530   *pzFile = zFile;
115531   return rc;
115532 }
115533
115534
115535 /*
115536 ** This routine does the work of opening a database on behalf of
115537 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
115538 ** is UTF-8 encoded.
115539 */
115540 static int openDatabase(
115541   const char *zFilename, /* Database filename UTF-8 encoded */
115542   sqlite3 **ppDb,        /* OUT: Returned database handle */
115543   unsigned int flags,    /* Operational flags */
115544   const char *zVfs       /* Name of the VFS to use */
115545 ){
115546   sqlite3 *db;                    /* Store allocated handle here */
115547   int rc;                         /* Return code */
115548   int isThreadsafe;               /* True for threadsafe connections */
115549   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
115550   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
115551
115552   *ppDb = 0;
115553 #ifndef SQLITE_OMIT_AUTOINIT
115554   rc = sqlite3_initialize();
115555   if( rc ) return rc;
115556 #endif
115557
115558   /* Only allow sensible combinations of bits in the flags argument.  
115559   ** Throw an error if any non-sense combination is used.  If we
115560   ** do not block illegal combinations here, it could trigger
115561   ** assert() statements in deeper layers.  Sensible combinations
115562   ** are:
115563   **
115564   **  1:  SQLITE_OPEN_READONLY
115565   **  2:  SQLITE_OPEN_READWRITE
115566   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
115567   */
115568   assert( SQLITE_OPEN_READONLY  == 0x01 );
115569   assert( SQLITE_OPEN_READWRITE == 0x02 );
115570   assert( SQLITE_OPEN_CREATE    == 0x04 );
115571   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
115572   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
115573   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
115574   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
115575
115576   if( sqlite3GlobalConfig.bCoreMutex==0 ){
115577     isThreadsafe = 0;
115578   }else if( flags & SQLITE_OPEN_NOMUTEX ){
115579     isThreadsafe = 0;
115580   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
115581     isThreadsafe = 1;
115582   }else{
115583     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
115584   }
115585   if( flags & SQLITE_OPEN_PRIVATECACHE ){
115586     flags &= ~SQLITE_OPEN_SHAREDCACHE;
115587   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
115588     flags |= SQLITE_OPEN_SHAREDCACHE;
115589   }
115590
115591   /* Remove harmful bits from the flags parameter
115592   **
115593   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
115594   ** dealt with in the previous code block.  Besides these, the only
115595   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
115596   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
115597   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
115598   ** off all other flags.
115599   */
115600   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
115601                SQLITE_OPEN_EXCLUSIVE |
115602                SQLITE_OPEN_MAIN_DB |
115603                SQLITE_OPEN_TEMP_DB | 
115604                SQLITE_OPEN_TRANSIENT_DB | 
115605                SQLITE_OPEN_MAIN_JOURNAL | 
115606                SQLITE_OPEN_TEMP_JOURNAL | 
115607                SQLITE_OPEN_SUBJOURNAL | 
115608                SQLITE_OPEN_MASTER_JOURNAL |
115609                SQLITE_OPEN_NOMUTEX |
115610                SQLITE_OPEN_FULLMUTEX |
115611                SQLITE_OPEN_WAL
115612              );
115613
115614   /* Allocate the sqlite data structure */
115615   db = sqlite3MallocZero( sizeof(sqlite3) );
115616   if( db==0 ) goto opendb_out;
115617   if( isThreadsafe ){
115618     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
115619     if( db->mutex==0 ){
115620       sqlite3_free(db);
115621       db = 0;
115622       goto opendb_out;
115623     }
115624   }
115625   sqlite3_mutex_enter(db->mutex);
115626   db->errMask = 0xff;
115627   db->nDb = 2;
115628   db->magic = SQLITE_MAGIC_BUSY;
115629   db->aDb = db->aDbStatic;
115630
115631   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
115632   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
115633   db->autoCommit = 1;
115634   db->nextAutovac = -1;
115635   db->nextPagesize = 0;
115636   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
115637 #if SQLITE_DEFAULT_FILE_FORMAT<4
115638                  | SQLITE_LegacyFileFmt
115639 #endif
115640 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
115641                  | SQLITE_LoadExtension
115642 #endif
115643 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
115644                  | SQLITE_RecTriggers
115645 #endif
115646 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
115647                  | SQLITE_ForeignKeys
115648 #endif
115649       ;
115650   sqlite3HashInit(&db->aCollSeq);
115651 #ifndef SQLITE_OMIT_VIRTUALTABLE
115652   sqlite3HashInit(&db->aModule);
115653 #endif
115654
115655   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
115656   ** and UTF-16, so add a version for each to avoid any unnecessary
115657   ** conversions. The only error that can occur here is a malloc() failure.
115658   */
115659   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
115660   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
115661   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
115662   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
115663   if( db->mallocFailed ){
115664     goto opendb_out;
115665   }
115666   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
115667   assert( db->pDfltColl!=0 );
115668
115669   /* Also add a UTF-8 case-insensitive collation sequence. */
115670   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
115671
115672   /* Parse the filename/URI argument. */
115673   db->openFlags = flags;
115674   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
115675   if( rc!=SQLITE_OK ){
115676     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
115677     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
115678     sqlite3_free(zErrMsg);
115679     goto opendb_out;
115680   }
115681
115682   /* Open the backend database driver */
115683   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
115684                         flags | SQLITE_OPEN_MAIN_DB);
115685   if( rc!=SQLITE_OK ){
115686     if( rc==SQLITE_IOERR_NOMEM ){
115687       rc = SQLITE_NOMEM;
115688     }
115689     sqlite3Error(db, rc, 0);
115690     goto opendb_out;
115691   }
115692   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
115693   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
115694
115695
115696   /* The default safety_level for the main database is 'full'; for the temp
115697   ** database it is 'NONE'. This matches the pager layer defaults.  
115698   */
115699   db->aDb[0].zName = "main";
115700   db->aDb[0].safety_level = 3;
115701   db->aDb[1].zName = "temp";
115702   db->aDb[1].safety_level = 1;
115703
115704   db->magic = SQLITE_MAGIC_OPEN;
115705   if( db->mallocFailed ){
115706     goto opendb_out;
115707   }
115708
115709   /* Register all built-in functions, but do not attempt to read the
115710   ** database schema yet. This is delayed until the first time the database
115711   ** is accessed.
115712   */
115713   sqlite3Error(db, SQLITE_OK, 0);
115714   sqlite3RegisterBuiltinFunctions(db);
115715
115716   /* Load automatic extensions - extensions that have been registered
115717   ** using the sqlite3_automatic_extension() API.
115718   */
115719   rc = sqlite3_errcode(db);
115720   if( rc==SQLITE_OK ){
115721     sqlite3AutoLoadExtensions(db);
115722     rc = sqlite3_errcode(db);
115723     if( rc!=SQLITE_OK ){
115724       goto opendb_out;
115725     }
115726   }
115727
115728 #ifdef SQLITE_ENABLE_FTS1
115729   if( !db->mallocFailed ){
115730     extern int sqlite3Fts1Init(sqlite3*);
115731     rc = sqlite3Fts1Init(db);
115732   }
115733 #endif
115734
115735 #ifdef SQLITE_ENABLE_FTS2
115736   if( !db->mallocFailed && rc==SQLITE_OK ){
115737     extern int sqlite3Fts2Init(sqlite3*);
115738     rc = sqlite3Fts2Init(db);
115739   }
115740 #endif
115741
115742 #ifdef SQLITE_ENABLE_FTS3
115743   if( !db->mallocFailed && rc==SQLITE_OK ){
115744     rc = sqlite3Fts3Init(db);
115745   }
115746 #endif
115747
115748 #ifdef SQLITE_ENABLE_ICU
115749   if( !db->mallocFailed && rc==SQLITE_OK ){
115750     rc = sqlite3IcuInit(db);
115751   }
115752 #endif
115753
115754 #ifdef SQLITE_ENABLE_RTREE
115755   if( !db->mallocFailed && rc==SQLITE_OK){
115756     rc = sqlite3RtreeInit(db);
115757   }
115758 #endif
115759
115760   sqlite3Error(db, rc, 0);
115761
115762   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
115763   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
115764   ** mode.  Doing nothing at all also makes NORMAL the default.
115765   */
115766 #ifdef SQLITE_DEFAULT_LOCKING_MODE
115767   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
115768   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
115769                           SQLITE_DEFAULT_LOCKING_MODE);
115770 #endif
115771
115772   /* Enable the lookaside-malloc subsystem */
115773   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
115774                         sqlite3GlobalConfig.nLookaside);
115775
115776   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
115777
115778 opendb_out:
115779   sqlite3_free(zOpen);
115780   if( db ){
115781     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
115782     sqlite3_mutex_leave(db->mutex);
115783   }
115784   rc = sqlite3_errcode(db);
115785   assert( db!=0 || rc==SQLITE_NOMEM );
115786   if( rc==SQLITE_NOMEM ){
115787     sqlite3_close(db);
115788     db = 0;
115789   }else if( rc!=SQLITE_OK ){
115790     db->magic = SQLITE_MAGIC_SICK;
115791   }
115792   *ppDb = db;
115793 #ifdef SQLITE_ENABLE_SQLLOG
115794   if( sqlite3GlobalConfig.xSqllog ){
115795     /* Opening a db handle. Fourth parameter is passed 0. */
115796     void *pArg = sqlite3GlobalConfig.pSqllogArg;
115797     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
115798   }
115799 #endif
115800   return sqlite3ApiExit(0, rc);
115801 }
115802
115803 /*
115804 ** Open a new database handle.
115805 */
115806 SQLITE_API int sqlite3_open(
115807   const char *zFilename, 
115808   sqlite3 **ppDb 
115809 ){
115810   return openDatabase(zFilename, ppDb,
115811                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
115812 }
115813 SQLITE_API int sqlite3_open_v2(
115814   const char *filename,   /* Database filename (UTF-8) */
115815   sqlite3 **ppDb,         /* OUT: SQLite db handle */
115816   int flags,              /* Flags */
115817   const char *zVfs        /* Name of VFS module to use */
115818 ){
115819   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
115820 }
115821
115822 #ifndef SQLITE_OMIT_UTF16
115823 /*
115824 ** Open a new database handle.
115825 */
115826 SQLITE_API int sqlite3_open16(
115827   const void *zFilename, 
115828   sqlite3 **ppDb
115829 ){
115830   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
115831   sqlite3_value *pVal;
115832   int rc;
115833
115834   assert( zFilename );
115835   assert( ppDb );
115836   *ppDb = 0;
115837 #ifndef SQLITE_OMIT_AUTOINIT
115838   rc = sqlite3_initialize();
115839   if( rc ) return rc;
115840 #endif
115841   pVal = sqlite3ValueNew(0);
115842   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
115843   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
115844   if( zFilename8 ){
115845     rc = openDatabase(zFilename8, ppDb,
115846                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
115847     assert( *ppDb || rc==SQLITE_NOMEM );
115848     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
115849       ENC(*ppDb) = SQLITE_UTF16NATIVE;
115850     }
115851   }else{
115852     rc = SQLITE_NOMEM;
115853   }
115854   sqlite3ValueFree(pVal);
115855
115856   return sqlite3ApiExit(0, rc);
115857 }
115858 #endif /* SQLITE_OMIT_UTF16 */
115859
115860 /*
115861 ** Register a new collation sequence with the database handle db.
115862 */
115863 SQLITE_API int sqlite3_create_collation(
115864   sqlite3* db, 
115865   const char *zName, 
115866   int enc, 
115867   void* pCtx,
115868   int(*xCompare)(void*,int,const void*,int,const void*)
115869 ){
115870   int rc;
115871   sqlite3_mutex_enter(db->mutex);
115872   assert( !db->mallocFailed );
115873   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
115874   rc = sqlite3ApiExit(db, rc);
115875   sqlite3_mutex_leave(db->mutex);
115876   return rc;
115877 }
115878
115879 /*
115880 ** Register a new collation sequence with the database handle db.
115881 */
115882 SQLITE_API int sqlite3_create_collation_v2(
115883   sqlite3* db, 
115884   const char *zName, 
115885   int enc, 
115886   void* pCtx,
115887   int(*xCompare)(void*,int,const void*,int,const void*),
115888   void(*xDel)(void*)
115889 ){
115890   int rc;
115891   sqlite3_mutex_enter(db->mutex);
115892   assert( !db->mallocFailed );
115893   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
115894   rc = sqlite3ApiExit(db, rc);
115895   sqlite3_mutex_leave(db->mutex);
115896   return rc;
115897 }
115898
115899 #ifndef SQLITE_OMIT_UTF16
115900 /*
115901 ** Register a new collation sequence with the database handle db.
115902 */
115903 SQLITE_API int sqlite3_create_collation16(
115904   sqlite3* db, 
115905   const void *zName,
115906   int enc, 
115907   void* pCtx,
115908   int(*xCompare)(void*,int,const void*,int,const void*)
115909 ){
115910   int rc = SQLITE_OK;
115911   char *zName8;
115912   sqlite3_mutex_enter(db->mutex);
115913   assert( !db->mallocFailed );
115914   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
115915   if( zName8 ){
115916     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
115917     sqlite3DbFree(db, zName8);
115918   }
115919   rc = sqlite3ApiExit(db, rc);
115920   sqlite3_mutex_leave(db->mutex);
115921   return rc;
115922 }
115923 #endif /* SQLITE_OMIT_UTF16 */
115924
115925 /*
115926 ** Register a collation sequence factory callback with the database handle
115927 ** db. Replace any previously installed collation sequence factory.
115928 */
115929 SQLITE_API int sqlite3_collation_needed(
115930   sqlite3 *db, 
115931   void *pCollNeededArg, 
115932   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
115933 ){
115934   sqlite3_mutex_enter(db->mutex);
115935   db->xCollNeeded = xCollNeeded;
115936   db->xCollNeeded16 = 0;
115937   db->pCollNeededArg = pCollNeededArg;
115938   sqlite3_mutex_leave(db->mutex);
115939   return SQLITE_OK;
115940 }
115941
115942 #ifndef SQLITE_OMIT_UTF16
115943 /*
115944 ** Register a collation sequence factory callback with the database handle
115945 ** db. Replace any previously installed collation sequence factory.
115946 */
115947 SQLITE_API int sqlite3_collation_needed16(
115948   sqlite3 *db, 
115949   void *pCollNeededArg, 
115950   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
115951 ){
115952   sqlite3_mutex_enter(db->mutex);
115953   db->xCollNeeded = 0;
115954   db->xCollNeeded16 = xCollNeeded16;
115955   db->pCollNeededArg = pCollNeededArg;
115956   sqlite3_mutex_leave(db->mutex);
115957   return SQLITE_OK;
115958 }
115959 #endif /* SQLITE_OMIT_UTF16 */
115960
115961 #ifndef SQLITE_OMIT_DEPRECATED
115962 /*
115963 ** This function is now an anachronism. It used to be used to recover from a
115964 ** malloc() failure, but SQLite now does this automatically.
115965 */
115966 SQLITE_API int sqlite3_global_recover(void){
115967   return SQLITE_OK;
115968 }
115969 #endif
115970
115971 /*
115972 ** Test to see whether or not the database connection is in autocommit
115973 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
115974 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
115975 ** by the next COMMIT or ROLLBACK.
115976 **
115977 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
115978 */
115979 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
115980   return db->autoCommit;
115981 }
115982
115983 /*
115984 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
115985 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
115986 ** constants.  They server two purposes:
115987 **
115988 **   1.  Serve as a convenient place to set a breakpoint in a debugger
115989 **       to detect when version error conditions occurs.
115990 **
115991 **   2.  Invoke sqlite3_log() to provide the source code location where
115992 **       a low-level error is first detected.
115993 */
115994 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
115995   testcase( sqlite3GlobalConfig.xLog!=0 );
115996   sqlite3_log(SQLITE_CORRUPT,
115997               "database corruption at line %d of [%.10s]",
115998               lineno, 20+sqlite3_sourceid());
115999   return SQLITE_CORRUPT;
116000 }
116001 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
116002   testcase( sqlite3GlobalConfig.xLog!=0 );
116003   sqlite3_log(SQLITE_MISUSE, 
116004               "misuse at line %d of [%.10s]",
116005               lineno, 20+sqlite3_sourceid());
116006   return SQLITE_MISUSE;
116007 }
116008 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
116009   testcase( sqlite3GlobalConfig.xLog!=0 );
116010   sqlite3_log(SQLITE_CANTOPEN, 
116011               "cannot open file at line %d of [%.10s]",
116012               lineno, 20+sqlite3_sourceid());
116013   return SQLITE_CANTOPEN;
116014 }
116015
116016
116017 #ifndef SQLITE_OMIT_DEPRECATED
116018 /*
116019 ** This is a convenience routine that makes sure that all thread-specific
116020 ** data for this thread has been deallocated.
116021 **
116022 ** SQLite no longer uses thread-specific data so this routine is now a
116023 ** no-op.  It is retained for historical compatibility.
116024 */
116025 SQLITE_API void sqlite3_thread_cleanup(void){
116026 }
116027 #endif
116028
116029 /*
116030 ** Return meta information about a specific column of a database table.
116031 ** See comment in sqlite3.h (sqlite.h.in) for details.
116032 */
116033 #ifdef SQLITE_ENABLE_COLUMN_METADATA
116034 SQLITE_API int sqlite3_table_column_metadata(
116035   sqlite3 *db,                /* Connection handle */
116036   const char *zDbName,        /* Database name or NULL */
116037   const char *zTableName,     /* Table name */
116038   const char *zColumnName,    /* Column name */
116039   char const **pzDataType,    /* OUTPUT: Declared data type */
116040   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
116041   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
116042   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
116043   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
116044 ){
116045   int rc;
116046   char *zErrMsg = 0;
116047   Table *pTab = 0;
116048   Column *pCol = 0;
116049   int iCol;
116050
116051   char const *zDataType = 0;
116052   char const *zCollSeq = 0;
116053   int notnull = 0;
116054   int primarykey = 0;
116055   int autoinc = 0;
116056
116057   /* Ensure the database schema has been loaded */
116058   sqlite3_mutex_enter(db->mutex);
116059   sqlite3BtreeEnterAll(db);
116060   rc = sqlite3Init(db, &zErrMsg);
116061   if( SQLITE_OK!=rc ){
116062     goto error_out;
116063   }
116064
116065   /* Locate the table in question */
116066   pTab = sqlite3FindTable(db, zTableName, zDbName);
116067   if( !pTab || pTab->pSelect ){
116068     pTab = 0;
116069     goto error_out;
116070   }
116071
116072   /* Find the column for which info is requested */
116073   if( sqlite3IsRowid(zColumnName) ){
116074     iCol = pTab->iPKey;
116075     if( iCol>=0 ){
116076       pCol = &pTab->aCol[iCol];
116077     }
116078   }else{
116079     for(iCol=0; iCol<pTab->nCol; iCol++){
116080       pCol = &pTab->aCol[iCol];
116081       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
116082         break;
116083       }
116084     }
116085     if( iCol==pTab->nCol ){
116086       pTab = 0;
116087       goto error_out;
116088     }
116089   }
116090
116091   /* The following block stores the meta information that will be returned
116092   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
116093   ** and autoinc. At this point there are two possibilities:
116094   ** 
116095   **     1. The specified column name was rowid", "oid" or "_rowid_" 
116096   **        and there is no explicitly declared IPK column. 
116097   **
116098   **     2. The table is not a view and the column name identified an 
116099   **        explicitly declared column. Copy meta information from *pCol.
116100   */ 
116101   if( pCol ){
116102     zDataType = pCol->zType;
116103     zCollSeq = pCol->zColl;
116104     notnull = pCol->notNull!=0;
116105     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
116106     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
116107   }else{
116108     zDataType = "INTEGER";
116109     primarykey = 1;
116110   }
116111   if( !zCollSeq ){
116112     zCollSeq = "BINARY";
116113   }
116114
116115 error_out:
116116   sqlite3BtreeLeaveAll(db);
116117
116118   /* Whether the function call succeeded or failed, set the output parameters
116119   ** to whatever their local counterparts contain. If an error did occur,
116120   ** this has the effect of zeroing all output parameters.
116121   */
116122   if( pzDataType ) *pzDataType = zDataType;
116123   if( pzCollSeq ) *pzCollSeq = zCollSeq;
116124   if( pNotNull ) *pNotNull = notnull;
116125   if( pPrimaryKey ) *pPrimaryKey = primarykey;
116126   if( pAutoinc ) *pAutoinc = autoinc;
116127
116128   if( SQLITE_OK==rc && !pTab ){
116129     sqlite3DbFree(db, zErrMsg);
116130     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
116131         zColumnName);
116132     rc = SQLITE_ERROR;
116133   }
116134   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
116135   sqlite3DbFree(db, zErrMsg);
116136   rc = sqlite3ApiExit(db, rc);
116137   sqlite3_mutex_leave(db->mutex);
116138   return rc;
116139 }
116140 #endif
116141
116142 /*
116143 ** Sleep for a little while.  Return the amount of time slept.
116144 */
116145 SQLITE_API int sqlite3_sleep(int ms){
116146   sqlite3_vfs *pVfs;
116147   int rc;
116148   pVfs = sqlite3_vfs_find(0);
116149   if( pVfs==0 ) return 0;
116150
116151   /* This function works in milliseconds, but the underlying OsSleep() 
116152   ** API uses microseconds. Hence the 1000's.
116153   */
116154   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
116155   return rc;
116156 }
116157
116158 /*
116159 ** Enable or disable the extended result codes.
116160 */
116161 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
116162   sqlite3_mutex_enter(db->mutex);
116163   db->errMask = onoff ? 0xffffffff : 0xff;
116164   sqlite3_mutex_leave(db->mutex);
116165   return SQLITE_OK;
116166 }
116167
116168 /*
116169 ** Invoke the xFileControl method on a particular database.
116170 */
116171 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
116172   int rc = SQLITE_ERROR;
116173   Btree *pBtree;
116174
116175   sqlite3_mutex_enter(db->mutex);
116176   pBtree = sqlite3DbNameToBtree(db, zDbName);
116177   if( pBtree ){
116178     Pager *pPager;
116179     sqlite3_file *fd;
116180     sqlite3BtreeEnter(pBtree);
116181     pPager = sqlite3BtreePager(pBtree);
116182     assert( pPager!=0 );
116183     fd = sqlite3PagerFile(pPager);
116184     assert( fd!=0 );
116185     if( op==SQLITE_FCNTL_FILE_POINTER ){
116186       *(sqlite3_file**)pArg = fd;
116187       rc = SQLITE_OK;
116188     }else if( fd->pMethods ){
116189       rc = sqlite3OsFileControl(fd, op, pArg);
116190     }else{
116191       rc = SQLITE_NOTFOUND;
116192     }
116193     sqlite3BtreeLeave(pBtree);
116194   }
116195   sqlite3_mutex_leave(db->mutex);
116196   return rc;   
116197 }
116198
116199 /*
116200 ** Interface to the testing logic.
116201 */
116202 SQLITE_API int sqlite3_test_control(int op, ...){
116203   int rc = 0;
116204 #ifndef SQLITE_OMIT_BUILTIN_TEST
116205   va_list ap;
116206   va_start(ap, op);
116207   switch( op ){
116208
116209     /*
116210     ** Save the current state of the PRNG.
116211     */
116212     case SQLITE_TESTCTRL_PRNG_SAVE: {
116213       sqlite3PrngSaveState();
116214       break;
116215     }
116216
116217     /*
116218     ** Restore the state of the PRNG to the last state saved using
116219     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
116220     ** this verb acts like PRNG_RESET.
116221     */
116222     case SQLITE_TESTCTRL_PRNG_RESTORE: {
116223       sqlite3PrngRestoreState();
116224       break;
116225     }
116226
116227     /*
116228     ** Reset the PRNG back to its uninitialized state.  The next call
116229     ** to sqlite3_randomness() will reseed the PRNG using a single call
116230     ** to the xRandomness method of the default VFS.
116231     */
116232     case SQLITE_TESTCTRL_PRNG_RESET: {
116233       sqlite3PrngResetState();
116234       break;
116235     }
116236
116237     /*
116238     **  sqlite3_test_control(BITVEC_TEST, size, program)
116239     **
116240     ** Run a test against a Bitvec object of size.  The program argument
116241     ** is an array of integers that defines the test.  Return -1 on a
116242     ** memory allocation error, 0 on success, or non-zero for an error.
116243     ** See the sqlite3BitvecBuiltinTest() for additional information.
116244     */
116245     case SQLITE_TESTCTRL_BITVEC_TEST: {
116246       int sz = va_arg(ap, int);
116247       int *aProg = va_arg(ap, int*);
116248       rc = sqlite3BitvecBuiltinTest(sz, aProg);
116249       break;
116250     }
116251
116252     /*
116253     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
116254     **
116255     ** Register hooks to call to indicate which malloc() failures 
116256     ** are benign.
116257     */
116258     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
116259       typedef void (*void_function)(void);
116260       void_function xBenignBegin;
116261       void_function xBenignEnd;
116262       xBenignBegin = va_arg(ap, void_function);
116263       xBenignEnd = va_arg(ap, void_function);
116264       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
116265       break;
116266     }
116267
116268     /*
116269     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
116270     **
116271     ** Set the PENDING byte to the value in the argument, if X>0.
116272     ** Make no changes if X==0.  Return the value of the pending byte
116273     ** as it existing before this routine was called.
116274     **
116275     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
116276     ** an incompatible database file format.  Changing the PENDING byte
116277     ** while any database connection is open results in undefined and
116278     ** dileterious behavior.
116279     */
116280     case SQLITE_TESTCTRL_PENDING_BYTE: {
116281       rc = PENDING_BYTE;
116282 #ifndef SQLITE_OMIT_WSD
116283       {
116284         unsigned int newVal = va_arg(ap, unsigned int);
116285         if( newVal ) sqlite3PendingByte = newVal;
116286       }
116287 #endif
116288       break;
116289     }
116290
116291     /*
116292     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
116293     **
116294     ** This action provides a run-time test to see whether or not
116295     ** assert() was enabled at compile-time.  If X is true and assert()
116296     ** is enabled, then the return value is true.  If X is true and
116297     ** assert() is disabled, then the return value is zero.  If X is
116298     ** false and assert() is enabled, then the assertion fires and the
116299     ** process aborts.  If X is false and assert() is disabled, then the
116300     ** return value is zero.
116301     */
116302     case SQLITE_TESTCTRL_ASSERT: {
116303       volatile int x = 0;
116304       assert( (x = va_arg(ap,int))!=0 );
116305       rc = x;
116306       break;
116307     }
116308
116309
116310     /*
116311     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
116312     **
116313     ** This action provides a run-time test to see how the ALWAYS and
116314     ** NEVER macros were defined at compile-time.
116315     **
116316     ** The return value is ALWAYS(X).  
116317     **
116318     ** The recommended test is X==2.  If the return value is 2, that means
116319     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
116320     ** default setting.  If the return value is 1, then ALWAYS() is either
116321     ** hard-coded to true or else it asserts if its argument is false.
116322     ** The first behavior (hard-coded to true) is the case if
116323     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
116324     ** behavior (assert if the argument to ALWAYS() is false) is the case if
116325     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
116326     **
116327     ** The run-time test procedure might look something like this:
116328     **
116329     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
116330     **      // ALWAYS() and NEVER() are no-op pass-through macros
116331     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
116332     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
116333     **    }else{
116334     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
116335     **    }
116336     */
116337     case SQLITE_TESTCTRL_ALWAYS: {
116338       int x = va_arg(ap,int);
116339       rc = ALWAYS(x);
116340       break;
116341     }
116342
116343     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
116344     **
116345     ** Set the nReserve size to N for the main database on the database
116346     ** connection db.
116347     */
116348     case SQLITE_TESTCTRL_RESERVE: {
116349       sqlite3 *db = va_arg(ap, sqlite3*);
116350       int x = va_arg(ap,int);
116351       sqlite3_mutex_enter(db->mutex);
116352       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
116353       sqlite3_mutex_leave(db->mutex);
116354       break;
116355     }
116356
116357     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
116358     **
116359     ** Enable or disable various optimizations for testing purposes.  The 
116360     ** argument N is a bitmask of optimizations to be disabled.  For normal
116361     ** operation N should be 0.  The idea is that a test program (like the
116362     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
116363     ** with various optimizations disabled to verify that the same answer
116364     ** is obtained in every case.
116365     */
116366     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
116367       sqlite3 *db = va_arg(ap, sqlite3*);
116368       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
116369       break;
116370     }
116371
116372 #ifdef SQLITE_N_KEYWORD
116373     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
116374     **
116375     ** If zWord is a keyword recognized by the parser, then return the
116376     ** number of keywords.  Or if zWord is not a keyword, return 0.
116377     ** 
116378     ** This test feature is only available in the amalgamation since
116379     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
116380     ** is built using separate source files.
116381     */
116382     case SQLITE_TESTCTRL_ISKEYWORD: {
116383       const char *zWord = va_arg(ap, const char*);
116384       int n = sqlite3Strlen30(zWord);
116385       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
116386       break;
116387     }
116388 #endif 
116389
116390     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
116391     **
116392     ** Pass pFree into sqlite3ScratchFree(). 
116393     ** If sz>0 then allocate a scratch buffer into pNew.  
116394     */
116395     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
116396       void *pFree, **ppNew;
116397       int sz;
116398       sz = va_arg(ap, int);
116399       ppNew = va_arg(ap, void**);
116400       pFree = va_arg(ap, void*);
116401       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
116402       sqlite3ScratchFree(pFree);
116403       break;
116404     }
116405
116406     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
116407     **
116408     ** If parameter onoff is non-zero, configure the wrappers so that all
116409     ** subsequent calls to localtime() and variants fail. If onoff is zero,
116410     ** undo this setting.
116411     */
116412     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
116413       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
116414       break;
116415     }
116416
116417 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
116418     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
116419     **                        sqlite3_stmt*,const char**);
116420     **
116421     ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
116422     ** a string that describes the optimized parse tree.  This test-control
116423     ** returns a pointer to that string.
116424     */
116425     case SQLITE_TESTCTRL_EXPLAIN_STMT: {
116426       sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
116427       const char **pzRet = va_arg(ap, const char**);
116428       *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
116429       break;
116430     }
116431 #endif
116432
116433   }
116434   va_end(ap);
116435 #endif /* SQLITE_OMIT_BUILTIN_TEST */
116436   return rc;
116437 }
116438
116439 /*
116440 ** This is a utility routine, useful to VFS implementations, that checks
116441 ** to see if a database file was a URI that contained a specific query 
116442 ** parameter, and if so obtains the value of the query parameter.
116443 **
116444 ** The zFilename argument is the filename pointer passed into the xOpen()
116445 ** method of a VFS implementation.  The zParam argument is the name of the
116446 ** query parameter we seek.  This routine returns the value of the zParam
116447 ** parameter if it exists.  If the parameter does not exist, this routine
116448 ** returns a NULL pointer.
116449 */
116450 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
116451   if( zFilename==0 ) return 0;
116452   zFilename += sqlite3Strlen30(zFilename) + 1;
116453   while( zFilename[0] ){
116454     int x = strcmp(zFilename, zParam);
116455     zFilename += sqlite3Strlen30(zFilename) + 1;
116456     if( x==0 ) return zFilename;
116457     zFilename += sqlite3Strlen30(zFilename) + 1;
116458   }
116459   return 0;
116460 }
116461
116462 /*
116463 ** Return a boolean value for a query parameter.
116464 */
116465 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
116466   const char *z = sqlite3_uri_parameter(zFilename, zParam);
116467   bDflt = bDflt!=0;
116468   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
116469 }
116470
116471 /*
116472 ** Return a 64-bit integer value for a query parameter.
116473 */
116474 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
116475   const char *zFilename,    /* Filename as passed to xOpen */
116476   const char *zParam,       /* URI parameter sought */
116477   sqlite3_int64 bDflt       /* return if parameter is missing */
116478 ){
116479   const char *z = sqlite3_uri_parameter(zFilename, zParam);
116480   sqlite3_int64 v;
116481   if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
116482     bDflt = v;
116483   }
116484   return bDflt;
116485 }
116486
116487 /*
116488 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
116489 */
116490 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
116491   int i;
116492   for(i=0; i<db->nDb; i++){
116493     if( db->aDb[i].pBt
116494      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
116495     ){
116496       return db->aDb[i].pBt;
116497     }
116498   }
116499   return 0;
116500 }
116501
116502 /*
116503 ** Return the filename of the database associated with a database
116504 ** connection.
116505 */
116506 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
116507   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
116508   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
116509 }
116510
116511 /*
116512 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
116513 ** no such database exists.
116514 */
116515 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
116516   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
116517   return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
116518 }
116519
116520 /************** End of main.c ************************************************/
116521 /************** Begin file notify.c ******************************************/
116522 /*
116523 ** 2009 March 3
116524 **
116525 ** The author disclaims copyright to this source code.  In place of
116526 ** a legal notice, here is a blessing:
116527 **
116528 **    May you do good and not evil.
116529 **    May you find forgiveness for yourself and forgive others.
116530 **    May you share freely, never taking more than you give.
116531 **
116532 *************************************************************************
116533 **
116534 ** This file contains the implementation of the sqlite3_unlock_notify()
116535 ** API method and its associated functionality.
116536 */
116537
116538 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
116539 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
116540
116541 /*
116542 ** Public interfaces:
116543 **
116544 **   sqlite3ConnectionBlocked()
116545 **   sqlite3ConnectionUnlocked()
116546 **   sqlite3ConnectionClosed()
116547 **   sqlite3_unlock_notify()
116548 */
116549
116550 #define assertMutexHeld() \
116551   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
116552
116553 /*
116554 ** Head of a linked list of all sqlite3 objects created by this process
116555 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
116556 ** is not NULL. This variable may only accessed while the STATIC_MASTER
116557 ** mutex is held.
116558 */
116559 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
116560
116561 #ifndef NDEBUG
116562 /*
116563 ** This function is a complex assert() that verifies the following 
116564 ** properties of the blocked connections list:
116565 **
116566 **   1) Each entry in the list has a non-NULL value for either 
116567 **      pUnlockConnection or pBlockingConnection, or both.
116568 **
116569 **   2) All entries in the list that share a common value for 
116570 **      xUnlockNotify are grouped together.
116571 **
116572 **   3) If the argument db is not NULL, then none of the entries in the
116573 **      blocked connections list have pUnlockConnection or pBlockingConnection
116574 **      set to db. This is used when closing connection db.
116575 */
116576 static void checkListProperties(sqlite3 *db){
116577   sqlite3 *p;
116578   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
116579     int seen = 0;
116580     sqlite3 *p2;
116581
116582     /* Verify property (1) */
116583     assert( p->pUnlockConnection || p->pBlockingConnection );
116584
116585     /* Verify property (2) */
116586     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
116587       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
116588       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
116589       assert( db==0 || p->pUnlockConnection!=db );
116590       assert( db==0 || p->pBlockingConnection!=db );
116591     }
116592   }
116593 }
116594 #else
116595 # define checkListProperties(x)
116596 #endif
116597
116598 /*
116599 ** Remove connection db from the blocked connections list. If connection
116600 ** db is not currently a part of the list, this function is a no-op.
116601 */
116602 static void removeFromBlockedList(sqlite3 *db){
116603   sqlite3 **pp;
116604   assertMutexHeld();
116605   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
116606     if( *pp==db ){
116607       *pp = (*pp)->pNextBlocked;
116608       break;
116609     }
116610   }
116611 }
116612
116613 /*
116614 ** Add connection db to the blocked connections list. It is assumed
116615 ** that it is not already a part of the list.
116616 */
116617 static void addToBlockedList(sqlite3 *db){
116618   sqlite3 **pp;
116619   assertMutexHeld();
116620   for(
116621     pp=&sqlite3BlockedList; 
116622     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
116623     pp=&(*pp)->pNextBlocked
116624   );
116625   db->pNextBlocked = *pp;
116626   *pp = db;
116627 }
116628
116629 /*
116630 ** Obtain the STATIC_MASTER mutex.
116631 */
116632 static void enterMutex(void){
116633   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
116634   checkListProperties(0);
116635 }
116636
116637 /*
116638 ** Release the STATIC_MASTER mutex.
116639 */
116640 static void leaveMutex(void){
116641   assertMutexHeld();
116642   checkListProperties(0);
116643   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
116644 }
116645
116646 /*
116647 ** Register an unlock-notify callback.
116648 **
116649 ** This is called after connection "db" has attempted some operation
116650 ** but has received an SQLITE_LOCKED error because another connection
116651 ** (call it pOther) in the same process was busy using the same shared
116652 ** cache.  pOther is found by looking at db->pBlockingConnection.
116653 **
116654 ** If there is no blocking connection, the callback is invoked immediately,
116655 ** before this routine returns.
116656 **
116657 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
116658 ** a deadlock.
116659 **
116660 ** Otherwise, make arrangements to invoke xNotify when pOther drops
116661 ** its locks.
116662 **
116663 ** Each call to this routine overrides any prior callbacks registered
116664 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
116665 ** cancelled.
116666 */
116667 SQLITE_API int sqlite3_unlock_notify(
116668   sqlite3 *db,
116669   void (*xNotify)(void **, int),
116670   void *pArg
116671 ){
116672   int rc = SQLITE_OK;
116673
116674   sqlite3_mutex_enter(db->mutex);
116675   enterMutex();
116676
116677   if( xNotify==0 ){
116678     removeFromBlockedList(db);
116679     db->pBlockingConnection = 0;
116680     db->pUnlockConnection = 0;
116681     db->xUnlockNotify = 0;
116682     db->pUnlockArg = 0;
116683   }else if( 0==db->pBlockingConnection ){
116684     /* The blocking transaction has been concluded. Or there never was a 
116685     ** blocking transaction. In either case, invoke the notify callback
116686     ** immediately. 
116687     */
116688     xNotify(&pArg, 1);
116689   }else{
116690     sqlite3 *p;
116691
116692     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
116693     if( p ){
116694       rc = SQLITE_LOCKED;              /* Deadlock detected. */
116695     }else{
116696       db->pUnlockConnection = db->pBlockingConnection;
116697       db->xUnlockNotify = xNotify;
116698       db->pUnlockArg = pArg;
116699       removeFromBlockedList(db);
116700       addToBlockedList(db);
116701     }
116702   }
116703
116704   leaveMutex();
116705   assert( !db->mallocFailed );
116706   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
116707   sqlite3_mutex_leave(db->mutex);
116708   return rc;
116709 }
116710
116711 /*
116712 ** This function is called while stepping or preparing a statement 
116713 ** associated with connection db. The operation will return SQLITE_LOCKED
116714 ** to the user because it requires a lock that will not be available
116715 ** until connection pBlocker concludes its current transaction.
116716 */
116717 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
116718   enterMutex();
116719   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
116720     addToBlockedList(db);
116721   }
116722   db->pBlockingConnection = pBlocker;
116723   leaveMutex();
116724 }
116725
116726 /*
116727 ** This function is called when
116728 ** the transaction opened by database db has just finished. Locks held 
116729 ** by database connection db have been released.
116730 **
116731 ** This function loops through each entry in the blocked connections
116732 ** list and does the following:
116733 **
116734 **   1) If the sqlite3.pBlockingConnection member of a list entry is
116735 **      set to db, then set pBlockingConnection=0.
116736 **
116737 **   2) If the sqlite3.pUnlockConnection member of a list entry is
116738 **      set to db, then invoke the configured unlock-notify callback and
116739 **      set pUnlockConnection=0.
116740 **
116741 **   3) If the two steps above mean that pBlockingConnection==0 and
116742 **      pUnlockConnection==0, remove the entry from the blocked connections
116743 **      list.
116744 */
116745 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
116746   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
116747   int nArg = 0;                            /* Number of entries in aArg[] */
116748   sqlite3 **pp;                            /* Iterator variable */
116749   void **aArg;               /* Arguments to the unlock callback */
116750   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
116751   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
116752
116753   aArg = aStatic;
116754   enterMutex();         /* Enter STATIC_MASTER mutex */
116755
116756   /* This loop runs once for each entry in the blocked-connections list. */
116757   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
116758     sqlite3 *p = *pp;
116759
116760     /* Step 1. */
116761     if( p->pBlockingConnection==db ){
116762       p->pBlockingConnection = 0;
116763     }
116764
116765     /* Step 2. */
116766     if( p->pUnlockConnection==db ){
116767       assert( p->xUnlockNotify );
116768       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
116769         xUnlockNotify(aArg, nArg);
116770         nArg = 0;
116771       }
116772
116773       sqlite3BeginBenignMalloc();
116774       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
116775       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
116776       if( (!aDyn && nArg==(int)ArraySize(aStatic))
116777        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
116778       ){
116779         /* The aArg[] array needs to grow. */
116780         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
116781         if( pNew ){
116782           memcpy(pNew, aArg, nArg*sizeof(void *));
116783           sqlite3_free(aDyn);
116784           aDyn = aArg = pNew;
116785         }else{
116786           /* This occurs when the array of context pointers that need to
116787           ** be passed to the unlock-notify callback is larger than the
116788           ** aStatic[] array allocated on the stack and the attempt to 
116789           ** allocate a larger array from the heap has failed.
116790           **
116791           ** This is a difficult situation to handle. Returning an error
116792           ** code to the caller is insufficient, as even if an error code
116793           ** is returned the transaction on connection db will still be
116794           ** closed and the unlock-notify callbacks on blocked connections
116795           ** will go unissued. This might cause the application to wait
116796           ** indefinitely for an unlock-notify callback that will never 
116797           ** arrive.
116798           **
116799           ** Instead, invoke the unlock-notify callback with the context
116800           ** array already accumulated. We can then clear the array and
116801           ** begin accumulating any further context pointers without 
116802           ** requiring any dynamic allocation. This is sub-optimal because
116803           ** it means that instead of one callback with a large array of
116804           ** context pointers the application will receive two or more
116805           ** callbacks with smaller arrays of context pointers, which will
116806           ** reduce the applications ability to prioritize multiple 
116807           ** connections. But it is the best that can be done under the
116808           ** circumstances.
116809           */
116810           xUnlockNotify(aArg, nArg);
116811           nArg = 0;
116812         }
116813       }
116814       sqlite3EndBenignMalloc();
116815
116816       aArg[nArg++] = p->pUnlockArg;
116817       xUnlockNotify = p->xUnlockNotify;
116818       p->pUnlockConnection = 0;
116819       p->xUnlockNotify = 0;
116820       p->pUnlockArg = 0;
116821     }
116822
116823     /* Step 3. */
116824     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
116825       /* Remove connection p from the blocked connections list. */
116826       *pp = p->pNextBlocked;
116827       p->pNextBlocked = 0;
116828     }else{
116829       pp = &p->pNextBlocked;
116830     }
116831   }
116832
116833   if( nArg!=0 ){
116834     xUnlockNotify(aArg, nArg);
116835   }
116836   sqlite3_free(aDyn);
116837   leaveMutex();         /* Leave STATIC_MASTER mutex */
116838 }
116839
116840 /*
116841 ** This is called when the database connection passed as an argument is 
116842 ** being closed. The connection is removed from the blocked list.
116843 */
116844 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
116845   sqlite3ConnectionUnlocked(db);
116846   enterMutex();
116847   removeFromBlockedList(db);
116848   checkListProperties(db);
116849   leaveMutex();
116850 }
116851 #endif
116852
116853 /************** End of notify.c **********************************************/
116854 /************** Begin file fts3.c ********************************************/
116855 /*
116856 ** 2006 Oct 10
116857 **
116858 ** The author disclaims copyright to this source code.  In place of
116859 ** a legal notice, here is a blessing:
116860 **
116861 **    May you do good and not evil.
116862 **    May you find forgiveness for yourself and forgive others.
116863 **    May you share freely, never taking more than you give.
116864 **
116865 ******************************************************************************
116866 **
116867 ** This is an SQLite module implementing full-text search.
116868 */
116869
116870 /*
116871 ** The code in this file is only compiled if:
116872 **
116873 **     * The FTS3 module is being built as an extension
116874 **       (in which case SQLITE_CORE is not defined), or
116875 **
116876 **     * The FTS3 module is being built into the core of
116877 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
116878 */
116879
116880 /* The full-text index is stored in a series of b+tree (-like)
116881 ** structures called segments which map terms to doclists.  The
116882 ** structures are like b+trees in layout, but are constructed from the
116883 ** bottom up in optimal fashion and are not updatable.  Since trees
116884 ** are built from the bottom up, things will be described from the
116885 ** bottom up.
116886 **
116887 **
116888 **** Varints ****
116889 ** The basic unit of encoding is a variable-length integer called a
116890 ** varint.  We encode variable-length integers in little-endian order
116891 ** using seven bits * per byte as follows:
116892 **
116893 ** KEY:
116894 **         A = 0xxxxxxx    7 bits of data and one flag bit
116895 **         B = 1xxxxxxx    7 bits of data and one flag bit
116896 **
116897 **  7 bits - A
116898 ** 14 bits - BA
116899 ** 21 bits - BBA
116900 ** and so on.
116901 **
116902 ** This is similar in concept to how sqlite encodes "varints" but
116903 ** the encoding is not the same.  SQLite varints are big-endian
116904 ** are are limited to 9 bytes in length whereas FTS3 varints are
116905 ** little-endian and can be up to 10 bytes in length (in theory).
116906 **
116907 ** Example encodings:
116908 **
116909 **     1:    0x01
116910 **   127:    0x7f
116911 **   128:    0x81 0x00
116912 **
116913 **
116914 **** Document lists ****
116915 ** A doclist (document list) holds a docid-sorted list of hits for a
116916 ** given term.  Doclists hold docids and associated token positions.
116917 ** A docid is the unique integer identifier for a single document.
116918 ** A position is the index of a word within the document.  The first 
116919 ** word of the document has a position of 0.
116920 **
116921 ** FTS3 used to optionally store character offsets using a compile-time
116922 ** option.  But that functionality is no longer supported.
116923 **
116924 ** A doclist is stored like this:
116925 **
116926 ** array {
116927 **   varint docid;          (delta from previous doclist)
116928 **   array {                (position list for column 0)
116929 **     varint position;     (2 more than the delta from previous position)
116930 **   }
116931 **   array {
116932 **     varint POS_COLUMN;   (marks start of position list for new column)
116933 **     varint column;       (index of new column)
116934 **     array {
116935 **       varint position;   (2 more than the delta from previous position)
116936 **     }
116937 **   }
116938 **   varint POS_END;        (marks end of positions for this document.
116939 ** }
116940 **
116941 ** Here, array { X } means zero or more occurrences of X, adjacent in
116942 ** memory.  A "position" is an index of a token in the token stream
116943 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
116944 ** in the same logical place as the position element, and act as sentinals
116945 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
116946 ** The positions numbers are not stored literally but rather as two more
116947 ** than the difference from the prior position, or the just the position plus
116948 ** 2 for the first position.  Example:
116949 **
116950 **   label:       A B C D E  F  G H   I  J K
116951 **   value:     123 5 9 1 1 14 35 0 234 72 0
116952 **
116953 ** The 123 value is the first docid.  For column zero in this document
116954 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
116955 ** at D signals the start of a new column; the 1 at E indicates that the
116956 ** new column is column number 1.  There are two positions at 12 and 45
116957 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
116958 ** 234 at I is the delta to next docid (357).  It has one position 70
116959 ** (72-2) and then terminates with the 0 at K.
116960 **
116961 ** A "position-list" is the list of positions for multiple columns for
116962 ** a single docid.  A "column-list" is the set of positions for a single
116963 ** column.  Hence, a position-list consists of one or more column-lists,
116964 ** a document record consists of a docid followed by a position-list and
116965 ** a doclist consists of one or more document records.
116966 **
116967 ** A bare doclist omits the position information, becoming an 
116968 ** array of varint-encoded docids.
116969 **
116970 **** Segment leaf nodes ****
116971 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
116972 ** nodes are written using LeafWriter, and read using LeafReader (to
116973 ** iterate through a single leaf node's data) and LeavesReader (to
116974 ** iterate through a segment's entire leaf layer).  Leaf nodes have
116975 ** the format:
116976 **
116977 ** varint iHeight;             (height from leaf level, always 0)
116978 ** varint nTerm;               (length of first term)
116979 ** char pTerm[nTerm];          (content of first term)
116980 ** varint nDoclist;            (length of term's associated doclist)
116981 ** char pDoclist[nDoclist];    (content of doclist)
116982 ** array {
116983 **                             (further terms are delta-encoded)
116984 **   varint nPrefix;           (length of prefix shared with previous term)
116985 **   varint nSuffix;           (length of unshared suffix)
116986 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
116987 **   varint nDoclist;          (length of term's associated doclist)
116988 **   char pDoclist[nDoclist];  (content of doclist)
116989 ** }
116990 **
116991 ** Here, array { X } means zero or more occurrences of X, adjacent in
116992 ** memory.
116993 **
116994 ** Leaf nodes are broken into blocks which are stored contiguously in
116995 ** the %_segments table in sorted order.  This means that when the end
116996 ** of a node is reached, the next term is in the node with the next
116997 ** greater node id.
116998 **
116999 ** New data is spilled to a new leaf node when the current node
117000 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
117001 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
117002 ** node (a leaf node with a single term and doclist).  The goal of
117003 ** these settings is to pack together groups of small doclists while
117004 ** making it efficient to directly access large doclists.  The
117005 ** assumption is that large doclists represent terms which are more
117006 ** likely to be query targets.
117007 **
117008 ** TODO(shess) It may be useful for blocking decisions to be more
117009 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
117010 ** node rather than splitting into 2k and .5k nodes.  My intuition is
117011 ** that this might extend through 2x or 4x the pagesize.
117012 **
117013 **
117014 **** Segment interior nodes ****
117015 ** Segment interior nodes store blockids for subtree nodes and terms
117016 ** to describe what data is stored by the each subtree.  Interior
117017 ** nodes are written using InteriorWriter, and read using
117018 ** InteriorReader.  InteriorWriters are created as needed when
117019 ** SegmentWriter creates new leaf nodes, or when an interior node
117020 ** itself grows too big and must be split.  The format of interior
117021 ** nodes:
117022 **
117023 ** varint iHeight;           (height from leaf level, always >0)
117024 ** varint iBlockid;          (block id of node's leftmost subtree)
117025 ** optional {
117026 **   varint nTerm;           (length of first term)
117027 **   char pTerm[nTerm];      (content of first term)
117028 **   array {
117029 **                                (further terms are delta-encoded)
117030 **     varint nPrefix;            (length of shared prefix with previous term)
117031 **     varint nSuffix;            (length of unshared suffix)
117032 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
117033 **   }
117034 ** }
117035 **
117036 ** Here, optional { X } means an optional element, while array { X }
117037 ** means zero or more occurrences of X, adjacent in memory.
117038 **
117039 ** An interior node encodes n terms separating n+1 subtrees.  The
117040 ** subtree blocks are contiguous, so only the first subtree's blockid
117041 ** is encoded.  The subtree at iBlockid will contain all terms less
117042 ** than the first term encoded (or all terms if no term is encoded).
117043 ** Otherwise, for terms greater than or equal to pTerm[i] but less
117044 ** than pTerm[i+1], the subtree for that term will be rooted at
117045 ** iBlockid+i.  Interior nodes only store enough term data to
117046 ** distinguish adjacent children (if the rightmost term of the left
117047 ** child is "something", and the leftmost term of the right child is
117048 ** "wicked", only "w" is stored).
117049 **
117050 ** New data is spilled to a new interior node at the same height when
117051 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
117052 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
117053 ** interior nodes and making the tree too skinny.  The interior nodes
117054 ** at a given height are naturally tracked by interior nodes at
117055 ** height+1, and so on.
117056 **
117057 **
117058 **** Segment directory ****
117059 ** The segment directory in table %_segdir stores meta-information for
117060 ** merging and deleting segments, and also the root node of the
117061 ** segment's tree.
117062 **
117063 ** The root node is the top node of the segment's tree after encoding
117064 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
117065 ** This could be either a leaf node or an interior node.  If the top
117066 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
117067 ** and a new root interior node is generated (which should always fit
117068 ** within ROOT_MAX because it only needs space for 2 varints, the
117069 ** height and the blockid of the previous root).
117070 **
117071 ** The meta-information in the segment directory is:
117072 **   level               - segment level (see below)
117073 **   idx                 - index within level
117074 **                       - (level,idx uniquely identify a segment)
117075 **   start_block         - first leaf node
117076 **   leaves_end_block    - last leaf node
117077 **   end_block           - last block (including interior nodes)
117078 **   root                - contents of root node
117079 **
117080 ** If the root node is a leaf node, then start_block,
117081 ** leaves_end_block, and end_block are all 0.
117082 **
117083 **
117084 **** Segment merging ****
117085 ** To amortize update costs, segments are grouped into levels and
117086 ** merged in batches.  Each increase in level represents exponentially
117087 ** more documents.
117088 **
117089 ** New documents (actually, document updates) are tokenized and
117090 ** written individually (using LeafWriter) to a level 0 segment, with
117091 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
117092 ** level 0 segments are merged into a single level 1 segment.  Level 1
117093 ** is populated like level 0, and eventually MERGE_COUNT level 1
117094 ** segments are merged to a single level 2 segment (representing
117095 ** MERGE_COUNT^2 updates), and so on.
117096 **
117097 ** A segment merge traverses all segments at a given level in
117098 ** parallel, performing a straightforward sorted merge.  Since segment
117099 ** leaf nodes are written in to the %_segments table in order, this
117100 ** merge traverses the underlying sqlite disk structures efficiently.
117101 ** After the merge, all segment blocks from the merged level are
117102 ** deleted.
117103 **
117104 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
117105 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
117106 ** very similar performance numbers to 16 on insertion, though they're
117107 ** a tiny bit slower (perhaps due to more overhead in merge-time
117108 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
117109 ** 16, 2 about 66% slower than 16.
117110 **
117111 ** At query time, high MERGE_COUNT increases the number of segments
117112 ** which need to be scanned and merged.  For instance, with 100k docs
117113 ** inserted:
117114 **
117115 **    MERGE_COUNT   segments
117116 **       16           25
117117 **        8           12
117118 **        4           10
117119 **        2            6
117120 **
117121 ** This appears to have only a moderate impact on queries for very
117122 ** frequent terms (which are somewhat dominated by segment merge
117123 ** costs), and infrequent and non-existent terms still seem to be fast
117124 ** even with many segments.
117125 **
117126 ** TODO(shess) That said, it would be nice to have a better query-side
117127 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
117128 ** optimizations to things like doclist merging will swing the sweet
117129 ** spot around.
117130 **
117131 **
117132 **
117133 **** Handling of deletions and updates ****
117134 ** Since we're using a segmented structure, with no docid-oriented
117135 ** index into the term index, we clearly cannot simply update the term
117136 ** index when a document is deleted or updated.  For deletions, we
117137 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
117138 ** we simply write the new doclist.  Segment merges overwrite older
117139 ** data for a particular docid with newer data, so deletes or updates
117140 ** will eventually overtake the earlier data and knock it out.  The
117141 ** query logic likewise merges doclists so that newer data knocks out
117142 ** older data.
117143 */
117144
117145 /************** Include fts3Int.h in the middle of fts3.c ********************/
117146 /************** Begin file fts3Int.h *****************************************/
117147 /*
117148 ** 2009 Nov 12
117149 **
117150 ** The author disclaims copyright to this source code.  In place of
117151 ** a legal notice, here is a blessing:
117152 **
117153 **    May you do good and not evil.
117154 **    May you find forgiveness for yourself and forgive others.
117155 **    May you share freely, never taking more than you give.
117156 **
117157 ******************************************************************************
117158 **
117159 */
117160 #ifndef _FTSINT_H
117161 #define _FTSINT_H
117162
117163 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
117164 # define NDEBUG 1
117165 #endif
117166
117167 /*
117168 ** FTS4 is really an extension for FTS3.  It is enabled using the
117169 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
117170 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
117171 */
117172 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
117173 # define SQLITE_ENABLE_FTS3
117174 #endif
117175
117176 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117177
117178 /* If not building as part of the core, include sqlite3ext.h. */
117179 #ifndef SQLITE_CORE
117180 SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
117181 #endif
117182
117183 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
117184 /************** Begin file fts3_tokenizer.h **********************************/
117185 /*
117186 ** 2006 July 10
117187 **
117188 ** The author disclaims copyright to this source code.
117189 **
117190 *************************************************************************
117191 ** Defines the interface to tokenizers used by fulltext-search.  There
117192 ** are three basic components:
117193 **
117194 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
117195 ** interface functions.  This is essentially the class structure for
117196 ** tokenizers.
117197 **
117198 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
117199 ** including customization information defined at creation time.
117200 **
117201 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
117202 ** tokens from a particular input.
117203 */
117204 #ifndef _FTS3_TOKENIZER_H_
117205 #define _FTS3_TOKENIZER_H_
117206
117207 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
117208 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
117209 ** we will need a way to register the API consistently.
117210 */
117211
117212 /*
117213 ** Structures used by the tokenizer interface. When a new tokenizer
117214 ** implementation is registered, the caller provides a pointer to
117215 ** an sqlite3_tokenizer_module containing pointers to the callback
117216 ** functions that make up an implementation.
117217 **
117218 ** When an fts3 table is created, it passes any arguments passed to
117219 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
117220 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
117221 ** implementation. The xCreate() function in turn returns an 
117222 ** sqlite3_tokenizer structure representing the specific tokenizer to
117223 ** be used for the fts3 table (customized by the tokenizer clause arguments).
117224 **
117225 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
117226 ** method is called. It returns an sqlite3_tokenizer_cursor object
117227 ** that may be used to tokenize a specific input buffer based on
117228 ** the tokenization rules supplied by a specific sqlite3_tokenizer
117229 ** object.
117230 */
117231 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
117232 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
117233 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
117234
117235 struct sqlite3_tokenizer_module {
117236
117237   /*
117238   ** Structure version. Should always be set to 0 or 1.
117239   */
117240   int iVersion;
117241
117242   /*
117243   ** Create a new tokenizer. The values in the argv[] array are the
117244   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
117245   ** TABLE statement that created the fts3 table. For example, if
117246   ** the following SQL is executed:
117247   **
117248   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
117249   **
117250   ** then argc is set to 2, and the argv[] array contains pointers
117251   ** to the strings "arg1" and "arg2".
117252   **
117253   ** This method should return either SQLITE_OK (0), or an SQLite error 
117254   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
117255   ** to point at the newly created tokenizer structure. The generic
117256   ** sqlite3_tokenizer.pModule variable should not be initialized by
117257   ** this callback. The caller will do so.
117258   */
117259   int (*xCreate)(
117260     int argc,                           /* Size of argv array */
117261     const char *const*argv,             /* Tokenizer argument strings */
117262     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
117263   );
117264
117265   /*
117266   ** Destroy an existing tokenizer. The fts3 module calls this method
117267   ** exactly once for each successful call to xCreate().
117268   */
117269   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
117270
117271   /*
117272   ** Create a tokenizer cursor to tokenize an input buffer. The caller
117273   ** is responsible for ensuring that the input buffer remains valid
117274   ** until the cursor is closed (using the xClose() method). 
117275   */
117276   int (*xOpen)(
117277     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
117278     const char *pInput, int nBytes,      /* Input buffer */
117279     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
117280   );
117281
117282   /*
117283   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
117284   ** method exactly once for each successful call to xOpen().
117285   */
117286   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
117287
117288   /*
117289   ** Retrieve the next token from the tokenizer cursor pCursor. This
117290   ** method should either return SQLITE_OK and set the values of the
117291   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
117292   ** the end of the buffer has been reached, or an SQLite error code.
117293   **
117294   ** *ppToken should be set to point at a buffer containing the 
117295   ** normalized version of the token (i.e. after any case-folding and/or
117296   ** stemming has been performed). *pnBytes should be set to the length
117297   ** of this buffer in bytes. The input text that generated the token is
117298   ** identified by the byte offsets returned in *piStartOffset and
117299   ** *piEndOffset. *piStartOffset should be set to the index of the first
117300   ** byte of the token in the input buffer. *piEndOffset should be set
117301   ** to the index of the first byte just past the end of the token in
117302   ** the input buffer.
117303   **
117304   ** The buffer *ppToken is set to point at is managed by the tokenizer
117305   ** implementation. It is only required to be valid until the next call
117306   ** to xNext() or xClose(). 
117307   */
117308   /* TODO(shess) current implementation requires pInput to be
117309   ** nul-terminated.  This should either be fixed, or pInput/nBytes
117310   ** should be converted to zInput.
117311   */
117312   int (*xNext)(
117313     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
117314     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
117315     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
117316     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
117317     int *piPosition      /* OUT: Number of tokens returned before this one */
117318   );
117319
117320   /***********************************************************************
117321   ** Methods below this point are only available if iVersion>=1.
117322   */
117323
117324   /* 
117325   ** Configure the language id of a tokenizer cursor.
117326   */
117327   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
117328 };
117329
117330 struct sqlite3_tokenizer {
117331   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
117332   /* Tokenizer implementations will typically add additional fields */
117333 };
117334
117335 struct sqlite3_tokenizer_cursor {
117336   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
117337   /* Tokenizer implementations will typically add additional fields */
117338 };
117339
117340 int fts3_global_term_cnt(int iTerm, int iCol);
117341 int fts3_term_cnt(int iTerm, int iCol);
117342
117343
117344 #endif /* _FTS3_TOKENIZER_H_ */
117345
117346 /************** End of fts3_tokenizer.h **************************************/
117347 /************** Continuing where we left off in fts3Int.h ********************/
117348 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
117349 /************** Begin file fts3_hash.h ***************************************/
117350 /*
117351 ** 2001 September 22
117352 **
117353 ** The author disclaims copyright to this source code.  In place of
117354 ** a legal notice, here is a blessing:
117355 **
117356 **    May you do good and not evil.
117357 **    May you find forgiveness for yourself and forgive others.
117358 **    May you share freely, never taking more than you give.
117359 **
117360 *************************************************************************
117361 ** This is the header file for the generic hash-table implementation
117362 ** used in SQLite.  We've modified it slightly to serve as a standalone
117363 ** hash table implementation for the full-text indexing module.
117364 **
117365 */
117366 #ifndef _FTS3_HASH_H_
117367 #define _FTS3_HASH_H_
117368
117369 /* Forward declarations of structures. */
117370 typedef struct Fts3Hash Fts3Hash;
117371 typedef struct Fts3HashElem Fts3HashElem;
117372
117373 /* A complete hash table is an instance of the following structure.
117374 ** The internals of this structure are intended to be opaque -- client
117375 ** code should not attempt to access or modify the fields of this structure
117376 ** directly.  Change this structure only by using the routines below.
117377 ** However, many of the "procedures" and "functions" for modifying and
117378 ** accessing this structure are really macros, so we can't really make
117379 ** this structure opaque.
117380 */
117381 struct Fts3Hash {
117382   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
117383   char copyKey;           /* True if copy of key made on insert */
117384   int count;              /* Number of entries in this table */
117385   Fts3HashElem *first;    /* The first element of the array */
117386   int htsize;             /* Number of buckets in the hash table */
117387   struct _fts3ht {        /* the hash table */
117388     int count;               /* Number of entries with this hash */
117389     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
117390   } *ht;
117391 };
117392
117393 /* Each element in the hash table is an instance of the following 
117394 ** structure.  All elements are stored on a single doubly-linked list.
117395 **
117396 ** Again, this structure is intended to be opaque, but it can't really
117397 ** be opaque because it is used by macros.
117398 */
117399 struct Fts3HashElem {
117400   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
117401   void *data;                /* Data associated with this element */
117402   void *pKey; int nKey;      /* Key associated with this element */
117403 };
117404
117405 /*
117406 ** There are 2 different modes of operation for a hash table:
117407 **
117408 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
117409 **                           (including the null-terminator, if any).  Case
117410 **                           is respected in comparisons.
117411 **
117412 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
117413 **                           memcmp() is used to compare keys.
117414 **
117415 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
117416 */
117417 #define FTS3_HASH_STRING    1
117418 #define FTS3_HASH_BINARY    2
117419
117420 /*
117421 ** Access routines.  To delete, insert a NULL pointer.
117422 */
117423 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
117424 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
117425 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
117426 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
117427 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
117428
117429 /*
117430 ** Shorthand for the functions above
117431 */
117432 #define fts3HashInit     sqlite3Fts3HashInit
117433 #define fts3HashInsert   sqlite3Fts3HashInsert
117434 #define fts3HashFind     sqlite3Fts3HashFind
117435 #define fts3HashClear    sqlite3Fts3HashClear
117436 #define fts3HashFindElem sqlite3Fts3HashFindElem
117437
117438 /*
117439 ** Macros for looping over all elements of a hash table.  The idiom is
117440 ** like this:
117441 **
117442 **   Fts3Hash h;
117443 **   Fts3HashElem *p;
117444 **   ...
117445 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
117446 **     SomeStructure *pData = fts3HashData(p);
117447 **     // do something with pData
117448 **   }
117449 */
117450 #define fts3HashFirst(H)  ((H)->first)
117451 #define fts3HashNext(E)   ((E)->next)
117452 #define fts3HashData(E)   ((E)->data)
117453 #define fts3HashKey(E)    ((E)->pKey)
117454 #define fts3HashKeysize(E) ((E)->nKey)
117455
117456 /*
117457 ** Number of entries in a hash table
117458 */
117459 #define fts3HashCount(H)  ((H)->count)
117460
117461 #endif /* _FTS3_HASH_H_ */
117462
117463 /************** End of fts3_hash.h *******************************************/
117464 /************** Continuing where we left off in fts3Int.h ********************/
117465
117466 /*
117467 ** This constant controls how often segments are merged. Once there are
117468 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
117469 ** segment of level N+1.
117470 */
117471 #define FTS3_MERGE_COUNT 16
117472
117473 /*
117474 ** This is the maximum amount of data (in bytes) to store in the 
117475 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
117476 ** populated as documents are inserted/updated/deleted in a transaction
117477 ** and used to create a new segment when the transaction is committed.
117478 ** However if this limit is reached midway through a transaction, a new 
117479 ** segment is created and the hash table cleared immediately.
117480 */
117481 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
117482
117483 /*
117484 ** Macro to return the number of elements in an array. SQLite has a
117485 ** similar macro called ArraySize(). Use a different name to avoid
117486 ** a collision when building an amalgamation with built-in FTS3.
117487 */
117488 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
117489
117490
117491 #ifndef MIN
117492 # define MIN(x,y) ((x)<(y)?(x):(y))
117493 #endif
117494 #ifndef MAX
117495 # define MAX(x,y) ((x)>(y)?(x):(y))
117496 #endif
117497
117498 /*
117499 ** Maximum length of a varint encoded integer. The varint format is different
117500 ** from that used by SQLite, so the maximum length is 10, not 9.
117501 */
117502 #define FTS3_VARINT_MAX 10
117503
117504 /*
117505 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
117506 ** in the document set and zero or more prefix indexes. All indexes are stored
117507 ** as one or more b+-trees in the %_segments and %_segdir tables. 
117508 **
117509 ** It is possible to determine which index a b+-tree belongs to based on the
117510 ** value stored in the "%_segdir.level" column. Given this value L, the index
117511 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
117512 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
117513 ** between 1024 and 2047 to index 1, and so on.
117514 **
117515 ** It is considered impossible for an index to use more than 1024 levels. In 
117516 ** theory though this may happen, but only after at least 
117517 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
117518 */
117519 #define FTS3_SEGDIR_MAXLEVEL      1024
117520 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
117521
117522 /*
117523 ** The testcase() macro is only used by the amalgamation.  If undefined,
117524 ** make it a no-op.
117525 */
117526 #ifndef testcase
117527 # define testcase(X)
117528 #endif
117529
117530 /*
117531 ** Terminator values for position-lists and column-lists.
117532 */
117533 #define POS_COLUMN  (1)     /* Column-list terminator */
117534 #define POS_END     (0)     /* Position-list terminator */ 
117535
117536 /*
117537 ** This section provides definitions to allow the
117538 ** FTS3 extension to be compiled outside of the 
117539 ** amalgamation.
117540 */
117541 #ifndef SQLITE_AMALGAMATION
117542 /*
117543 ** Macros indicating that conditional expressions are always true or
117544 ** false.
117545 */
117546 #ifdef SQLITE_COVERAGE_TEST
117547 # define ALWAYS(x) (1)
117548 # define NEVER(X)  (0)
117549 #else
117550 # define ALWAYS(x) (x)
117551 # define NEVER(x)  (x)
117552 #endif
117553
117554 /*
117555 ** Internal types used by SQLite.
117556 */
117557 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
117558 typedef short int i16;            /* 2-byte (or larger) signed integer */
117559 typedef unsigned int u32;         /* 4-byte unsigned integer */
117560 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
117561 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
117562
117563 /*
117564 ** Macro used to suppress compiler warnings for unused parameters.
117565 */
117566 #define UNUSED_PARAMETER(x) (void)(x)
117567
117568 /*
117569 ** Activate assert() only if SQLITE_TEST is enabled.
117570 */
117571 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
117572 # define NDEBUG 1
117573 #endif
117574
117575 /*
117576 ** The TESTONLY macro is used to enclose variable declarations or
117577 ** other bits of code that are needed to support the arguments
117578 ** within testcase() and assert() macros.
117579 */
117580 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
117581 # define TESTONLY(X)  X
117582 #else
117583 # define TESTONLY(X)
117584 #endif
117585
117586 #endif /* SQLITE_AMALGAMATION */
117587
117588 #ifdef SQLITE_DEBUG
117589 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
117590 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
117591 #else
117592 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
117593 #endif
117594
117595 typedef struct Fts3Table Fts3Table;
117596 typedef struct Fts3Cursor Fts3Cursor;
117597 typedef struct Fts3Expr Fts3Expr;
117598 typedef struct Fts3Phrase Fts3Phrase;
117599 typedef struct Fts3PhraseToken Fts3PhraseToken;
117600
117601 typedef struct Fts3Doclist Fts3Doclist;
117602 typedef struct Fts3SegFilter Fts3SegFilter;
117603 typedef struct Fts3DeferredToken Fts3DeferredToken;
117604 typedef struct Fts3SegReader Fts3SegReader;
117605 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
117606
117607 /*
117608 ** A connection to a fulltext index is an instance of the following
117609 ** structure. The xCreate and xConnect methods create an instance
117610 ** of this structure and xDestroy and xDisconnect free that instance.
117611 ** All other methods receive a pointer to the structure as one of their
117612 ** arguments.
117613 */
117614 struct Fts3Table {
117615   sqlite3_vtab base;              /* Base class used by SQLite core */
117616   sqlite3 *db;                    /* The database connection */
117617   const char *zDb;                /* logical database name */
117618   const char *zName;              /* virtual table name */
117619   int nColumn;                    /* number of named columns in virtual table */
117620   char **azColumn;                /* column names.  malloced */
117621   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
117622   char *zContentTbl;              /* content=xxx option, or NULL */
117623   char *zLanguageid;              /* languageid=xxx option, or NULL */
117624   u8 bAutoincrmerge;              /* True if automerge=1 */
117625   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
117626
117627   /* Precompiled statements used by the implementation. Each of these 
117628   ** statements is run and reset within a single virtual table API call. 
117629   */
117630   sqlite3_stmt *aStmt[37];
117631
117632   char *zReadExprlist;
117633   char *zWriteExprlist;
117634
117635   int nNodeSize;                  /* Soft limit for node size */
117636   u8 bFts4;                       /* True for FTS4, false for FTS3 */
117637   u8 bHasStat;                    /* True if %_stat table exists */
117638   u8 bHasDocsize;                 /* True if %_docsize table exists */
117639   u8 bDescIdx;                    /* True if doclists are in reverse order */
117640   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
117641   int nPgsz;                      /* Page size for host database */
117642   char *zSegmentsTbl;             /* Name of %_segments table */
117643   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
117644
117645   /* 
117646   ** The following array of hash tables is used to buffer pending index 
117647   ** updates during transactions. All pending updates buffered at any one
117648   ** time must share a common language-id (see the FTS4 langid= feature).
117649   ** The current language id is stored in variable iPrevLangid.
117650   **
117651   ** A single FTS4 table may have multiple full-text indexes. For each index
117652   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
117653   ** terms that appear in the document set. Each subsequent index in aIndex[]
117654   ** is an index of prefixes of a specific length.
117655   **
117656   ** Variable nPendingData contains an estimate the memory consumed by the 
117657   ** pending data structures, including hash table overhead, but not including
117658   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
117659   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most 
117660   ** recently inserted record.
117661   */
117662   int nIndex;                     /* Size of aIndex[] */
117663   struct Fts3Index {
117664     int nPrefix;                  /* Prefix length (0 for main terms index) */
117665     Fts3Hash hPending;            /* Pending terms table for this index */
117666   } *aIndex;
117667   int nMaxPendingData;            /* Max pending data before flush to disk */
117668   int nPendingData;               /* Current bytes of pending data */
117669   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
117670   int iPrevLangid;                /* Langid of recently inserted document */
117671
117672 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
117673   /* State variables used for validating that the transaction control
117674   ** methods of the virtual table are called at appropriate times.  These
117675   ** values do not contribute to FTS functionality; they are used for
117676   ** verifying the operation of the SQLite core.
117677   */
117678   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
117679   int mxSavepoint;       /* Largest valid xSavepoint integer */
117680 #endif
117681 };
117682
117683 /*
117684 ** When the core wants to read from the virtual table, it creates a
117685 ** virtual table cursor (an instance of the following structure) using
117686 ** the xOpen method. Cursors are destroyed using the xClose method.
117687 */
117688 struct Fts3Cursor {
117689   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
117690   i16 eSearch;                    /* Search strategy (see below) */
117691   u8 isEof;                       /* True if at End Of Results */
117692   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
117693   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
117694   Fts3Expr *pExpr;                /* Parsed MATCH query string */
117695   int iLangid;                    /* Language being queried for */
117696   int nPhrase;                    /* Number of matchable phrases in query */
117697   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
117698   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
117699   char *pNextId;                  /* Pointer into the body of aDoclist */
117700   char *aDoclist;                 /* List of docids for full-text queries */
117701   int nDoclist;                   /* Size of buffer at aDoclist */
117702   u8 bDesc;                       /* True to sort in descending order */
117703   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
117704   int nRowAvg;                    /* Average size of database rows, in pages */
117705   sqlite3_int64 nDoc;             /* Documents in table */
117706
117707   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
117708   u32 *aMatchinfo;                /* Information about most recent match */
117709   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
117710   char *zMatchinfo;               /* Matchinfo specification */
117711 };
117712
117713 #define FTS3_EVAL_FILTER    0
117714 #define FTS3_EVAL_NEXT      1
117715 #define FTS3_EVAL_MATCHINFO 2
117716
117717 /*
117718 ** The Fts3Cursor.eSearch member is always set to one of the following.
117719 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
117720 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
117721 ** of the column to be searched.  For example, in
117722 **
117723 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
117724 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
117725 ** 
117726 ** Because the LHS of the MATCH operator is 2nd column "b",
117727 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
117728 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
117729 ** indicating that all columns should be searched,
117730 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
117731 */
117732 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
117733 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
117734 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
117735
117736
117737 struct Fts3Doclist {
117738   char *aAll;                    /* Array containing doclist (or NULL) */
117739   int nAll;                      /* Size of a[] in bytes */
117740   char *pNextDocid;              /* Pointer to next docid */
117741
117742   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
117743   int bFreeList;                 /* True if pList should be sqlite3_free()d */
117744   char *pList;                   /* Pointer to position list following iDocid */
117745   int nList;                     /* Length of position list */
117746 };
117747
117748 /*
117749 ** A "phrase" is a sequence of one or more tokens that must match in
117750 ** sequence.  A single token is the base case and the most common case.
117751 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
117752 ** nToken will be the number of tokens in the string.
117753 */
117754 struct Fts3PhraseToken {
117755   char *z;                        /* Text of the token */
117756   int n;                          /* Number of bytes in buffer z */
117757   int isPrefix;                   /* True if token ends with a "*" character */
117758   int bFirst;                     /* True if token must appear at position 0 */
117759
117760   /* Variables above this point are populated when the expression is
117761   ** parsed (by code in fts3_expr.c). Below this point the variables are
117762   ** used when evaluating the expression. */
117763   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
117764   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
117765 };
117766
117767 struct Fts3Phrase {
117768   /* Cache of doclist for this phrase. */
117769   Fts3Doclist doclist;
117770   int bIncr;                 /* True if doclist is loaded incrementally */
117771   int iDoclistToken;
117772
117773   /* Variables below this point are populated by fts3_expr.c when parsing 
117774   ** a MATCH expression. Everything above is part of the evaluation phase. 
117775   */
117776   int nToken;                /* Number of tokens in the phrase */
117777   int iColumn;               /* Index of column this phrase must match */
117778   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
117779 };
117780
117781 /*
117782 ** A tree of these objects forms the RHS of a MATCH operator.
117783 **
117784 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
117785 ** points to a malloced buffer, size nDoclist bytes, containing the results 
117786 ** of this phrase query in FTS3 doclist format. As usual, the initial 
117787 ** "Length" field found in doclists stored on disk is omitted from this 
117788 ** buffer.
117789 **
117790 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
117791 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
117792 ** where nCol is the number of columns in the queried FTS table. The array
117793 ** is populated as follows:
117794 **
117795 **   aMI[iCol*3 + 0] = Undefined
117796 **   aMI[iCol*3 + 1] = Number of occurrences
117797 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
117798 **
117799 ** The aMI array is allocated using sqlite3_malloc(). It should be freed 
117800 ** when the expression node is.
117801 */
117802 struct Fts3Expr {
117803   int eType;                 /* One of the FTSQUERY_XXX values defined below */
117804   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
117805   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
117806   Fts3Expr *pLeft;           /* Left operand */
117807   Fts3Expr *pRight;          /* Right operand */
117808   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
117809
117810   /* The following are used by the fts3_eval.c module. */
117811   sqlite3_int64 iDocid;      /* Current docid */
117812   u8 bEof;                   /* True this expression is at EOF already */
117813   u8 bStart;                 /* True if iDocid is valid */
117814   u8 bDeferred;              /* True if this expression is entirely deferred */
117815
117816   u32 *aMI;
117817 };
117818
117819 /*
117820 ** Candidate values for Fts3Query.eType. Note that the order of the first
117821 ** four values is in order of precedence when parsing expressions. For 
117822 ** example, the following:
117823 **
117824 **   "a OR b AND c NOT d NEAR e"
117825 **
117826 ** is equivalent to:
117827 **
117828 **   "a OR (b AND (c NOT (d NEAR e)))"
117829 */
117830 #define FTSQUERY_NEAR   1
117831 #define FTSQUERY_NOT    2
117832 #define FTSQUERY_AND    3
117833 #define FTSQUERY_OR     4
117834 #define FTSQUERY_PHRASE 5
117835
117836
117837 /* fts3_write.c */
117838 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
117839 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
117840 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
117841 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
117842 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
117843   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
117844 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
117845   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
117846 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
117847 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
117848 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
117849 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
117850
117851 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
117852 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
117853
117854 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
117855 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
117856 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
117857 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
117858 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
117859 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
117860 #else
117861 # define sqlite3Fts3FreeDeferredTokens(x)
117862 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
117863 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
117864 # define sqlite3Fts3FreeDeferredDoclists(x)
117865 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
117866 #endif
117867
117868 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
117869 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
117870
117871 /* Special values interpreted by sqlite3SegReaderCursor() */
117872 #define FTS3_SEGCURSOR_PENDING        -1
117873 #define FTS3_SEGCURSOR_ALL            -2
117874
117875 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
117876 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
117877 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
117878
117879 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, 
117880     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
117881
117882 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
117883 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
117884 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
117885 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
117886 #define FTS3_SEGMENT_PREFIX        0x00000008
117887 #define FTS3_SEGMENT_SCAN          0x00000010
117888 #define FTS3_SEGMENT_FIRST         0x00000020
117889
117890 /* Type passed as 4th argument to SegmentReaderIterate() */
117891 struct Fts3SegFilter {
117892   const char *zTerm;
117893   int nTerm;
117894   int iCol;
117895   int flags;
117896 };
117897
117898 struct Fts3MultiSegReader {
117899   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
117900   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
117901   int nSegment;                   /* Size of apSegment array */
117902   int nAdvance;                   /* How many seg-readers to advance */
117903   Fts3SegFilter *pFilter;         /* Pointer to filter object */
117904   char *aBuffer;                  /* Buffer to merge doclists in */
117905   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
117906
117907   int iColFilter;                 /* If >=0, filter for this column */
117908   int bRestart;
117909
117910   /* Used by fts3.c only. */
117911   int nCost;                      /* Cost of running iterator */
117912   int bLookup;                    /* True if a lookup of a single entry. */
117913
117914   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
117915   char *zTerm;                    /* Pointer to term buffer */
117916   int nTerm;                      /* Size of zTerm in bytes */
117917   char *aDoclist;                 /* Pointer to doclist buffer */
117918   int nDoclist;                   /* Size of aDoclist[] in bytes */
117919 };
117920
117921 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
117922
117923 /* fts3.c */
117924 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
117925 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
117926 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
117927 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
117928 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
117929 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
117930 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
117931 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
117932 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
117933
117934 /* fts3_tokenizer.c */
117935 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
117936 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
117937 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
117938     sqlite3_tokenizer **, char **
117939 );
117940 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
117941
117942 /* fts3_snippet.c */
117943 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
117944 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
117945   const char *, const char *, int, int
117946 );
117947 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
117948
117949 /* fts3_expr.c */
117950 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
117951   char **, int, int, int, const char *, int, Fts3Expr **
117952 );
117953 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
117954 #ifdef SQLITE_TEST
117955 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
117956 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
117957 #endif
117958
117959 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
117960   sqlite3_tokenizer_cursor **
117961 );
117962
117963 /* fts3_aux.c */
117964 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
117965
117966 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
117967
117968 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
117969     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
117970 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
117971     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
117972 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); 
117973 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
117974 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
117975
117976 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
117977 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
117978 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
117979 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
117980 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
117981 #endif
117982
117983 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
117984 #endif /* _FTSINT_H */
117985
117986 /************** End of fts3Int.h *********************************************/
117987 /************** Continuing where we left off in fts3.c ***********************/
117988 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117989
117990 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
117991 # define SQLITE_CORE 1
117992 #endif
117993
117994 /* #include <assert.h> */
117995 /* #include <stdlib.h> */
117996 /* #include <stddef.h> */
117997 /* #include <stdio.h> */
117998 /* #include <string.h> */
117999 /* #include <stdarg.h> */
118000
118001 #ifndef SQLITE_CORE 
118002   SQLITE_EXTENSION_INIT1
118003 #endif
118004
118005 static int fts3EvalNext(Fts3Cursor *pCsr);
118006 static int fts3EvalStart(Fts3Cursor *pCsr);
118007 static int fts3TermSegReaderCursor(
118008     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
118009
118010 /* 
118011 ** Write a 64-bit variable-length integer to memory starting at p[0].
118012 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
118013 ** The number of bytes written is returned.
118014 */
118015 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
118016   unsigned char *q = (unsigned char *) p;
118017   sqlite_uint64 vu = v;
118018   do{
118019     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
118020     vu >>= 7;
118021   }while( vu!=0 );
118022   q[-1] &= 0x7f;  /* turn off high bit in final byte */
118023   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
118024   return (int) (q - (unsigned char *)p);
118025 }
118026
118027 /* 
118028 ** Read a 64-bit variable-length integer from memory starting at p[0].
118029 ** Return the number of bytes read, or 0 on error.
118030 ** The value is stored in *v.
118031 */
118032 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
118033   const unsigned char *q = (const unsigned char *) p;
118034   sqlite_uint64 x = 0, y = 1;
118035   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
118036     x += y * (*q++ & 0x7f);
118037     y <<= 7;
118038   }
118039   x += y * (*q++);
118040   *v = (sqlite_int64) x;
118041   return (int) (q - (unsigned char *)p);
118042 }
118043
118044 /*
118045 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
118046 ** 32-bit integer before it is returned.
118047 */
118048 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
118049  sqlite_int64 i;
118050  int ret = sqlite3Fts3GetVarint(p, &i);
118051  *pi = (int) i;
118052  return ret;
118053 }
118054
118055 /*
118056 ** Return the number of bytes required to encode v as a varint
118057 */
118058 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
118059   int i = 0;
118060   do{
118061     i++;
118062     v >>= 7;
118063   }while( v!=0 );
118064   return i;
118065 }
118066
118067 /*
118068 ** Convert an SQL-style quoted string into a normal string by removing
118069 ** the quote characters.  The conversion is done in-place.  If the
118070 ** input does not begin with a quote character, then this routine
118071 ** is a no-op.
118072 **
118073 ** Examples:
118074 **
118075 **     "abc"   becomes   abc
118076 **     'xyz'   becomes   xyz
118077 **     [pqr]   becomes   pqr
118078 **     `mno`   becomes   mno
118079 **
118080 */
118081 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
118082   char quote;                     /* Quote character (if any ) */
118083
118084   quote = z[0];
118085   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
118086     int iIn = 1;                  /* Index of next byte to read from input */
118087     int iOut = 0;                 /* Index of next byte to write to output */
118088
118089     /* If the first byte was a '[', then the close-quote character is a ']' */
118090     if( quote=='[' ) quote = ']';  
118091
118092     while( ALWAYS(z[iIn]) ){
118093       if( z[iIn]==quote ){
118094         if( z[iIn+1]!=quote ) break;
118095         z[iOut++] = quote;
118096         iIn += 2;
118097       }else{
118098         z[iOut++] = z[iIn++];
118099       }
118100     }
118101     z[iOut] = '\0';
118102   }
118103 }
118104
118105 /*
118106 ** Read a single varint from the doclist at *pp and advance *pp to point
118107 ** to the first byte past the end of the varint.  Add the value of the varint
118108 ** to *pVal.
118109 */
118110 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
118111   sqlite3_int64 iVal;
118112   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
118113   *pVal += iVal;
118114 }
118115
118116 /*
118117 ** When this function is called, *pp points to the first byte following a
118118 ** varint that is part of a doclist (or position-list, or any other list
118119 ** of varints). This function moves *pp to point to the start of that varint,
118120 ** and sets *pVal by the varint value.
118121 **
118122 ** Argument pStart points to the first byte of the doclist that the
118123 ** varint is part of.
118124 */
118125 static void fts3GetReverseVarint(
118126   char **pp, 
118127   char *pStart, 
118128   sqlite3_int64 *pVal
118129 ){
118130   sqlite3_int64 iVal;
118131   char *p;
118132
118133   /* Pointer p now points at the first byte past the varint we are 
118134   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
118135   ** clear on character p[-1]. */
118136   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
118137   p++;
118138   *pp = p;
118139
118140   sqlite3Fts3GetVarint(p, &iVal);
118141   *pVal = iVal;
118142 }
118143
118144 /*
118145 ** The xDisconnect() virtual table method.
118146 */
118147 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
118148   Fts3Table *p = (Fts3Table *)pVtab;
118149   int i;
118150
118151   assert( p->nPendingData==0 );
118152   assert( p->pSegments==0 );
118153
118154   /* Free any prepared statements held */
118155   for(i=0; i<SizeofArray(p->aStmt); i++){
118156     sqlite3_finalize(p->aStmt[i]);
118157   }
118158   sqlite3_free(p->zSegmentsTbl);
118159   sqlite3_free(p->zReadExprlist);
118160   sqlite3_free(p->zWriteExprlist);
118161   sqlite3_free(p->zContentTbl);
118162   sqlite3_free(p->zLanguageid);
118163
118164   /* Invoke the tokenizer destructor to free the tokenizer. */
118165   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
118166
118167   sqlite3_free(p);
118168   return SQLITE_OK;
118169 }
118170
118171 /*
118172 ** Construct one or more SQL statements from the format string given
118173 ** and then evaluate those statements. The success code is written
118174 ** into *pRc.
118175 **
118176 ** If *pRc is initially non-zero then this routine is a no-op.
118177 */
118178 static void fts3DbExec(
118179   int *pRc,              /* Success code */
118180   sqlite3 *db,           /* Database in which to run SQL */
118181   const char *zFormat,   /* Format string for SQL */
118182   ...                    /* Arguments to the format string */
118183 ){
118184   va_list ap;
118185   char *zSql;
118186   if( *pRc ) return;
118187   va_start(ap, zFormat);
118188   zSql = sqlite3_vmprintf(zFormat, ap);
118189   va_end(ap);
118190   if( zSql==0 ){
118191     *pRc = SQLITE_NOMEM;
118192   }else{
118193     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
118194     sqlite3_free(zSql);
118195   }
118196 }
118197
118198 /*
118199 ** The xDestroy() virtual table method.
118200 */
118201 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
118202   Fts3Table *p = (Fts3Table *)pVtab;
118203   int rc = SQLITE_OK;              /* Return code */
118204   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
118205   sqlite3 *db = p->db;             /* Database handle */
118206
118207   /* Drop the shadow tables */
118208   if( p->zContentTbl==0 ){
118209     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
118210   }
118211   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
118212   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
118213   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
118214   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
118215
118216   /* If everything has worked, invoke fts3DisconnectMethod() to free the
118217   ** memory associated with the Fts3Table structure and return SQLITE_OK.
118218   ** Otherwise, return an SQLite error code.
118219   */
118220   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
118221 }
118222
118223
118224 /*
118225 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
118226 ** passed as the first argument. This is done as part of the xConnect()
118227 ** and xCreate() methods.
118228 **
118229 ** If *pRc is non-zero when this function is called, it is a no-op. 
118230 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
118231 ** before returning.
118232 */
118233 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
118234   if( *pRc==SQLITE_OK ){
118235     int i;                        /* Iterator variable */
118236     int rc;                       /* Return code */
118237     char *zSql;                   /* SQL statement passed to declare_vtab() */
118238     char *zCols;                  /* List of user defined columns */
118239     const char *zLanguageid;
118240
118241     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
118242     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
118243
118244     /* Create a list of user columns for the virtual table */
118245     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
118246     for(i=1; zCols && i<p->nColumn; i++){
118247       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
118248     }
118249
118250     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
118251     zSql = sqlite3_mprintf(
118252         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", 
118253         zCols, p->zName, zLanguageid
118254     );
118255     if( !zCols || !zSql ){
118256       rc = SQLITE_NOMEM;
118257     }else{
118258       rc = sqlite3_declare_vtab(p->db, zSql);
118259     }
118260
118261     sqlite3_free(zSql);
118262     sqlite3_free(zCols);
118263     *pRc = rc;
118264   }
118265 }
118266
118267 /*
118268 ** Create the %_stat table if it does not already exist.
118269 */
118270 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
118271   fts3DbExec(pRc, p->db, 
118272       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
118273           "(id INTEGER PRIMARY KEY, value BLOB);",
118274       p->zDb, p->zName
118275   );
118276   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
118277 }
118278
118279 /*
118280 ** Create the backing store tables (%_content, %_segments and %_segdir)
118281 ** required by the FTS3 table passed as the only argument. This is done
118282 ** as part of the vtab xCreate() method.
118283 **
118284 ** If the p->bHasDocsize boolean is true (indicating that this is an
118285 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
118286 ** %_stat tables required by FTS4.
118287 */
118288 static int fts3CreateTables(Fts3Table *p){
118289   int rc = SQLITE_OK;             /* Return code */
118290   int i;                          /* Iterator variable */
118291   sqlite3 *db = p->db;            /* The database connection */
118292
118293   if( p->zContentTbl==0 ){
118294     const char *zLanguageid = p->zLanguageid;
118295     char *zContentCols;           /* Columns of %_content table */
118296
118297     /* Create a list of user columns for the content table */
118298     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
118299     for(i=0; zContentCols && i<p->nColumn; i++){
118300       char *z = p->azColumn[i];
118301       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
118302     }
118303     if( zLanguageid && zContentCols ){
118304       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
118305     }
118306     if( zContentCols==0 ) rc = SQLITE_NOMEM;
118307   
118308     /* Create the content table */
118309     fts3DbExec(&rc, db, 
118310        "CREATE TABLE %Q.'%q_content'(%s)",
118311        p->zDb, p->zName, zContentCols
118312     );
118313     sqlite3_free(zContentCols);
118314   }
118315
118316   /* Create other tables */
118317   fts3DbExec(&rc, db, 
118318       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
118319       p->zDb, p->zName
118320   );
118321   fts3DbExec(&rc, db, 
118322       "CREATE TABLE %Q.'%q_segdir'("
118323         "level INTEGER,"
118324         "idx INTEGER,"
118325         "start_block INTEGER,"
118326         "leaves_end_block INTEGER,"
118327         "end_block INTEGER,"
118328         "root BLOB,"
118329         "PRIMARY KEY(level, idx)"
118330       ");",
118331       p->zDb, p->zName
118332   );
118333   if( p->bHasDocsize ){
118334     fts3DbExec(&rc, db, 
118335         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
118336         p->zDb, p->zName
118337     );
118338   }
118339   assert( p->bHasStat==p->bFts4 );
118340   if( p->bHasStat ){
118341     sqlite3Fts3CreateStatTable(&rc, p);
118342   }
118343   return rc;
118344 }
118345
118346 /*
118347 ** Store the current database page-size in bytes in p->nPgsz.
118348 **
118349 ** If *pRc is non-zero when this function is called, it is a no-op. 
118350 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
118351 ** before returning.
118352 */
118353 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
118354   if( *pRc==SQLITE_OK ){
118355     int rc;                       /* Return code */
118356     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
118357     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
118358   
118359     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
118360     if( !zSql ){
118361       rc = SQLITE_NOMEM;
118362     }else{
118363       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
118364       if( rc==SQLITE_OK ){
118365         sqlite3_step(pStmt);
118366         p->nPgsz = sqlite3_column_int(pStmt, 0);
118367         rc = sqlite3_finalize(pStmt);
118368       }else if( rc==SQLITE_AUTH ){
118369         p->nPgsz = 1024;
118370         rc = SQLITE_OK;
118371       }
118372     }
118373     assert( p->nPgsz>0 || rc!=SQLITE_OK );
118374     sqlite3_free(zSql);
118375     *pRc = rc;
118376   }
118377 }
118378
118379 /*
118380 ** "Special" FTS4 arguments are column specifications of the following form:
118381 **
118382 **   <key> = <value>
118383 **
118384 ** There may not be whitespace surrounding the "=" character. The <value> 
118385 ** term may be quoted, but the <key> may not.
118386 */
118387 static int fts3IsSpecialColumn(
118388   const char *z, 
118389   int *pnKey,
118390   char **pzValue
118391 ){
118392   char *zValue;
118393   const char *zCsr = z;
118394
118395   while( *zCsr!='=' ){
118396     if( *zCsr=='\0' ) return 0;
118397     zCsr++;
118398   }
118399
118400   *pnKey = (int)(zCsr-z);
118401   zValue = sqlite3_mprintf("%s", &zCsr[1]);
118402   if( zValue ){
118403     sqlite3Fts3Dequote(zValue);
118404   }
118405   *pzValue = zValue;
118406   return 1;
118407 }
118408
118409 /*
118410 ** Append the output of a printf() style formatting to an existing string.
118411 */
118412 static void fts3Appendf(
118413   int *pRc,                       /* IN/OUT: Error code */
118414   char **pz,                      /* IN/OUT: Pointer to string buffer */
118415   const char *zFormat,            /* Printf format string to append */
118416   ...                             /* Arguments for printf format string */
118417 ){
118418   if( *pRc==SQLITE_OK ){
118419     va_list ap;
118420     char *z;
118421     va_start(ap, zFormat);
118422     z = sqlite3_vmprintf(zFormat, ap);
118423     va_end(ap);
118424     if( z && *pz ){
118425       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
118426       sqlite3_free(z);
118427       z = z2;
118428     }
118429     if( z==0 ) *pRc = SQLITE_NOMEM;
118430     sqlite3_free(*pz);
118431     *pz = z;
118432   }
118433 }
118434
118435 /*
118436 ** Return a copy of input string zInput enclosed in double-quotes (") and
118437 ** with all double quote characters escaped. For example:
118438 **
118439 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
118440 **
118441 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
118442 ** is the callers responsibility to call sqlite3_free() to release this
118443 ** memory.
118444 */
118445 static char *fts3QuoteId(char const *zInput){
118446   int nRet;
118447   char *zRet;
118448   nRet = 2 + (int)strlen(zInput)*2 + 1;
118449   zRet = sqlite3_malloc(nRet);
118450   if( zRet ){
118451     int i;
118452     char *z = zRet;
118453     *(z++) = '"';
118454     for(i=0; zInput[i]; i++){
118455       if( zInput[i]=='"' ) *(z++) = '"';
118456       *(z++) = zInput[i];
118457     }
118458     *(z++) = '"';
118459     *(z++) = '\0';
118460   }
118461   return zRet;
118462 }
118463
118464 /*
118465 ** Return a list of comma separated SQL expressions and a FROM clause that 
118466 ** could be used in a SELECT statement such as the following:
118467 **
118468 **     SELECT <list of expressions> FROM %_content AS x ...
118469 **
118470 ** to return the docid, followed by each column of text data in order
118471 ** from left to write. If parameter zFunc is not NULL, then instead of
118472 ** being returned directly each column of text data is passed to an SQL
118473 ** function named zFunc first. For example, if zFunc is "unzip" and the
118474 ** table has the three user-defined columns "a", "b", and "c", the following
118475 ** string is returned:
118476 **
118477 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
118478 **
118479 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
118480 ** is the responsibility of the caller to eventually free it.
118481 **
118482 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
118483 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
118484 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
118485 ** no error occurs, *pRc is left unmodified.
118486 */
118487 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
118488   char *zRet = 0;
118489   char *zFree = 0;
118490   char *zFunction;
118491   int i;
118492
118493   if( p->zContentTbl==0 ){
118494     if( !zFunc ){
118495       zFunction = "";
118496     }else{
118497       zFree = zFunction = fts3QuoteId(zFunc);
118498     }
118499     fts3Appendf(pRc, &zRet, "docid");
118500     for(i=0; i<p->nColumn; i++){
118501       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
118502     }
118503     if( p->zLanguageid ){
118504       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
118505     }
118506     sqlite3_free(zFree);
118507   }else{
118508     fts3Appendf(pRc, &zRet, "rowid");
118509     for(i=0; i<p->nColumn; i++){
118510       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
118511     }
118512     if( p->zLanguageid ){
118513       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
118514     }
118515   }
118516   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", 
118517       p->zDb,
118518       (p->zContentTbl ? p->zContentTbl : p->zName),
118519       (p->zContentTbl ? "" : "_content")
118520   );
118521   return zRet;
118522 }
118523
118524 /*
118525 ** Return a list of N comma separated question marks, where N is the number
118526 ** of columns in the %_content table (one for the docid plus one for each
118527 ** user-defined text column).
118528 **
118529 ** If argument zFunc is not NULL, then all but the first question mark
118530 ** is preceded by zFunc and an open bracket, and followed by a closed
118531 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
118532 ** user-defined text columns, the following string is returned:
118533 **
118534 **     "?, zip(?), zip(?), zip(?)"
118535 **
118536 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
118537 ** is the responsibility of the caller to eventually free it.
118538 **
118539 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
118540 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
118541 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
118542 ** no error occurs, *pRc is left unmodified.
118543 */
118544 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
118545   char *zRet = 0;
118546   char *zFree = 0;
118547   char *zFunction;
118548   int i;
118549
118550   if( !zFunc ){
118551     zFunction = "";
118552   }else{
118553     zFree = zFunction = fts3QuoteId(zFunc);
118554   }
118555   fts3Appendf(pRc, &zRet, "?");
118556   for(i=0; i<p->nColumn; i++){
118557     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
118558   }
118559   if( p->zLanguageid ){
118560     fts3Appendf(pRc, &zRet, ", ?");
118561   }
118562   sqlite3_free(zFree);
118563   return zRet;
118564 }
118565
118566 /*
118567 ** This function interprets the string at (*pp) as a non-negative integer
118568 ** value. It reads the integer and sets *pnOut to the value read, then 
118569 ** sets *pp to point to the byte immediately following the last byte of
118570 ** the integer value.
118571 **
118572 ** Only decimal digits ('0'..'9') may be part of an integer value. 
118573 **
118574 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
118575 ** the output value undefined. Otherwise SQLITE_OK is returned.
118576 **
118577 ** This function is used when parsing the "prefix=" FTS4 parameter.
118578 */
118579 static int fts3GobbleInt(const char **pp, int *pnOut){
118580   const char *p;                  /* Iterator pointer */
118581   int nInt = 0;                   /* Output value */
118582
118583   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
118584     nInt = nInt * 10 + (p[0] - '0');
118585   }
118586   if( p==*pp ) return SQLITE_ERROR;
118587   *pnOut = nInt;
118588   *pp = p;
118589   return SQLITE_OK;
118590 }
118591
118592 /*
118593 ** This function is called to allocate an array of Fts3Index structures
118594 ** representing the indexes maintained by the current FTS table. FTS tables
118595 ** always maintain the main "terms" index, but may also maintain one or
118596 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
118597 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
118598 **
118599 ** Argument zParam is passed the value of the "prefix=" option if one was
118600 ** specified, or NULL otherwise.
118601 **
118602 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
118603 ** the allocated array. *pnIndex is set to the number of elements in the
118604 ** array. If an error does occur, an SQLite error code is returned.
118605 **
118606 ** Regardless of whether or not an error is returned, it is the responsibility
118607 ** of the caller to call sqlite3_free() on the output array to free it.
118608 */
118609 static int fts3PrefixParameter(
118610   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
118611   int *pnIndex,                   /* OUT: size of *apIndex[] array */
118612   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
118613 ){
118614   struct Fts3Index *aIndex;       /* Allocated array */
118615   int nIndex = 1;                 /* Number of entries in array */
118616
118617   if( zParam && zParam[0] ){
118618     const char *p;
118619     nIndex++;
118620     for(p=zParam; *p; p++){
118621       if( *p==',' ) nIndex++;
118622     }
118623   }
118624
118625   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
118626   *apIndex = aIndex;
118627   *pnIndex = nIndex;
118628   if( !aIndex ){
118629     return SQLITE_NOMEM;
118630   }
118631
118632   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
118633   if( zParam ){
118634     const char *p = zParam;
118635     int i;
118636     for(i=1; i<nIndex; i++){
118637       int nPrefix;
118638       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
118639       aIndex[i].nPrefix = nPrefix;
118640       p++;
118641     }
118642   }
118643
118644   return SQLITE_OK;
118645 }
118646
118647 /*
118648 ** This function is called when initializing an FTS4 table that uses the
118649 ** content=xxx option. It determines the number of and names of the columns
118650 ** of the new FTS4 table.
118651 **
118652 ** The third argument passed to this function is the value passed to the
118653 ** config=xxx option (i.e. "xxx"). This function queries the database for
118654 ** a table of that name. If found, the output variables are populated
118655 ** as follows:
118656 **
118657 **   *pnCol:   Set to the number of columns table xxx has,
118658 **
118659 **   *pnStr:   Set to the total amount of space required to store a copy
118660 **             of each columns name, including the nul-terminator.
118661 **
118662 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
118663 **             the name of the corresponding column in table xxx. The array
118664 **             and its contents are allocated using a single allocation. It
118665 **             is the responsibility of the caller to free this allocation
118666 **             by eventually passing the *pazCol value to sqlite3_free().
118667 **
118668 ** If the table cannot be found, an error code is returned and the output
118669 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
118670 ** returned (and the output variables are undefined).
118671 */
118672 static int fts3ContentColumns(
118673   sqlite3 *db,                    /* Database handle */
118674   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
118675   const char *zTbl,               /* Name of content table */
118676   const char ***pazCol,           /* OUT: Malloc'd array of column names */
118677   int *pnCol,                     /* OUT: Size of array *pazCol */
118678   int *pnStr                      /* OUT: Bytes of string content */
118679 ){
118680   int rc = SQLITE_OK;             /* Return code */
118681   char *zSql;                     /* "SELECT *" statement on zTbl */  
118682   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
118683
118684   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
118685   if( !zSql ){
118686     rc = SQLITE_NOMEM;
118687   }else{
118688     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
118689   }
118690   sqlite3_free(zSql);
118691
118692   if( rc==SQLITE_OK ){
118693     const char **azCol;           /* Output array */
118694     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
118695     int nCol;                     /* Number of table columns */
118696     int i;                        /* Used to iterate through columns */
118697
118698     /* Loop through the returned columns. Set nStr to the number of bytes of
118699     ** space required to store a copy of each column name, including the
118700     ** nul-terminator byte.  */
118701     nCol = sqlite3_column_count(pStmt);
118702     for(i=0; i<nCol; i++){
118703       const char *zCol = sqlite3_column_name(pStmt, i);
118704       nStr += (int)strlen(zCol) + 1;
118705     }
118706
118707     /* Allocate and populate the array to return. */
118708     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
118709     if( azCol==0 ){
118710       rc = SQLITE_NOMEM;
118711     }else{
118712       char *p = (char *)&azCol[nCol];
118713       for(i=0; i<nCol; i++){
118714         const char *zCol = sqlite3_column_name(pStmt, i);
118715         int n = (int)strlen(zCol)+1;
118716         memcpy(p, zCol, n);
118717         azCol[i] = p;
118718         p += n;
118719       }
118720     }
118721     sqlite3_finalize(pStmt);
118722
118723     /* Set the output variables. */
118724     *pnCol = nCol;
118725     *pnStr = nStr;
118726     *pazCol = azCol;
118727   }
118728
118729   return rc;
118730 }
118731
118732 /*
118733 ** This function is the implementation of both the xConnect and xCreate
118734 ** methods of the FTS3 virtual table.
118735 **
118736 ** The argv[] array contains the following:
118737 **
118738 **   argv[0]   -> module name  ("fts3" or "fts4")
118739 **   argv[1]   -> database name
118740 **   argv[2]   -> table name
118741 **   argv[...] -> "column name" and other module argument fields.
118742 */
118743 static int fts3InitVtab(
118744   int isCreate,                   /* True for xCreate, false for xConnect */
118745   sqlite3 *db,                    /* The SQLite database connection */
118746   void *pAux,                     /* Hash table containing tokenizers */
118747   int argc,                       /* Number of elements in argv array */
118748   const char * const *argv,       /* xCreate/xConnect argument array */
118749   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
118750   char **pzErr                    /* Write any error message here */
118751 ){
118752   Fts3Hash *pHash = (Fts3Hash *)pAux;
118753   Fts3Table *p = 0;               /* Pointer to allocated vtab */
118754   int rc = SQLITE_OK;             /* Return code */
118755   int i;                          /* Iterator variable */
118756   int nByte;                      /* Size of allocation used for *p */
118757   int iCol;                       /* Column index */
118758   int nString = 0;                /* Bytes required to hold all column names */
118759   int nCol = 0;                   /* Number of columns in the FTS table */
118760   char *zCsr;                     /* Space for holding column names */
118761   int nDb;                        /* Bytes required to hold database name */
118762   int nName;                      /* Bytes required to hold table name */
118763   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
118764   const char **aCol;              /* Array of column names */
118765   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
118766
118767   int nIndex;                     /* Size of aIndex[] array */
118768   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
118769
118770   /* The results of parsing supported FTS4 key=value options: */
118771   int bNoDocsize = 0;             /* True to omit %_docsize table */
118772   int bDescIdx = 0;               /* True to store descending indexes */
118773   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
118774   char *zCompress = 0;            /* compress=? parameter (or NULL) */
118775   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
118776   char *zContent = 0;             /* content=? parameter (or NULL) */
118777   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
118778
118779   assert( strlen(argv[0])==4 );
118780   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
118781        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
118782   );
118783
118784   nDb = (int)strlen(argv[1]) + 1;
118785   nName = (int)strlen(argv[2]) + 1;
118786
118787   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
118788   if( !aCol ) return SQLITE_NOMEM;
118789   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
118790
118791   /* Loop through all of the arguments passed by the user to the FTS3/4
118792   ** module (i.e. all the column names and special arguments). This loop
118793   ** does the following:
118794   **
118795   **   + Figures out the number of columns the FTSX table will have, and
118796   **     the number of bytes of space that must be allocated to store copies
118797   **     of the column names.
118798   **
118799   **   + If there is a tokenizer specification included in the arguments,
118800   **     initializes the tokenizer pTokenizer.
118801   */
118802   for(i=3; rc==SQLITE_OK && i<argc; i++){
118803     char const *z = argv[i];
118804     int nKey;
118805     char *zVal;
118806
118807     /* Check if this is a tokenizer specification */
118808     if( !pTokenizer 
118809      && strlen(z)>8
118810      && 0==sqlite3_strnicmp(z, "tokenize", 8) 
118811      && 0==sqlite3Fts3IsIdChar(z[8])
118812     ){
118813       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
118814     }
118815
118816     /* Check if it is an FTS4 special argument. */
118817     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
118818       struct Fts4Option {
118819         const char *zOpt;
118820         int nOpt;
118821       } aFts4Opt[] = {
118822         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
118823         { "prefix",      6 },     /* 1 -> PREFIX */
118824         { "compress",    8 },     /* 2 -> COMPRESS */
118825         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
118826         { "order",       5 },     /* 4 -> ORDER */
118827         { "content",     7 },     /* 5 -> CONTENT */
118828         { "languageid", 10 }      /* 6 -> LANGUAGEID */
118829       };
118830
118831       int iOpt;
118832       if( !zVal ){
118833         rc = SQLITE_NOMEM;
118834       }else{
118835         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
118836           struct Fts4Option *pOp = &aFts4Opt[iOpt];
118837           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
118838             break;
118839           }
118840         }
118841         if( iOpt==SizeofArray(aFts4Opt) ){
118842           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
118843           rc = SQLITE_ERROR;
118844         }else{
118845           switch( iOpt ){
118846             case 0:               /* MATCHINFO */
118847               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
118848                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
118849                 rc = SQLITE_ERROR;
118850               }
118851               bNoDocsize = 1;
118852               break;
118853
118854             case 1:               /* PREFIX */
118855               sqlite3_free(zPrefix);
118856               zPrefix = zVal;
118857               zVal = 0;
118858               break;
118859
118860             case 2:               /* COMPRESS */
118861               sqlite3_free(zCompress);
118862               zCompress = zVal;
118863               zVal = 0;
118864               break;
118865
118866             case 3:               /* UNCOMPRESS */
118867               sqlite3_free(zUncompress);
118868               zUncompress = zVal;
118869               zVal = 0;
118870               break;
118871
118872             case 4:               /* ORDER */
118873               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 
118874                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) 
118875               ){
118876                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
118877                 rc = SQLITE_ERROR;
118878               }
118879               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
118880               break;
118881
118882             case 5:              /* CONTENT */
118883               sqlite3_free(zContent);
118884               zContent = zVal;
118885               zVal = 0;
118886               break;
118887
118888             case 6:              /* LANGUAGEID */
118889               assert( iOpt==6 );
118890               sqlite3_free(zLanguageid);
118891               zLanguageid = zVal;
118892               zVal = 0;
118893               break;
118894           }
118895         }
118896         sqlite3_free(zVal);
118897       }
118898     }
118899
118900     /* Otherwise, the argument is a column name. */
118901     else {
118902       nString += (int)(strlen(z) + 1);
118903       aCol[nCol++] = z;
118904     }
118905   }
118906
118907   /* If a content=xxx option was specified, the following:
118908   **
118909   **   1. Ignore any compress= and uncompress= options.
118910   **
118911   **   2. If no column names were specified as part of the CREATE VIRTUAL
118912   **      TABLE statement, use all columns from the content table.
118913   */
118914   if( rc==SQLITE_OK && zContent ){
118915     sqlite3_free(zCompress); 
118916     sqlite3_free(zUncompress); 
118917     zCompress = 0;
118918     zUncompress = 0;
118919     if( nCol==0 ){
118920       sqlite3_free((void*)aCol); 
118921       aCol = 0;
118922       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
118923
118924       /* If a languageid= option was specified, remove the language id
118925       ** column from the aCol[] array. */ 
118926       if( rc==SQLITE_OK && zLanguageid ){
118927         int j;
118928         for(j=0; j<nCol; j++){
118929           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
118930             int k;
118931             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
118932             nCol--;
118933             break;
118934           }
118935         }
118936       }
118937     }
118938   }
118939   if( rc!=SQLITE_OK ) goto fts3_init_out;
118940
118941   if( nCol==0 ){
118942     assert( nString==0 );
118943     aCol[0] = "content";
118944     nString = 8;
118945     nCol = 1;
118946   }
118947
118948   if( pTokenizer==0 ){
118949     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
118950     if( rc!=SQLITE_OK ) goto fts3_init_out;
118951   }
118952   assert( pTokenizer );
118953
118954   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
118955   if( rc==SQLITE_ERROR ){
118956     assert( zPrefix );
118957     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
118958   }
118959   if( rc!=SQLITE_OK ) goto fts3_init_out;
118960
118961   /* Allocate and populate the Fts3Table structure. */
118962   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
118963           nCol * sizeof(char *) +              /* azColumn */
118964           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
118965           nName +                              /* zName */
118966           nDb +                                /* zDb */
118967           nString;                             /* Space for azColumn strings */
118968   p = (Fts3Table*)sqlite3_malloc(nByte);
118969   if( p==0 ){
118970     rc = SQLITE_NOMEM;
118971     goto fts3_init_out;
118972   }
118973   memset(p, 0, nByte);
118974   p->db = db;
118975   p->nColumn = nCol;
118976   p->nPendingData = 0;
118977   p->azColumn = (char **)&p[1];
118978   p->pTokenizer = pTokenizer;
118979   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
118980   p->bHasDocsize = (isFts4 && bNoDocsize==0);
118981   p->bHasStat = isFts4;
118982   p->bFts4 = isFts4;
118983   p->bDescIdx = bDescIdx;
118984   p->bAutoincrmerge = 0xff;   /* 0xff means setting unknown */
118985   p->zContentTbl = zContent;
118986   p->zLanguageid = zLanguageid;
118987   zContent = 0;
118988   zLanguageid = 0;
118989   TESTONLY( p->inTransaction = -1 );
118990   TESTONLY( p->mxSavepoint = -1 );
118991
118992   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
118993   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
118994   p->nIndex = nIndex;
118995   for(i=0; i<nIndex; i++){
118996     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
118997   }
118998
118999   /* Fill in the zName and zDb fields of the vtab structure. */
119000   zCsr = (char *)&p->aIndex[nIndex];
119001   p->zName = zCsr;
119002   memcpy(zCsr, argv[2], nName);
119003   zCsr += nName;
119004   p->zDb = zCsr;
119005   memcpy(zCsr, argv[1], nDb);
119006   zCsr += nDb;
119007
119008   /* Fill in the azColumn array */
119009   for(iCol=0; iCol<nCol; iCol++){
119010     char *z; 
119011     int n = 0;
119012     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
119013     memcpy(zCsr, z, n);
119014     zCsr[n] = '\0';
119015     sqlite3Fts3Dequote(zCsr);
119016     p->azColumn[iCol] = zCsr;
119017     zCsr += n+1;
119018     assert( zCsr <= &((char *)p)[nByte] );
119019   }
119020
119021   if( (zCompress==0)!=(zUncompress==0) ){
119022     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
119023     rc = SQLITE_ERROR;
119024     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
119025   }
119026   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
119027   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
119028   if( rc!=SQLITE_OK ) goto fts3_init_out;
119029
119030   /* If this is an xCreate call, create the underlying tables in the 
119031   ** database. TODO: For xConnect(), it could verify that said tables exist.
119032   */
119033   if( isCreate ){
119034     rc = fts3CreateTables(p);
119035   }
119036
119037   /* Check to see if a legacy fts3 table has been "upgraded" by the
119038   ** addition of a %_stat table so that it can use incremental merge.
119039   */
119040   if( !isFts4 && !isCreate ){
119041     int rc2 = SQLITE_OK;
119042     fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
119043                p->zDb, p->zName);
119044     if( rc2==SQLITE_OK ) p->bHasStat = 1;
119045   }
119046
119047   /* Figure out the page-size for the database. This is required in order to
119048   ** estimate the cost of loading large doclists from the database.  */
119049   fts3DatabasePageSize(&rc, p);
119050   p->nNodeSize = p->nPgsz-35;
119051
119052   /* Declare the table schema to SQLite. */
119053   fts3DeclareVtab(&rc, p);
119054
119055 fts3_init_out:
119056   sqlite3_free(zPrefix);
119057   sqlite3_free(aIndex);
119058   sqlite3_free(zCompress);
119059   sqlite3_free(zUncompress);
119060   sqlite3_free(zContent);
119061   sqlite3_free(zLanguageid);
119062   sqlite3_free((void *)aCol);
119063   if( rc!=SQLITE_OK ){
119064     if( p ){
119065       fts3DisconnectMethod((sqlite3_vtab *)p);
119066     }else if( pTokenizer ){
119067       pTokenizer->pModule->xDestroy(pTokenizer);
119068     }
119069   }else{
119070     assert( p->pSegments==0 );
119071     *ppVTab = &p->base;
119072   }
119073   return rc;
119074 }
119075
119076 /*
119077 ** The xConnect() and xCreate() methods for the virtual table. All the
119078 ** work is done in function fts3InitVtab().
119079 */
119080 static int fts3ConnectMethod(
119081   sqlite3 *db,                    /* Database connection */
119082   void *pAux,                     /* Pointer to tokenizer hash table */
119083   int argc,                       /* Number of elements in argv array */
119084   const char * const *argv,       /* xCreate/xConnect argument array */
119085   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
119086   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
119087 ){
119088   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
119089 }
119090 static int fts3CreateMethod(
119091   sqlite3 *db,                    /* Database connection */
119092   void *pAux,                     /* Pointer to tokenizer hash table */
119093   int argc,                       /* Number of elements in argv array */
119094   const char * const *argv,       /* xCreate/xConnect argument array */
119095   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
119096   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
119097 ){
119098   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
119099 }
119100
119101 /* 
119102 ** Implementation of the xBestIndex method for FTS3 tables. There
119103 ** are three possible strategies, in order of preference:
119104 **
119105 **   1. Direct lookup by rowid or docid. 
119106 **   2. Full-text search using a MATCH operator on a non-docid column.
119107 **   3. Linear scan of %_content table.
119108 */
119109 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
119110   Fts3Table *p = (Fts3Table *)pVTab;
119111   int i;                          /* Iterator variable */
119112   int iCons = -1;                 /* Index of constraint to use */
119113   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
119114
119115   /* By default use a full table scan. This is an expensive option,
119116   ** so search through the constraints to see if a more efficient 
119117   ** strategy is possible.
119118   */
119119   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
119120   pInfo->estimatedCost = 500000;
119121   for(i=0; i<pInfo->nConstraint; i++){
119122     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
119123     if( pCons->usable==0 ) continue;
119124
119125     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
119126     if( iCons<0 
119127      && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
119128      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
119129     ){
119130       pInfo->idxNum = FTS3_DOCID_SEARCH;
119131       pInfo->estimatedCost = 1.0;
119132       iCons = i;
119133     }
119134
119135     /* A MATCH constraint. Use a full-text search.
119136     **
119137     ** If there is more than one MATCH constraint available, use the first
119138     ** one encountered. If there is both a MATCH constraint and a direct
119139     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
119140     ** though the rowid/docid lookup is faster than a MATCH query, selecting
119141     ** it would lead to an "unable to use function MATCH in the requested 
119142     ** context" error.
119143     */
119144     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
119145      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
119146     ){
119147       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
119148       pInfo->estimatedCost = 2.0;
119149       iCons = i;
119150     }
119151
119152     /* Equality constraint on the langid column */
119153     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
119154      && pCons->iColumn==p->nColumn + 2
119155     ){
119156       iLangidCons = i;
119157     }
119158   }
119159
119160   if( iCons>=0 ){
119161     pInfo->aConstraintUsage[iCons].argvIndex = 1;
119162     pInfo->aConstraintUsage[iCons].omit = 1;
119163   } 
119164   if( iLangidCons>=0 ){
119165     pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
119166   } 
119167
119168   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
119169   ** docid) order. Both ascending and descending are possible. 
119170   */
119171   if( pInfo->nOrderBy==1 ){
119172     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
119173     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
119174       if( pOrder->desc ){
119175         pInfo->idxStr = "DESC";
119176       }else{
119177         pInfo->idxStr = "ASC";
119178       }
119179       pInfo->orderByConsumed = 1;
119180     }
119181   }
119182
119183   assert( p->pSegments==0 );
119184   return SQLITE_OK;
119185 }
119186
119187 /*
119188 ** Implementation of xOpen method.
119189 */
119190 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
119191   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
119192
119193   UNUSED_PARAMETER(pVTab);
119194
119195   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
119196   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
119197   ** if the allocation fails, return SQLITE_NOMEM.
119198   */
119199   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
119200   if( !pCsr ){
119201     return SQLITE_NOMEM;
119202   }
119203   memset(pCsr, 0, sizeof(Fts3Cursor));
119204   return SQLITE_OK;
119205 }
119206
119207 /*
119208 ** Close the cursor.  For additional information see the documentation
119209 ** on the xClose method of the virtual table interface.
119210 */
119211 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
119212   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
119213   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119214   sqlite3_finalize(pCsr->pStmt);
119215   sqlite3Fts3ExprFree(pCsr->pExpr);
119216   sqlite3Fts3FreeDeferredTokens(pCsr);
119217   sqlite3_free(pCsr->aDoclist);
119218   sqlite3_free(pCsr->aMatchinfo);
119219   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119220   sqlite3_free(pCsr);
119221   return SQLITE_OK;
119222 }
119223
119224 /*
119225 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
119226 ** compose and prepare an SQL statement of the form:
119227 **
119228 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
119229 **
119230 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
119231 ** it. If an error occurs, return an SQLite error code.
119232 **
119233 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
119234 */
119235 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
119236   int rc = SQLITE_OK;
119237   if( pCsr->pStmt==0 ){
119238     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
119239     char *zSql;
119240     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
119241     if( !zSql ) return SQLITE_NOMEM;
119242     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
119243     sqlite3_free(zSql);
119244   }
119245   *ppStmt = pCsr->pStmt;
119246   return rc;
119247 }
119248
119249 /*
119250 ** Position the pCsr->pStmt statement so that it is on the row
119251 ** of the %_content table that contains the last match.  Return
119252 ** SQLITE_OK on success.  
119253 */
119254 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
119255   int rc = SQLITE_OK;
119256   if( pCsr->isRequireSeek ){
119257     sqlite3_stmt *pStmt = 0;
119258
119259     rc = fts3CursorSeekStmt(pCsr, &pStmt);
119260     if( rc==SQLITE_OK ){
119261       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
119262       pCsr->isRequireSeek = 0;
119263       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
119264         return SQLITE_OK;
119265       }else{
119266         rc = sqlite3_reset(pCsr->pStmt);
119267         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
119268           /* If no row was found and no error has occurred, then the %_content
119269           ** table is missing a row that is present in the full-text index.
119270           ** The data structures are corrupt.  */
119271           rc = FTS_CORRUPT_VTAB;
119272           pCsr->isEof = 1;
119273         }
119274       }
119275     }
119276   }
119277
119278   if( rc!=SQLITE_OK && pContext ){
119279     sqlite3_result_error_code(pContext, rc);
119280   }
119281   return rc;
119282 }
119283
119284 /*
119285 ** This function is used to process a single interior node when searching
119286 ** a b-tree for a term or term prefix. The node data is passed to this 
119287 ** function via the zNode/nNode parameters. The term to search for is
119288 ** passed in zTerm/nTerm.
119289 **
119290 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
119291 ** of the child node that heads the sub-tree that may contain the term.
119292 **
119293 ** If piLast is not NULL, then *piLast is set to the right-most child node
119294 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
119295 ** a prefix.
119296 **
119297 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
119298 */
119299 static int fts3ScanInteriorNode(
119300   const char *zTerm,              /* Term to select leaves for */
119301   int nTerm,                      /* Size of term zTerm in bytes */
119302   const char *zNode,              /* Buffer containing segment interior node */
119303   int nNode,                      /* Size of buffer at zNode */
119304   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
119305   sqlite3_int64 *piLast           /* OUT: Selected child node */
119306 ){
119307   int rc = SQLITE_OK;             /* Return code */
119308   const char *zCsr = zNode;       /* Cursor to iterate through node */
119309   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
119310   char *zBuffer = 0;              /* Buffer to load terms into */
119311   int nAlloc = 0;                 /* Size of allocated buffer */
119312   int isFirstTerm = 1;            /* True when processing first term on page */
119313   sqlite3_int64 iChild;           /* Block id of child node to descend to */
119314
119315   /* Skip over the 'height' varint that occurs at the start of every 
119316   ** interior node. Then load the blockid of the left-child of the b-tree
119317   ** node into variable iChild.  
119318   **
119319   ** Even if the data structure on disk is corrupted, this (reading two
119320   ** varints from the buffer) does not risk an overread. If zNode is a
119321   ** root node, then the buffer comes from a SELECT statement. SQLite does
119322   ** not make this guarantee explicitly, but in practice there are always
119323   ** either more than 20 bytes of allocated space following the nNode bytes of
119324   ** contents, or two zero bytes. Or, if the node is read from the %_segments
119325   ** table, then there are always 20 bytes of zeroed padding following the
119326   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
119327   */
119328   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
119329   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
119330   if( zCsr>zEnd ){
119331     return FTS_CORRUPT_VTAB;
119332   }
119333   
119334   while( zCsr<zEnd && (piFirst || piLast) ){
119335     int cmp;                      /* memcmp() result */
119336     int nSuffix;                  /* Size of term suffix */
119337     int nPrefix = 0;              /* Size of term prefix */
119338     int nBuffer;                  /* Total term size */
119339   
119340     /* Load the next term on the node into zBuffer. Use realloc() to expand
119341     ** the size of zBuffer if required.  */
119342     if( !isFirstTerm ){
119343       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
119344     }
119345     isFirstTerm = 0;
119346     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
119347     
119348     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
119349       rc = FTS_CORRUPT_VTAB;
119350       goto finish_scan;
119351     }
119352     if( nPrefix+nSuffix>nAlloc ){
119353       char *zNew;
119354       nAlloc = (nPrefix+nSuffix) * 2;
119355       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
119356       if( !zNew ){
119357         rc = SQLITE_NOMEM;
119358         goto finish_scan;
119359       }
119360       zBuffer = zNew;
119361     }
119362     assert( zBuffer );
119363     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
119364     nBuffer = nPrefix + nSuffix;
119365     zCsr += nSuffix;
119366
119367     /* Compare the term we are searching for with the term just loaded from
119368     ** the interior node. If the specified term is greater than or equal
119369     ** to the term from the interior node, then all terms on the sub-tree 
119370     ** headed by node iChild are smaller than zTerm. No need to search 
119371     ** iChild.
119372     **
119373     ** If the interior node term is larger than the specified term, then
119374     ** the tree headed by iChild may contain the specified term.
119375     */
119376     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
119377     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
119378       *piFirst = iChild;
119379       piFirst = 0;
119380     }
119381
119382     if( piLast && cmp<0 ){
119383       *piLast = iChild;
119384       piLast = 0;
119385     }
119386
119387     iChild++;
119388   };
119389
119390   if( piFirst ) *piFirst = iChild;
119391   if( piLast ) *piLast = iChild;
119392
119393  finish_scan:
119394   sqlite3_free(zBuffer);
119395   return rc;
119396 }
119397
119398
119399 /*
119400 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
119401 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
119402 ** contains a term. This function searches the sub-tree headed by the zNode
119403 ** node for the range of leaf nodes that may contain the specified term
119404 ** or terms for which the specified term is a prefix.
119405 **
119406 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
119407 ** left-most leaf node in the tree that may contain the specified term.
119408 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
119409 ** right-most leaf node that may contain a term for which the specified
119410 ** term is a prefix.
119411 **
119412 ** It is possible that the range of returned leaf nodes does not contain 
119413 ** the specified term or any terms for which it is a prefix. However, if the 
119414 ** segment does contain any such terms, they are stored within the identified
119415 ** range. Because this function only inspects interior segment nodes (and
119416 ** never loads leaf nodes into memory), it is not possible to be sure.
119417 **
119418 ** If an error occurs, an error code other than SQLITE_OK is returned.
119419 */ 
119420 static int fts3SelectLeaf(
119421   Fts3Table *p,                   /* Virtual table handle */
119422   const char *zTerm,              /* Term to select leaves for */
119423   int nTerm,                      /* Size of term zTerm in bytes */
119424   const char *zNode,              /* Buffer containing segment interior node */
119425   int nNode,                      /* Size of buffer at zNode */
119426   sqlite3_int64 *piLeaf,          /* Selected leaf node */
119427   sqlite3_int64 *piLeaf2          /* Selected leaf node */
119428 ){
119429   int rc;                         /* Return code */
119430   int iHeight;                    /* Height of this node in tree */
119431
119432   assert( piLeaf || piLeaf2 );
119433
119434   sqlite3Fts3GetVarint32(zNode, &iHeight);
119435   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
119436   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
119437
119438   if( rc==SQLITE_OK && iHeight>1 ){
119439     char *zBlob = 0;              /* Blob read from %_segments table */
119440     int nBlob;                    /* Size of zBlob in bytes */
119441
119442     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
119443       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
119444       if( rc==SQLITE_OK ){
119445         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
119446       }
119447       sqlite3_free(zBlob);
119448       piLeaf = 0;
119449       zBlob = 0;
119450     }
119451
119452     if( rc==SQLITE_OK ){
119453       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
119454     }
119455     if( rc==SQLITE_OK ){
119456       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
119457     }
119458     sqlite3_free(zBlob);
119459   }
119460
119461   return rc;
119462 }
119463
119464 /*
119465 ** This function is used to create delta-encoded serialized lists of FTS3 
119466 ** varints. Each call to this function appends a single varint to a list.
119467 */
119468 static void fts3PutDeltaVarint(
119469   char **pp,                      /* IN/OUT: Output pointer */
119470   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
119471   sqlite3_int64 iVal              /* Write this value to the list */
119472 ){
119473   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
119474   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
119475   *piPrev = iVal;
119476 }
119477
119478 /*
119479 ** When this function is called, *ppPoslist is assumed to point to the 
119480 ** start of a position-list. After it returns, *ppPoslist points to the
119481 ** first byte after the position-list.
119482 **
119483 ** A position list is list of positions (delta encoded) and columns for 
119484 ** a single document record of a doclist.  So, in other words, this
119485 ** routine advances *ppPoslist so that it points to the next docid in
119486 ** the doclist, or to the first byte past the end of the doclist.
119487 **
119488 ** If pp is not NULL, then the contents of the position list are copied
119489 ** to *pp. *pp is set to point to the first byte past the last byte copied
119490 ** before this function returns.
119491 */
119492 static void fts3PoslistCopy(char **pp, char **ppPoslist){
119493   char *pEnd = *ppPoslist;
119494   char c = 0;
119495
119496   /* The end of a position list is marked by a zero encoded as an FTS3 
119497   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
119498   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
119499   ** of some other, multi-byte, value.
119500   **
119501   ** The following while-loop moves pEnd to point to the first byte that is not 
119502   ** immediately preceded by a byte with the 0x80 bit set. Then increments
119503   ** pEnd once more so that it points to the byte immediately following the
119504   ** last byte in the position-list.
119505   */
119506   while( *pEnd | c ){
119507     c = *pEnd++ & 0x80;
119508     testcase( c!=0 && (*pEnd)==0 );
119509   }
119510   pEnd++;  /* Advance past the POS_END terminator byte */
119511
119512   if( pp ){
119513     int n = (int)(pEnd - *ppPoslist);
119514     char *p = *pp;
119515     memcpy(p, *ppPoslist, n);
119516     p += n;
119517     *pp = p;
119518   }
119519   *ppPoslist = pEnd;
119520 }
119521
119522 /*
119523 ** When this function is called, *ppPoslist is assumed to point to the 
119524 ** start of a column-list. After it returns, *ppPoslist points to the
119525 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
119526 **
119527 ** A column-list is list of delta-encoded positions for a single column
119528 ** within a single document within a doclist.
119529 **
119530 ** The column-list is terminated either by a POS_COLUMN varint (1) or
119531 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
119532 ** the POS_COLUMN or POS_END that terminates the column-list.
119533 **
119534 ** If pp is not NULL, then the contents of the column-list are copied
119535 ** to *pp. *pp is set to point to the first byte past the last byte copied
119536 ** before this function returns.  The POS_COLUMN or POS_END terminator
119537 ** is not copied into *pp.
119538 */
119539 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
119540   char *pEnd = *ppPoslist;
119541   char c = 0;
119542
119543   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
119544   ** not part of a multi-byte varint.
119545   */
119546   while( 0xFE & (*pEnd | c) ){
119547     c = *pEnd++ & 0x80;
119548     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
119549   }
119550   if( pp ){
119551     int n = (int)(pEnd - *ppPoslist);
119552     char *p = *pp;
119553     memcpy(p, *ppPoslist, n);
119554     p += n;
119555     *pp = p;
119556   }
119557   *ppPoslist = pEnd;
119558 }
119559
119560 /*
119561 ** Value used to signify the end of an position-list. This is safe because
119562 ** it is not possible to have a document with 2^31 terms.
119563 */
119564 #define POSITION_LIST_END 0x7fffffff
119565
119566 /*
119567 ** This function is used to help parse position-lists. When this function is
119568 ** called, *pp may point to the start of the next varint in the position-list
119569 ** being parsed, or it may point to 1 byte past the end of the position-list
119570 ** (in which case **pp will be a terminator bytes POS_END (0) or
119571 ** (1)).
119572 **
119573 ** If *pp points past the end of the current position-list, set *pi to 
119574 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
119575 ** increment the current value of *pi by the value read, and set *pp to
119576 ** point to the next value before returning.
119577 **
119578 ** Before calling this routine *pi must be initialized to the value of
119579 ** the previous position, or zero if we are reading the first position
119580 ** in the position-list.  Because positions are delta-encoded, the value
119581 ** of the previous position is needed in order to compute the value of
119582 ** the next position.
119583 */
119584 static void fts3ReadNextPos(
119585   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
119586   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
119587 ){
119588   if( (**pp)&0xFE ){
119589     fts3GetDeltaVarint(pp, pi);
119590     *pi -= 2;
119591   }else{
119592     *pi = POSITION_LIST_END;
119593   }
119594 }
119595
119596 /*
119597 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
119598 ** the value of iCol encoded as a varint to *pp.   This will start a new
119599 ** column list.
119600 **
119601 ** Set *pp to point to the byte just after the last byte written before 
119602 ** returning (do not modify it if iCol==0). Return the total number of bytes
119603 ** written (0 if iCol==0).
119604 */
119605 static int fts3PutColNumber(char **pp, int iCol){
119606   int n = 0;                      /* Number of bytes written */
119607   if( iCol ){
119608     char *p = *pp;                /* Output pointer */
119609     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
119610     *p = 0x01;
119611     *pp = &p[n];
119612   }
119613   return n;
119614 }
119615
119616 /*
119617 ** Compute the union of two position lists.  The output written
119618 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
119619 ** order and with any duplicates removed.  All pointers are
119620 ** updated appropriately.   The caller is responsible for insuring
119621 ** that there is enough space in *pp to hold the complete output.
119622 */
119623 static void fts3PoslistMerge(
119624   char **pp,                      /* Output buffer */
119625   char **pp1,                     /* Left input list */
119626   char **pp2                      /* Right input list */
119627 ){
119628   char *p = *pp;
119629   char *p1 = *pp1;
119630   char *p2 = *pp2;
119631
119632   while( *p1 || *p2 ){
119633     int iCol1;         /* The current column index in pp1 */
119634     int iCol2;         /* The current column index in pp2 */
119635
119636     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
119637     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
119638     else iCol1 = 0;
119639
119640     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
119641     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
119642     else iCol2 = 0;
119643
119644     if( iCol1==iCol2 ){
119645       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
119646       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
119647       sqlite3_int64 iPrev = 0;
119648       int n = fts3PutColNumber(&p, iCol1);
119649       p1 += n;
119650       p2 += n;
119651
119652       /* At this point, both p1 and p2 point to the start of column-lists
119653       ** for the same column (the column with index iCol1 and iCol2).
119654       ** A column-list is a list of non-negative delta-encoded varints, each 
119655       ** incremented by 2 before being stored. Each list is terminated by a
119656       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
119657       ** and writes the results to buffer p. p is left pointing to the byte
119658       ** after the list written. No terminator (POS_END or POS_COLUMN) is
119659       ** written to the output.
119660       */
119661       fts3GetDeltaVarint(&p1, &i1);
119662       fts3GetDeltaVarint(&p2, &i2);
119663       do {
119664         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
119665         iPrev -= 2;
119666         if( i1==i2 ){
119667           fts3ReadNextPos(&p1, &i1);
119668           fts3ReadNextPos(&p2, &i2);
119669         }else if( i1<i2 ){
119670           fts3ReadNextPos(&p1, &i1);
119671         }else{
119672           fts3ReadNextPos(&p2, &i2);
119673         }
119674       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
119675     }else if( iCol1<iCol2 ){
119676       p1 += fts3PutColNumber(&p, iCol1);
119677       fts3ColumnlistCopy(&p, &p1);
119678     }else{
119679       p2 += fts3PutColNumber(&p, iCol2);
119680       fts3ColumnlistCopy(&p, &p2);
119681     }
119682   }
119683
119684   *p++ = POS_END;
119685   *pp = p;
119686   *pp1 = p1 + 1;
119687   *pp2 = p2 + 1;
119688 }
119689
119690 /*
119691 ** This function is used to merge two position lists into one. When it is
119692 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
119693 ** the part of a doclist that follows each document id. For example, if a row
119694 ** contains:
119695 **
119696 **     'a b c'|'x y z'|'a b b a'
119697 **
119698 ** Then the position list for this row for token 'b' would consist of:
119699 **
119700 **     0x02 0x01 0x02 0x03 0x03 0x00
119701 **
119702 ** When this function returns, both *pp1 and *pp2 are left pointing to the
119703 ** byte following the 0x00 terminator of their respective position lists.
119704 **
119705 ** If isSaveLeft is 0, an entry is added to the output position list for 
119706 ** each position in *pp2 for which there exists one or more positions in
119707 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
119708 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
119709 ** slots before it.
119710 **
119711 ** e.g. nToken==1 searches for adjacent positions.
119712 */
119713 static int fts3PoslistPhraseMerge(
119714   char **pp,                      /* IN/OUT: Preallocated output buffer */
119715   int nToken,                     /* Maximum difference in token positions */
119716   int isSaveLeft,                 /* Save the left position */
119717   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
119718   char **pp1,                     /* IN/OUT: Left input list */
119719   char **pp2                      /* IN/OUT: Right input list */
119720 ){
119721   char *p = *pp;
119722   char *p1 = *pp1;
119723   char *p2 = *pp2;
119724   int iCol1 = 0;
119725   int iCol2 = 0;
119726
119727   /* Never set both isSaveLeft and isExact for the same invocation. */
119728   assert( isSaveLeft==0 || isExact==0 );
119729
119730   assert( p!=0 && *p1!=0 && *p2!=0 );
119731   if( *p1==POS_COLUMN ){ 
119732     p1++;
119733     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
119734   }
119735   if( *p2==POS_COLUMN ){ 
119736     p2++;
119737     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
119738   }
119739
119740   while( 1 ){
119741     if( iCol1==iCol2 ){
119742       char *pSave = p;
119743       sqlite3_int64 iPrev = 0;
119744       sqlite3_int64 iPos1 = 0;
119745       sqlite3_int64 iPos2 = 0;
119746
119747       if( iCol1 ){
119748         *p++ = POS_COLUMN;
119749         p += sqlite3Fts3PutVarint(p, iCol1);
119750       }
119751
119752       assert( *p1!=POS_END && *p1!=POS_COLUMN );
119753       assert( *p2!=POS_END && *p2!=POS_COLUMN );
119754       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
119755       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
119756
119757       while( 1 ){
119758         if( iPos2==iPos1+nToken 
119759          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
119760         ){
119761           sqlite3_int64 iSave;
119762           iSave = isSaveLeft ? iPos1 : iPos2;
119763           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
119764           pSave = 0;
119765           assert( p );
119766         }
119767         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
119768           if( (*p2&0xFE)==0 ) break;
119769           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
119770         }else{
119771           if( (*p1&0xFE)==0 ) break;
119772           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
119773         }
119774       }
119775
119776       if( pSave ){
119777         assert( pp && p );
119778         p = pSave;
119779       }
119780
119781       fts3ColumnlistCopy(0, &p1);
119782       fts3ColumnlistCopy(0, &p2);
119783       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
119784       if( 0==*p1 || 0==*p2 ) break;
119785
119786       p1++;
119787       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
119788       p2++;
119789       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
119790     }
119791
119792     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
119793     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
119794     ** end of the position list, or the 0x01 that precedes the next 
119795     ** column-number in the position list. 
119796     */
119797     else if( iCol1<iCol2 ){
119798       fts3ColumnlistCopy(0, &p1);
119799       if( 0==*p1 ) break;
119800       p1++;
119801       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
119802     }else{
119803       fts3ColumnlistCopy(0, &p2);
119804       if( 0==*p2 ) break;
119805       p2++;
119806       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
119807     }
119808   }
119809
119810   fts3PoslistCopy(0, &p2);
119811   fts3PoslistCopy(0, &p1);
119812   *pp1 = p1;
119813   *pp2 = p2;
119814   if( *pp==p ){
119815     return 0;
119816   }
119817   *p++ = 0x00;
119818   *pp = p;
119819   return 1;
119820 }
119821
119822 /*
119823 ** Merge two position-lists as required by the NEAR operator. The argument
119824 ** position lists correspond to the left and right phrases of an expression 
119825 ** like:
119826 **
119827 **     "phrase 1" NEAR "phrase number 2"
119828 **
119829 ** Position list *pp1 corresponds to the left-hand side of the NEAR 
119830 ** expression and *pp2 to the right. As usual, the indexes in the position 
119831 ** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
119832 ** in the example above).
119833 **
119834 ** The output position list - written to *pp - is a copy of *pp2 with those
119835 ** entries that are not sufficiently NEAR entries in *pp1 removed.
119836 */
119837 static int fts3PoslistNearMerge(
119838   char **pp,                      /* Output buffer */
119839   char *aTmp,                     /* Temporary buffer space */
119840   int nRight,                     /* Maximum difference in token positions */
119841   int nLeft,                      /* Maximum difference in token positions */
119842   char **pp1,                     /* IN/OUT: Left input list */
119843   char **pp2                      /* IN/OUT: Right input list */
119844 ){
119845   char *p1 = *pp1;
119846   char *p2 = *pp2;
119847
119848   char *pTmp1 = aTmp;
119849   char *pTmp2;
119850   char *aTmp2;
119851   int res = 1;
119852
119853   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
119854   aTmp2 = pTmp2 = pTmp1;
119855   *pp1 = p1;
119856   *pp2 = p2;
119857   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
119858   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
119859     fts3PoslistMerge(pp, &aTmp, &aTmp2);
119860   }else if( pTmp1!=aTmp ){
119861     fts3PoslistCopy(pp, &aTmp);
119862   }else if( pTmp2!=aTmp2 ){
119863     fts3PoslistCopy(pp, &aTmp2);
119864   }else{
119865     res = 0;
119866   }
119867
119868   return res;
119869 }
119870
119871 /* 
119872 ** An instance of this function is used to merge together the (potentially
119873 ** large number of) doclists for each term that matches a prefix query.
119874 ** See function fts3TermSelectMerge() for details.
119875 */
119876 typedef struct TermSelect TermSelect;
119877 struct TermSelect {
119878   char *aaOutput[16];             /* Malloc'd output buffers */
119879   int anOutput[16];               /* Size each output buffer in bytes */
119880 };
119881
119882 /*
119883 ** This function is used to read a single varint from a buffer. Parameter
119884 ** pEnd points 1 byte past the end of the buffer. When this function is
119885 ** called, if *pp points to pEnd or greater, then the end of the buffer
119886 ** has been reached. In this case *pp is set to 0 and the function returns.
119887 **
119888 ** If *pp does not point to or past pEnd, then a single varint is read
119889 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
119890 **
119891 ** If bDescIdx is false, the value read is added to *pVal before returning.
119892 ** If it is true, the value read is subtracted from *pVal before this 
119893 ** function returns.
119894 */
119895 static void fts3GetDeltaVarint3(
119896   char **pp,                      /* IN/OUT: Point to read varint from */
119897   char *pEnd,                     /* End of buffer */
119898   int bDescIdx,                   /* True if docids are descending */
119899   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
119900 ){
119901   if( *pp>=pEnd ){
119902     *pp = 0;
119903   }else{
119904     sqlite3_int64 iVal;
119905     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
119906     if( bDescIdx ){
119907       *pVal -= iVal;
119908     }else{
119909       *pVal += iVal;
119910     }
119911   }
119912 }
119913
119914 /*
119915 ** This function is used to write a single varint to a buffer. The varint
119916 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
119917 ** end of the value written.
119918 **
119919 ** If *pbFirst is zero when this function is called, the value written to
119920 ** the buffer is that of parameter iVal. 
119921 **
119922 ** If *pbFirst is non-zero when this function is called, then the value 
119923 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
119924 ** (if bDescIdx is non-zero).
119925 **
119926 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
119927 ** to the value of parameter iVal.
119928 */
119929 static void fts3PutDeltaVarint3(
119930   char **pp,                      /* IN/OUT: Output pointer */
119931   int bDescIdx,                   /* True for descending docids */
119932   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
119933   int *pbFirst,                   /* IN/OUT: True after first int written */
119934   sqlite3_int64 iVal              /* Write this value to the list */
119935 ){
119936   sqlite3_int64 iWrite;
119937   if( bDescIdx==0 || *pbFirst==0 ){
119938     iWrite = iVal - *piPrev;
119939   }else{
119940     iWrite = *piPrev - iVal;
119941   }
119942   assert( *pbFirst || *piPrev==0 );
119943   assert( *pbFirst==0 || iWrite>0 );
119944   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
119945   *piPrev = iVal;
119946   *pbFirst = 1;
119947 }
119948
119949
119950 /*
119951 ** This macro is used by various functions that merge doclists. The two
119952 ** arguments are 64-bit docid values. If the value of the stack variable
119953 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
119954 ** Otherwise, (i2-i1).
119955 **
119956 ** Using this makes it easier to write code that can merge doclists that are
119957 ** sorted in either ascending or descending order.
119958 */
119959 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
119960
119961 /*
119962 ** This function does an "OR" merge of two doclists (output contains all
119963 ** positions contained in either argument doclist). If the docids in the 
119964 ** input doclists are sorted in ascending order, parameter bDescDoclist
119965 ** should be false. If they are sorted in ascending order, it should be
119966 ** passed a non-zero value.
119967 **
119968 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
119969 ** containing the output doclist and SQLITE_OK is returned. In this case
119970 ** *pnOut is set to the number of bytes in the output doclist.
119971 **
119972 ** If an error occurs, an SQLite error code is returned. The output values
119973 ** are undefined in this case.
119974 */
119975 static int fts3DoclistOrMerge(
119976   int bDescDoclist,               /* True if arguments are desc */
119977   char *a1, int n1,               /* First doclist */
119978   char *a2, int n2,               /* Second doclist */
119979   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
119980 ){
119981   sqlite3_int64 i1 = 0;
119982   sqlite3_int64 i2 = 0;
119983   sqlite3_int64 iPrev = 0;
119984   char *pEnd1 = &a1[n1];
119985   char *pEnd2 = &a2[n2];
119986   char *p1 = a1;
119987   char *p2 = a2;
119988   char *p;
119989   char *aOut;
119990   int bFirstOut = 0;
119991
119992   *paOut = 0;
119993   *pnOut = 0;
119994
119995   /* Allocate space for the output. Both the input and output doclists
119996   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
119997   ** then the first docid in each list is simply encoded as a varint. For
119998   ** each subsequent docid, the varint stored is the difference between the
119999   ** current and previous docid (a positive number - since the list is in
120000   ** ascending order).
120001   **
120002   ** The first docid written to the output is therefore encoded using the 
120003   ** same number of bytes as it is in whichever of the input lists it is
120004   ** read from. And each subsequent docid read from the same input list 
120005   ** consumes either the same or less bytes as it did in the input (since
120006   ** the difference between it and the previous value in the output must
120007   ** be a positive value less than or equal to the delta value read from 
120008   ** the input list). The same argument applies to all but the first docid
120009   ** read from the 'other' list. And to the contents of all position lists
120010   ** that will be copied and merged from the input to the output.
120011   **
120012   ** However, if the first docid copied to the output is a negative number,
120013   ** then the encoding of the first docid from the 'other' input list may
120014   ** be larger in the output than it was in the input (since the delta value
120015   ** may be a larger positive integer than the actual docid).
120016   **
120017   ** The space required to store the output is therefore the sum of the
120018   ** sizes of the two inputs, plus enough space for exactly one of the input
120019   ** docids to grow. 
120020   **
120021   ** A symetric argument may be made if the doclists are in descending 
120022   ** order.
120023   */
120024   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
120025   if( !aOut ) return SQLITE_NOMEM;
120026
120027   p = aOut;
120028   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
120029   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
120030   while( p1 || p2 ){
120031     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
120032
120033     if( p2 && p1 && iDiff==0 ){
120034       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
120035       fts3PoslistMerge(&p, &p1, &p2);
120036       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
120037       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
120038     }else if( !p2 || (p1 && iDiff<0) ){
120039       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
120040       fts3PoslistCopy(&p, &p1);
120041       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
120042     }else{
120043       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
120044       fts3PoslistCopy(&p, &p2);
120045       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
120046     }
120047   }
120048
120049   *paOut = aOut;
120050   *pnOut = (int)(p-aOut);
120051   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
120052   return SQLITE_OK;
120053 }
120054
120055 /*
120056 ** This function does a "phrase" merge of two doclists. In a phrase merge,
120057 ** the output contains a copy of each position from the right-hand input
120058 ** doclist for which there is a position in the left-hand input doclist
120059 ** exactly nDist tokens before it.
120060 **
120061 ** If the docids in the input doclists are sorted in ascending order,
120062 ** parameter bDescDoclist should be false. If they are sorted in ascending 
120063 ** order, it should be passed a non-zero value.
120064 **
120065 ** The right-hand input doclist is overwritten by this function.
120066 */
120067 static void fts3DoclistPhraseMerge(
120068   int bDescDoclist,               /* True if arguments are desc */
120069   int nDist,                      /* Distance from left to right (1=adjacent) */
120070   char *aLeft, int nLeft,         /* Left doclist */
120071   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
120072 ){
120073   sqlite3_int64 i1 = 0;
120074   sqlite3_int64 i2 = 0;
120075   sqlite3_int64 iPrev = 0;
120076   char *pEnd1 = &aLeft[nLeft];
120077   char *pEnd2 = &aRight[*pnRight];
120078   char *p1 = aLeft;
120079   char *p2 = aRight;
120080   char *p;
120081   int bFirstOut = 0;
120082   char *aOut = aRight;
120083
120084   assert( nDist>0 );
120085
120086   p = aOut;
120087   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
120088   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
120089
120090   while( p1 && p2 ){
120091     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
120092     if( iDiff==0 ){
120093       char *pSave = p;
120094       sqlite3_int64 iPrevSave = iPrev;
120095       int bFirstOutSave = bFirstOut;
120096
120097       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
120098       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
120099         p = pSave;
120100         iPrev = iPrevSave;
120101         bFirstOut = bFirstOutSave;
120102       }
120103       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
120104       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
120105     }else if( iDiff<0 ){
120106       fts3PoslistCopy(0, &p1);
120107       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
120108     }else{
120109       fts3PoslistCopy(0, &p2);
120110       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
120111     }
120112   }
120113
120114   *pnRight = (int)(p - aOut);
120115 }
120116
120117 /*
120118 ** Argument pList points to a position list nList bytes in size. This
120119 ** function checks to see if the position list contains any entries for
120120 ** a token in position 0 (of any column). If so, it writes argument iDelta
120121 ** to the output buffer pOut, followed by a position list consisting only
120122 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
120123 ** The value returned is the number of bytes written to pOut (if any).
120124 */
120125 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
120126   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
120127   char *pList,                    /* Position list (no 0x00 term) */
120128   int nList,                      /* Size of pList in bytes */
120129   char *pOut                      /* Write output here */
120130 ){
120131   int nOut = 0;
120132   int bWritten = 0;               /* True once iDelta has been written */
120133   char *p = pList;
120134   char *pEnd = &pList[nList];
120135
120136   if( *p!=0x01 ){
120137     if( *p==0x02 ){
120138       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
120139       pOut[nOut++] = 0x02;
120140       bWritten = 1;
120141     }
120142     fts3ColumnlistCopy(0, &p);
120143   }
120144
120145   while( p<pEnd && *p==0x01 ){
120146     sqlite3_int64 iCol;
120147     p++;
120148     p += sqlite3Fts3GetVarint(p, &iCol);
120149     if( *p==0x02 ){
120150       if( bWritten==0 ){
120151         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
120152         bWritten = 1;
120153       }
120154       pOut[nOut++] = 0x01;
120155       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
120156       pOut[nOut++] = 0x02;
120157     }
120158     fts3ColumnlistCopy(0, &p);
120159   }
120160   if( bWritten ){
120161     pOut[nOut++] = 0x00;
120162   }
120163
120164   return nOut;
120165 }
120166
120167
120168 /*
120169 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
120170 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
120171 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
120172 **
120173 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
120174 ** the responsibility of the caller to free any doclists left in the
120175 ** TermSelect.aaOutput[] array.
120176 */
120177 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
120178   char *aOut = 0;
120179   int nOut = 0;
120180   int i;
120181
120182   /* Loop through the doclists in the aaOutput[] array. Merge them all
120183   ** into a single doclist.
120184   */
120185   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
120186     if( pTS->aaOutput[i] ){
120187       if( !aOut ){
120188         aOut = pTS->aaOutput[i];
120189         nOut = pTS->anOutput[i];
120190         pTS->aaOutput[i] = 0;
120191       }else{
120192         int nNew;
120193         char *aNew;
120194
120195         int rc = fts3DoclistOrMerge(p->bDescIdx, 
120196             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
120197         );
120198         if( rc!=SQLITE_OK ){
120199           sqlite3_free(aOut);
120200           return rc;
120201         }
120202
120203         sqlite3_free(pTS->aaOutput[i]);
120204         sqlite3_free(aOut);
120205         pTS->aaOutput[i] = 0;
120206         aOut = aNew;
120207         nOut = nNew;
120208       }
120209     }
120210   }
120211
120212   pTS->aaOutput[0] = aOut;
120213   pTS->anOutput[0] = nOut;
120214   return SQLITE_OK;
120215 }
120216
120217 /*
120218 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
120219 ** as the first argument. The merge is an "OR" merge (see function
120220 ** fts3DoclistOrMerge() for details).
120221 **
120222 ** This function is called with the doclist for each term that matches
120223 ** a queried prefix. It merges all these doclists into one, the doclist
120224 ** for the specified prefix. Since there can be a very large number of
120225 ** doclists to merge, the merging is done pair-wise using the TermSelect
120226 ** object.
120227 **
120228 ** This function returns SQLITE_OK if the merge is successful, or an
120229 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
120230 */
120231 static int fts3TermSelectMerge(
120232   Fts3Table *p,                   /* FTS table handle */
120233   TermSelect *pTS,                /* TermSelect object to merge into */
120234   char *aDoclist,                 /* Pointer to doclist */
120235   int nDoclist                    /* Size of aDoclist in bytes */
120236 ){
120237   if( pTS->aaOutput[0]==0 ){
120238     /* If this is the first term selected, copy the doclist to the output
120239     ** buffer using memcpy(). */
120240     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
120241     pTS->anOutput[0] = nDoclist;
120242     if( pTS->aaOutput[0] ){
120243       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
120244     }else{
120245       return SQLITE_NOMEM;
120246     }
120247   }else{
120248     char *aMerge = aDoclist;
120249     int nMerge = nDoclist;
120250     int iOut;
120251
120252     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
120253       if( pTS->aaOutput[iOut]==0 ){
120254         assert( iOut>0 );
120255         pTS->aaOutput[iOut] = aMerge;
120256         pTS->anOutput[iOut] = nMerge;
120257         break;
120258       }else{
120259         char *aNew;
120260         int nNew;
120261
120262         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
120263             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
120264         );
120265         if( rc!=SQLITE_OK ){
120266           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
120267           return rc;
120268         }
120269
120270         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
120271         sqlite3_free(pTS->aaOutput[iOut]);
120272         pTS->aaOutput[iOut] = 0;
120273   
120274         aMerge = aNew;
120275         nMerge = nNew;
120276         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
120277           pTS->aaOutput[iOut] = aMerge;
120278           pTS->anOutput[iOut] = nMerge;
120279         }
120280       }
120281     }
120282   }
120283   return SQLITE_OK;
120284 }
120285
120286 /*
120287 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
120288 */
120289 static int fts3SegReaderCursorAppend(
120290   Fts3MultiSegReader *pCsr, 
120291   Fts3SegReader *pNew
120292 ){
120293   if( (pCsr->nSegment%16)==0 ){
120294     Fts3SegReader **apNew;
120295     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
120296     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
120297     if( !apNew ){
120298       sqlite3Fts3SegReaderFree(pNew);
120299       return SQLITE_NOMEM;
120300     }
120301     pCsr->apSegment = apNew;
120302   }
120303   pCsr->apSegment[pCsr->nSegment++] = pNew;
120304   return SQLITE_OK;
120305 }
120306
120307 /*
120308 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
120309 ** 8th argument.
120310 **
120311 ** This function returns SQLITE_OK if successful, or an SQLite error code
120312 ** otherwise.
120313 */
120314 static int fts3SegReaderCursor(
120315   Fts3Table *p,                   /* FTS3 table handle */
120316   int iLangid,                    /* Language id */
120317   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
120318   int iLevel,                     /* Level of segments to scan */
120319   const char *zTerm,              /* Term to query for */
120320   int nTerm,                      /* Size of zTerm in bytes */
120321   int isPrefix,                   /* True for a prefix search */
120322   int isScan,                     /* True to scan from zTerm to EOF */
120323   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
120324 ){
120325   int rc = SQLITE_OK;             /* Error code */
120326   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
120327   int rc2;                        /* Result of sqlite3_reset() */
120328
120329   /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
120330   ** for the pending-terms. If this is a scan, then this call must be being
120331   ** made by an fts4aux module, not an FTS table. In this case calling
120332   ** Fts3SegReaderPending might segfault, as the data structures used by 
120333   ** fts4aux are not completely populated. So it's easiest to filter these
120334   ** calls out here.  */
120335   if( iLevel<0 && p->aIndex ){
120336     Fts3SegReader *pSeg = 0;
120337     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
120338     if( rc==SQLITE_OK && pSeg ){
120339       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
120340     }
120341   }
120342
120343   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
120344     if( rc==SQLITE_OK ){
120345       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
120346     }
120347
120348     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
120349       Fts3SegReader *pSeg = 0;
120350
120351       /* Read the values returned by the SELECT into local variables. */
120352       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
120353       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
120354       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
120355       int nRoot = sqlite3_column_bytes(pStmt, 4);
120356       char const *zRoot = sqlite3_column_blob(pStmt, 4);
120357
120358       /* If zTerm is not NULL, and this segment is not stored entirely on its
120359       ** root node, the range of leaves scanned can be reduced. Do this. */
120360       if( iStartBlock && zTerm ){
120361         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
120362         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
120363         if( rc!=SQLITE_OK ) goto finished;
120364         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
120365       }
120366  
120367       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 
120368           (isPrefix==0 && isScan==0),
120369           iStartBlock, iLeavesEndBlock, 
120370           iEndBlock, zRoot, nRoot, &pSeg
120371       );
120372       if( rc!=SQLITE_OK ) goto finished;
120373       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
120374     }
120375   }
120376
120377  finished:
120378   rc2 = sqlite3_reset(pStmt);
120379   if( rc==SQLITE_DONE ) rc = rc2;
120380
120381   return rc;
120382 }
120383
120384 /*
120385 ** Set up a cursor object for iterating through a full-text index or a 
120386 ** single level therein.
120387 */
120388 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
120389   Fts3Table *p,                   /* FTS3 table handle */
120390   int iLangid,                    /* Language-id to search */
120391   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
120392   int iLevel,                     /* Level of segments to scan */
120393   const char *zTerm,              /* Term to query for */
120394   int nTerm,                      /* Size of zTerm in bytes */
120395   int isPrefix,                   /* True for a prefix search */
120396   int isScan,                     /* True to scan from zTerm to EOF */
120397   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
120398 ){
120399   assert( iIndex>=0 && iIndex<p->nIndex );
120400   assert( iLevel==FTS3_SEGCURSOR_ALL
120401       ||  iLevel==FTS3_SEGCURSOR_PENDING 
120402       ||  iLevel>=0
120403   );
120404   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
120405   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
120406   assert( isPrefix==0 || isScan==0 );
120407
120408   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
120409   return fts3SegReaderCursor(
120410       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
120411   );
120412 }
120413
120414 /*
120415 ** In addition to its current configuration, have the Fts3MultiSegReader
120416 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
120417 **
120418 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120419 */
120420 static int fts3SegReaderCursorAddZero(
120421   Fts3Table *p,                   /* FTS virtual table handle */
120422   int iLangid,
120423   const char *zTerm,              /* Term to scan doclist of */
120424   int nTerm,                      /* Number of bytes in zTerm */
120425   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
120426 ){
120427   return fts3SegReaderCursor(p, 
120428       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
120429   );
120430 }
120431
120432 /*
120433 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
120434 ** if isPrefix is true, to scan the doclist for all terms for which 
120435 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
120436 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
120437 ** an SQLite error code.
120438 **
120439 ** It is the responsibility of the caller to free this object by eventually
120440 ** passing it to fts3SegReaderCursorFree() 
120441 **
120442 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120443 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
120444 */
120445 static int fts3TermSegReaderCursor(
120446   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
120447   const char *zTerm,              /* Term to query for */
120448   int nTerm,                      /* Size of zTerm in bytes */
120449   int isPrefix,                   /* True for a prefix search */
120450   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
120451 ){
120452   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
120453   int rc = SQLITE_NOMEM;          /* Return code */
120454
120455   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
120456   if( pSegcsr ){
120457     int i;
120458     int bFound = 0;               /* True once an index has been found */
120459     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
120460
120461     if( isPrefix ){
120462       for(i=1; bFound==0 && i<p->nIndex; i++){
120463         if( p->aIndex[i].nPrefix==nTerm ){
120464           bFound = 1;
120465           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
120466               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
120467           );
120468           pSegcsr->bLookup = 1;
120469         }
120470       }
120471
120472       for(i=1; bFound==0 && i<p->nIndex; i++){
120473         if( p->aIndex[i].nPrefix==nTerm+1 ){
120474           bFound = 1;
120475           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
120476               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
120477           );
120478           if( rc==SQLITE_OK ){
120479             rc = fts3SegReaderCursorAddZero(
120480                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
120481             );
120482           }
120483         }
120484       }
120485     }
120486
120487     if( bFound==0 ){
120488       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
120489           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
120490       );
120491       pSegcsr->bLookup = !isPrefix;
120492     }
120493   }
120494
120495   *ppSegcsr = pSegcsr;
120496   return rc;
120497 }
120498
120499 /*
120500 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
120501 */
120502 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
120503   sqlite3Fts3SegReaderFinish(pSegcsr);
120504   sqlite3_free(pSegcsr);
120505 }
120506
120507 /*
120508 ** This function retrieves the doclist for the specified term (or term
120509 ** prefix) from the database.
120510 */
120511 static int fts3TermSelect(
120512   Fts3Table *p,                   /* Virtual table handle */
120513   Fts3PhraseToken *pTok,          /* Token to query for */
120514   int iColumn,                    /* Column to query (or -ve for all columns) */
120515   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
120516   char **ppOut                    /* OUT: Malloced result buffer */
120517 ){
120518   int rc;                         /* Return code */
120519   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
120520   TermSelect tsc;                 /* Object for pair-wise doclist merging */
120521   Fts3SegFilter filter;           /* Segment term filter configuration */
120522
120523   pSegcsr = pTok->pSegcsr;
120524   memset(&tsc, 0, sizeof(TermSelect));
120525
120526   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
120527         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
120528         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
120529         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
120530   filter.iCol = iColumn;
120531   filter.zTerm = pTok->z;
120532   filter.nTerm = pTok->n;
120533
120534   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
120535   while( SQLITE_OK==rc
120536       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
120537   ){
120538     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
120539   }
120540
120541   if( rc==SQLITE_OK ){
120542     rc = fts3TermSelectFinishMerge(p, &tsc);
120543   }
120544   if( rc==SQLITE_OK ){
120545     *ppOut = tsc.aaOutput[0];
120546     *pnOut = tsc.anOutput[0];
120547   }else{
120548     int i;
120549     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
120550       sqlite3_free(tsc.aaOutput[i]);
120551     }
120552   }
120553
120554   fts3SegReaderCursorFree(pSegcsr);
120555   pTok->pSegcsr = 0;
120556   return rc;
120557 }
120558
120559 /*
120560 ** This function counts the total number of docids in the doclist stored
120561 ** in buffer aList[], size nList bytes.
120562 **
120563 ** If the isPoslist argument is true, then it is assumed that the doclist
120564 ** contains a position-list following each docid. Otherwise, it is assumed
120565 ** that the doclist is simply a list of docids stored as delta encoded 
120566 ** varints.
120567 */
120568 static int fts3DoclistCountDocids(char *aList, int nList){
120569   int nDoc = 0;                   /* Return value */
120570   if( aList ){
120571     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
120572     char *p = aList;              /* Cursor */
120573     while( p<aEnd ){
120574       nDoc++;
120575       while( (*p++)&0x80 );     /* Skip docid varint */
120576       fts3PoslistCopy(0, &p);   /* Skip over position list */
120577     }
120578   }
120579
120580   return nDoc;
120581 }
120582
120583 /*
120584 ** Advance the cursor to the next row in the %_content table that
120585 ** matches the search criteria.  For a MATCH search, this will be
120586 ** the next row that matches. For a full-table scan, this will be
120587 ** simply the next row in the %_content table.  For a docid lookup,
120588 ** this routine simply sets the EOF flag.
120589 **
120590 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
120591 ** even if we reach end-of-file.  The fts3EofMethod() will be called
120592 ** subsequently to determine whether or not an EOF was hit.
120593 */
120594 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
120595   int rc;
120596   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
120597   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
120598     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
120599       pCsr->isEof = 1;
120600       rc = sqlite3_reset(pCsr->pStmt);
120601     }else{
120602       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
120603       rc = SQLITE_OK;
120604     }
120605   }else{
120606     rc = fts3EvalNext((Fts3Cursor *)pCursor);
120607   }
120608   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120609   return rc;
120610 }
120611
120612 /*
120613 ** This is the xFilter interface for the virtual table.  See
120614 ** the virtual table xFilter method documentation for additional
120615 ** information.
120616 **
120617 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
120618 ** the %_content table.
120619 **
120620 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
120621 ** in the %_content table.
120622 **
120623 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
120624 ** column on the left-hand side of the MATCH operator is column
120625 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
120626 ** side of the MATCH operator.
120627 */
120628 static int fts3FilterMethod(
120629   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
120630   int idxNum,                     /* Strategy index */
120631   const char *idxStr,             /* Unused */
120632   int nVal,                       /* Number of elements in apVal */
120633   sqlite3_value **apVal           /* Arguments for the indexing scheme */
120634 ){
120635   int rc;
120636   char *zSql;                     /* SQL statement used to access %_content */
120637   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
120638   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
120639
120640   UNUSED_PARAMETER(idxStr);
120641   UNUSED_PARAMETER(nVal);
120642
120643   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
120644   assert( nVal==0 || nVal==1 || nVal==2 );
120645   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
120646   assert( p->pSegments==0 );
120647
120648   /* In case the cursor has been used before, clear it now. */
120649   sqlite3_finalize(pCsr->pStmt);
120650   sqlite3_free(pCsr->aDoclist);
120651   sqlite3Fts3ExprFree(pCsr->pExpr);
120652   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
120653
120654   if( idxStr ){
120655     pCsr->bDesc = (idxStr[0]=='D');
120656   }else{
120657     pCsr->bDesc = p->bDescIdx;
120658   }
120659   pCsr->eSearch = (i16)idxNum;
120660
120661   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
120662     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
120663     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
120664
120665     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
120666       return SQLITE_NOMEM;
120667     }
120668
120669     pCsr->iLangid = 0;
120670     if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
120671
120672     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
120673         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
120674     );
120675     if( rc!=SQLITE_OK ){
120676       if( rc==SQLITE_ERROR ){
120677         static const char *zErr = "malformed MATCH expression: [%s]";
120678         p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
120679       }
120680       return rc;
120681     }
120682
120683     rc = sqlite3Fts3ReadLock(p);
120684     if( rc!=SQLITE_OK ) return rc;
120685
120686     rc = fts3EvalStart(pCsr);
120687
120688     sqlite3Fts3SegmentsClose(p);
120689     if( rc!=SQLITE_OK ) return rc;
120690     pCsr->pNextId = pCsr->aDoclist;
120691     pCsr->iPrevId = 0;
120692   }
120693
120694   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
120695   ** statement loops through all rows of the %_content table. For a
120696   ** full-text query or docid lookup, the statement retrieves a single
120697   ** row by docid.
120698   */
120699   if( idxNum==FTS3_FULLSCAN_SEARCH ){
120700     zSql = sqlite3_mprintf(
120701         "SELECT %s ORDER BY rowid %s",
120702         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
120703     );
120704     if( zSql ){
120705       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
120706       sqlite3_free(zSql);
120707     }else{
120708       rc = SQLITE_NOMEM;
120709     }
120710   }else if( idxNum==FTS3_DOCID_SEARCH ){
120711     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
120712     if( rc==SQLITE_OK ){
120713       rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
120714     }
120715   }
120716   if( rc!=SQLITE_OK ) return rc;
120717
120718   return fts3NextMethod(pCursor);
120719 }
120720
120721 /* 
120722 ** This is the xEof method of the virtual table. SQLite calls this 
120723 ** routine to find out if it has reached the end of a result set.
120724 */
120725 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
120726   return ((Fts3Cursor *)pCursor)->isEof;
120727 }
120728
120729 /* 
120730 ** This is the xRowid method. The SQLite core calls this routine to
120731 ** retrieve the rowid for the current row of the result set. fts3
120732 ** exposes %_content.docid as the rowid for the virtual table. The
120733 ** rowid should be written to *pRowid.
120734 */
120735 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
120736   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
120737   *pRowid = pCsr->iPrevId;
120738   return SQLITE_OK;
120739 }
120740
120741 /* 
120742 ** This is the xColumn method, called by SQLite to request a value from
120743 ** the row that the supplied cursor currently points to.
120744 **
120745 ** If:
120746 **
120747 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
120748 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
120749 **   (iCol == p->nColumn+1) -> Docid column
120750 **   (iCol == p->nColumn+2) -> Langid column
120751 */
120752 static int fts3ColumnMethod(
120753   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
120754   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
120755   int iCol                        /* Index of column to read value from */
120756 ){
120757   int rc = SQLITE_OK;             /* Return Code */
120758   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
120759   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
120760
120761   /* The column value supplied by SQLite must be in range. */
120762   assert( iCol>=0 && iCol<=p->nColumn+2 );
120763
120764   if( iCol==p->nColumn+1 ){
120765     /* This call is a request for the "docid" column. Since "docid" is an 
120766     ** alias for "rowid", use the xRowid() method to obtain the value.
120767     */
120768     sqlite3_result_int64(pCtx, pCsr->iPrevId);
120769   }else if( iCol==p->nColumn ){
120770     /* The extra column whose name is the same as the table.
120771     ** Return a blob which is a pointer to the cursor.  */
120772     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
120773   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
120774     sqlite3_result_int64(pCtx, pCsr->iLangid);
120775   }else{
120776     /* The requested column is either a user column (one that contains 
120777     ** indexed data), or the language-id column.  */
120778     rc = fts3CursorSeek(0, pCsr);
120779
120780     if( rc==SQLITE_OK ){
120781       if( iCol==p->nColumn+2 ){
120782         int iLangid = 0;
120783         if( p->zLanguageid ){
120784           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
120785         }
120786         sqlite3_result_int(pCtx, iLangid);
120787       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
120788         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
120789       }
120790     }
120791   }
120792
120793   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120794   return rc;
120795 }
120796
120797 /* 
120798 ** This function is the implementation of the xUpdate callback used by 
120799 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
120800 ** inserted, updated or deleted.
120801 */
120802 static int fts3UpdateMethod(
120803   sqlite3_vtab *pVtab,            /* Virtual table handle */
120804   int nArg,                       /* Size of argument array */
120805   sqlite3_value **apVal,          /* Array of arguments */
120806   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
120807 ){
120808   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
120809 }
120810
120811 /*
120812 ** Implementation of xSync() method. Flush the contents of the pending-terms
120813 ** hash-table to the database.
120814 */
120815 static int fts3SyncMethod(sqlite3_vtab *pVtab){
120816
120817   /* Following an incremental-merge operation, assuming that the input
120818   ** segments are not completely consumed (the usual case), they are updated
120819   ** in place to remove the entries that have already been merged. This
120820   ** involves updating the leaf block that contains the smallest unmerged
120821   ** entry and each block (if any) between the leaf and the root node. So
120822   ** if the height of the input segment b-trees is N, and input segments
120823   ** are merged eight at a time, updating the input segments at the end
120824   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
120825   ** small - often between 0 and 2. So the overhead of the incremental
120826   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
120827   ** dwarfing the actual productive work accomplished, the incremental merge
120828   ** is only attempted if it will write at least 64 leaf blocks. Hence
120829   ** nMinMerge.
120830   **
120831   ** Of course, updating the input segments also involves deleting a bunch
120832   ** of blocks from the segments table. But this is not considered overhead
120833   ** as it would also be required by a crisis-merge that used the same input 
120834   ** segments.
120835   */
120836   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
120837
120838   Fts3Table *p = (Fts3Table*)pVtab;
120839   int rc = sqlite3Fts3PendingTermsFlush(p);
120840
120841   if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
120842     int mxLevel = 0;              /* Maximum relative level value in db */
120843     int A;                        /* Incr-merge parameter A */
120844
120845     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
120846     assert( rc==SQLITE_OK || mxLevel==0 );
120847     A = p->nLeafAdd * mxLevel;
120848     A += (A/2);
120849     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
120850   }
120851   sqlite3Fts3SegmentsClose(p);
120852   return rc;
120853 }
120854
120855 /*
120856 ** Implementation of xBegin() method. This is a no-op.
120857 */
120858 static int fts3BeginMethod(sqlite3_vtab *pVtab){
120859   Fts3Table *p = (Fts3Table*)pVtab;
120860   UNUSED_PARAMETER(pVtab);
120861   assert( p->pSegments==0 );
120862   assert( p->nPendingData==0 );
120863   assert( p->inTransaction!=1 );
120864   TESTONLY( p->inTransaction = 1 );
120865   TESTONLY( p->mxSavepoint = -1; );
120866   p->nLeafAdd = 0;
120867   return SQLITE_OK;
120868 }
120869
120870 /*
120871 ** Implementation of xCommit() method. This is a no-op. The contents of
120872 ** the pending-terms hash-table have already been flushed into the database
120873 ** by fts3SyncMethod().
120874 */
120875 static int fts3CommitMethod(sqlite3_vtab *pVtab){
120876   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
120877   UNUSED_PARAMETER(pVtab);
120878   assert( p->nPendingData==0 );
120879   assert( p->inTransaction!=0 );
120880   assert( p->pSegments==0 );
120881   TESTONLY( p->inTransaction = 0 );
120882   TESTONLY( p->mxSavepoint = -1; );
120883   return SQLITE_OK;
120884 }
120885
120886 /*
120887 ** Implementation of xRollback(). Discard the contents of the pending-terms
120888 ** hash-table. Any changes made to the database are reverted by SQLite.
120889 */
120890 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
120891   Fts3Table *p = (Fts3Table*)pVtab;
120892   sqlite3Fts3PendingTermsClear(p);
120893   assert( p->inTransaction!=0 );
120894   TESTONLY( p->inTransaction = 0 );
120895   TESTONLY( p->mxSavepoint = -1; );
120896   return SQLITE_OK;
120897 }
120898
120899 /*
120900 ** When called, *ppPoslist must point to the byte immediately following the
120901 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
120902 ** moves *ppPoslist so that it instead points to the first byte of the
120903 ** same position list.
120904 */
120905 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
120906   char *p = &(*ppPoslist)[-2];
120907   char c = 0;
120908
120909   while( p>pStart && (c=*p--)==0 );
120910   while( p>pStart && (*p & 0x80) | c ){ 
120911     c = *p--; 
120912   }
120913   if( p>pStart ){ p = &p[2]; }
120914   while( *p++&0x80 );
120915   *ppPoslist = p;
120916 }
120917
120918 /*
120919 ** Helper function used by the implementation of the overloaded snippet(),
120920 ** offsets() and optimize() SQL functions.
120921 **
120922 ** If the value passed as the third argument is a blob of size
120923 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
120924 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
120925 ** message is written to context pContext and SQLITE_ERROR returned. The
120926 ** string passed via zFunc is used as part of the error message.
120927 */
120928 static int fts3FunctionArg(
120929   sqlite3_context *pContext,      /* SQL function call context */
120930   const char *zFunc,              /* Function name */
120931   sqlite3_value *pVal,            /* argv[0] passed to function */
120932   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
120933 ){
120934   Fts3Cursor *pRet;
120935   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
120936    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
120937   ){
120938     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
120939     sqlite3_result_error(pContext, zErr, -1);
120940     sqlite3_free(zErr);
120941     return SQLITE_ERROR;
120942   }
120943   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
120944   *ppCsr = pRet;
120945   return SQLITE_OK;
120946 }
120947
120948 /*
120949 ** Implementation of the snippet() function for FTS3
120950 */
120951 static void fts3SnippetFunc(
120952   sqlite3_context *pContext,      /* SQLite function call context */
120953   int nVal,                       /* Size of apVal[] array */
120954   sqlite3_value **apVal           /* Array of arguments */
120955 ){
120956   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
120957   const char *zStart = "<b>";
120958   const char *zEnd = "</b>";
120959   const char *zEllipsis = "<b>...</b>";
120960   int iCol = -1;
120961   int nToken = 15;                /* Default number of tokens in snippet */
120962
120963   /* There must be at least one argument passed to this function (otherwise
120964   ** the non-overloaded version would have been called instead of this one).
120965   */
120966   assert( nVal>=1 );
120967
120968   if( nVal>6 ){
120969     sqlite3_result_error(pContext, 
120970         "wrong number of arguments to function snippet()", -1);
120971     return;
120972   }
120973   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
120974
120975   switch( nVal ){
120976     case 6: nToken = sqlite3_value_int(apVal[5]);
120977     case 5: iCol = sqlite3_value_int(apVal[4]);
120978     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
120979     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
120980     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
120981   }
120982   if( !zEllipsis || !zEnd || !zStart ){
120983     sqlite3_result_error_nomem(pContext);
120984   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
120985     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
120986   }
120987 }
120988
120989 /*
120990 ** Implementation of the offsets() function for FTS3
120991 */
120992 static void fts3OffsetsFunc(
120993   sqlite3_context *pContext,      /* SQLite function call context */
120994   int nVal,                       /* Size of argument array */
120995   sqlite3_value **apVal           /* Array of arguments */
120996 ){
120997   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
120998
120999   UNUSED_PARAMETER(nVal);
121000
121001   assert( nVal==1 );
121002   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
121003   assert( pCsr );
121004   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
121005     sqlite3Fts3Offsets(pContext, pCsr);
121006   }
121007 }
121008
121009 /* 
121010 ** Implementation of the special optimize() function for FTS3. This 
121011 ** function merges all segments in the database to a single segment.
121012 ** Example usage is:
121013 **
121014 **   SELECT optimize(t) FROM t LIMIT 1;
121015 **
121016 ** where 't' is the name of an FTS3 table.
121017 */
121018 static void fts3OptimizeFunc(
121019   sqlite3_context *pContext,      /* SQLite function call context */
121020   int nVal,                       /* Size of argument array */
121021   sqlite3_value **apVal           /* Array of arguments */
121022 ){
121023   int rc;                         /* Return code */
121024   Fts3Table *p;                   /* Virtual table handle */
121025   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
121026
121027   UNUSED_PARAMETER(nVal);
121028
121029   assert( nVal==1 );
121030   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
121031   p = (Fts3Table *)pCursor->base.pVtab;
121032   assert( p );
121033
121034   rc = sqlite3Fts3Optimize(p);
121035
121036   switch( rc ){
121037     case SQLITE_OK:
121038       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
121039       break;
121040     case SQLITE_DONE:
121041       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
121042       break;
121043     default:
121044       sqlite3_result_error_code(pContext, rc);
121045       break;
121046   }
121047 }
121048
121049 /*
121050 ** Implementation of the matchinfo() function for FTS3
121051 */
121052 static void fts3MatchinfoFunc(
121053   sqlite3_context *pContext,      /* SQLite function call context */
121054   int nVal,                       /* Size of argument array */
121055   sqlite3_value **apVal           /* Array of arguments */
121056 ){
121057   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
121058   assert( nVal==1 || nVal==2 );
121059   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
121060     const char *zArg = 0;
121061     if( nVal>1 ){
121062       zArg = (const char *)sqlite3_value_text(apVal[1]);
121063     }
121064     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
121065   }
121066 }
121067
121068 /*
121069 ** This routine implements the xFindFunction method for the FTS3
121070 ** virtual table.
121071 */
121072 static int fts3FindFunctionMethod(
121073   sqlite3_vtab *pVtab,            /* Virtual table handle */
121074   int nArg,                       /* Number of SQL function arguments */
121075   const char *zName,              /* Name of SQL function */
121076   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
121077   void **ppArg                    /* Unused */
121078 ){
121079   struct Overloaded {
121080     const char *zName;
121081     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
121082   } aOverload[] = {
121083     { "snippet", fts3SnippetFunc },
121084     { "offsets", fts3OffsetsFunc },
121085     { "optimize", fts3OptimizeFunc },
121086     { "matchinfo", fts3MatchinfoFunc },
121087   };
121088   int i;                          /* Iterator variable */
121089
121090   UNUSED_PARAMETER(pVtab);
121091   UNUSED_PARAMETER(nArg);
121092   UNUSED_PARAMETER(ppArg);
121093
121094   for(i=0; i<SizeofArray(aOverload); i++){
121095     if( strcmp(zName, aOverload[i].zName)==0 ){
121096       *pxFunc = aOverload[i].xFunc;
121097       return 1;
121098     }
121099   }
121100
121101   /* No function of the specified name was found. Return 0. */
121102   return 0;
121103 }
121104
121105 /*
121106 ** Implementation of FTS3 xRename method. Rename an fts3 table.
121107 */
121108 static int fts3RenameMethod(
121109   sqlite3_vtab *pVtab,            /* Virtual table handle */
121110   const char *zName               /* New name of table */
121111 ){
121112   Fts3Table *p = (Fts3Table *)pVtab;
121113   sqlite3 *db = p->db;            /* Database connection */
121114   int rc;                         /* Return Code */
121115
121116   /* As it happens, the pending terms table is always empty here. This is
121117   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
121118   ** always opens a savepoint transaction. And the xSavepoint() method 
121119   ** flushes the pending terms table. But leave the (no-op) call to
121120   ** PendingTermsFlush() in in case that changes.
121121   */
121122   assert( p->nPendingData==0 );
121123   rc = sqlite3Fts3PendingTermsFlush(p);
121124
121125   if( p->zContentTbl==0 ){
121126     fts3DbExec(&rc, db,
121127       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
121128       p->zDb, p->zName, zName
121129     );
121130   }
121131
121132   if( p->bHasDocsize ){
121133     fts3DbExec(&rc, db,
121134       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
121135       p->zDb, p->zName, zName
121136     );
121137   }
121138   if( p->bHasStat ){
121139     fts3DbExec(&rc, db,
121140       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
121141       p->zDb, p->zName, zName
121142     );
121143   }
121144   fts3DbExec(&rc, db,
121145     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
121146     p->zDb, p->zName, zName
121147   );
121148   fts3DbExec(&rc, db,
121149     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
121150     p->zDb, p->zName, zName
121151   );
121152   return rc;
121153 }
121154
121155 /*
121156 ** The xSavepoint() method.
121157 **
121158 ** Flush the contents of the pending-terms table to disk.
121159 */
121160 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
121161   int rc = SQLITE_OK;
121162   UNUSED_PARAMETER(iSavepoint);
121163   assert( ((Fts3Table *)pVtab)->inTransaction );
121164   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
121165   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
121166   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
121167     rc = fts3SyncMethod(pVtab);
121168   }
121169   return rc;
121170 }
121171
121172 /*
121173 ** The xRelease() method.
121174 **
121175 ** This is a no-op.
121176 */
121177 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
121178   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
121179   UNUSED_PARAMETER(iSavepoint);
121180   UNUSED_PARAMETER(pVtab);
121181   assert( p->inTransaction );
121182   assert( p->mxSavepoint >= iSavepoint );
121183   TESTONLY( p->mxSavepoint = iSavepoint-1 );
121184   return SQLITE_OK;
121185 }
121186
121187 /*
121188 ** The xRollbackTo() method.
121189 **
121190 ** Discard the contents of the pending terms table.
121191 */
121192 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
121193   Fts3Table *p = (Fts3Table*)pVtab;
121194   UNUSED_PARAMETER(iSavepoint);
121195   assert( p->inTransaction );
121196   assert( p->mxSavepoint >= iSavepoint );
121197   TESTONLY( p->mxSavepoint = iSavepoint );
121198   sqlite3Fts3PendingTermsClear(p);
121199   return SQLITE_OK;
121200 }
121201
121202 static const sqlite3_module fts3Module = {
121203   /* iVersion      */ 2,
121204   /* xCreate       */ fts3CreateMethod,
121205   /* xConnect      */ fts3ConnectMethod,
121206   /* xBestIndex    */ fts3BestIndexMethod,
121207   /* xDisconnect   */ fts3DisconnectMethod,
121208   /* xDestroy      */ fts3DestroyMethod,
121209   /* xOpen         */ fts3OpenMethod,
121210   /* xClose        */ fts3CloseMethod,
121211   /* xFilter       */ fts3FilterMethod,
121212   /* xNext         */ fts3NextMethod,
121213   /* xEof          */ fts3EofMethod,
121214   /* xColumn       */ fts3ColumnMethod,
121215   /* xRowid        */ fts3RowidMethod,
121216   /* xUpdate       */ fts3UpdateMethod,
121217   /* xBegin        */ fts3BeginMethod,
121218   /* xSync         */ fts3SyncMethod,
121219   /* xCommit       */ fts3CommitMethod,
121220   /* xRollback     */ fts3RollbackMethod,
121221   /* xFindFunction */ fts3FindFunctionMethod,
121222   /* xRename */       fts3RenameMethod,
121223   /* xSavepoint    */ fts3SavepointMethod,
121224   /* xRelease      */ fts3ReleaseMethod,
121225   /* xRollbackTo   */ fts3RollbackToMethod,
121226 };
121227
121228 /*
121229 ** This function is registered as the module destructor (called when an
121230 ** FTS3 enabled database connection is closed). It frees the memory
121231 ** allocated for the tokenizer hash table.
121232 */
121233 static void hashDestroy(void *p){
121234   Fts3Hash *pHash = (Fts3Hash *)p;
121235   sqlite3Fts3HashClear(pHash);
121236   sqlite3_free(pHash);
121237 }
121238
121239 /*
121240 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
121241 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
121242 ** respectively. The following three forward declarations are for functions
121243 ** declared in these files used to retrieve the respective implementations.
121244 **
121245 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
121246 ** to by the argument to point to the "simple" tokenizer implementation.
121247 ** And so on.
121248 */
121249 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
121250 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
121251 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
121252 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
121253 #endif
121254 #ifdef SQLITE_ENABLE_ICU
121255 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
121256 #endif
121257
121258 /*
121259 ** Initialize the fts3 extension. If this extension is built as part
121260 ** of the sqlite library, then this function is called directly by
121261 ** SQLite. If fts3 is built as a dynamically loadable extension, this
121262 ** function is called by the sqlite3_extension_init() entry point.
121263 */
121264 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
121265   int rc = SQLITE_OK;
121266   Fts3Hash *pHash = 0;
121267   const sqlite3_tokenizer_module *pSimple = 0;
121268   const sqlite3_tokenizer_module *pPorter = 0;
121269 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
121270   const sqlite3_tokenizer_module *pUnicode = 0;
121271 #endif
121272
121273 #ifdef SQLITE_ENABLE_ICU
121274   const sqlite3_tokenizer_module *pIcu = 0;
121275   sqlite3Fts3IcuTokenizerModule(&pIcu);
121276 #endif
121277
121278 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
121279   sqlite3Fts3UnicodeTokenizer(&pUnicode);
121280 #endif
121281
121282 #ifdef SQLITE_TEST
121283   rc = sqlite3Fts3InitTerm(db);
121284   if( rc!=SQLITE_OK ) return rc;
121285 #endif
121286
121287   rc = sqlite3Fts3InitAux(db);
121288   if( rc!=SQLITE_OK ) return rc;
121289
121290   sqlite3Fts3SimpleTokenizerModule(&pSimple);
121291   sqlite3Fts3PorterTokenizerModule(&pPorter);
121292
121293   /* Allocate and initialize the hash-table used to store tokenizers. */
121294   pHash = sqlite3_malloc(sizeof(Fts3Hash));
121295   if( !pHash ){
121296     rc = SQLITE_NOMEM;
121297   }else{
121298     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
121299   }
121300
121301   /* Load the built-in tokenizers into the hash table */
121302   if( rc==SQLITE_OK ){
121303     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
121304      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
121305
121306 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
121307      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) 
121308 #endif
121309 #ifdef SQLITE_ENABLE_ICU
121310      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
121311 #endif
121312     ){
121313       rc = SQLITE_NOMEM;
121314     }
121315   }
121316
121317 #ifdef SQLITE_TEST
121318   if( rc==SQLITE_OK ){
121319     rc = sqlite3Fts3ExprInitTestInterface(db);
121320   }
121321 #endif
121322
121323   /* Create the virtual table wrapper around the hash-table and overload 
121324   ** the two scalar functions. If this is successful, register the
121325   ** module with sqlite.
121326   */
121327   if( SQLITE_OK==rc 
121328    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
121329    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
121330    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
121331    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
121332    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
121333    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
121334   ){
121335     rc = sqlite3_create_module_v2(
121336         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
121337     );
121338     if( rc==SQLITE_OK ){
121339       rc = sqlite3_create_module_v2(
121340           db, "fts4", &fts3Module, (void *)pHash, 0
121341       );
121342     }
121343     return rc;
121344   }
121345
121346   /* An error has occurred. Delete the hash table and return the error code. */
121347   assert( rc!=SQLITE_OK );
121348   if( pHash ){
121349     sqlite3Fts3HashClear(pHash);
121350     sqlite3_free(pHash);
121351   }
121352   return rc;
121353 }
121354
121355 /*
121356 ** Allocate an Fts3MultiSegReader for each token in the expression headed
121357 ** by pExpr. 
121358 **
121359 ** An Fts3SegReader object is a cursor that can seek or scan a range of
121360 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
121361 ** Fts3SegReader objects internally to provide an interface to seek or scan
121362 ** within the union of all segments of a b-tree. Hence the name.
121363 **
121364 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
121365 ** segment b-tree (if the term is not a prefix or it is a prefix for which
121366 ** there exists prefix b-tree of the right length) then it may be traversed
121367 ** and merged incrementally. Otherwise, it has to be merged into an in-memory 
121368 ** doclist and then traversed.
121369 */
121370 static void fts3EvalAllocateReaders(
121371   Fts3Cursor *pCsr,               /* FTS cursor handle */
121372   Fts3Expr *pExpr,                /* Allocate readers for this expression */
121373   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
121374   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
121375   int *pRc                        /* IN/OUT: Error code */
121376 ){
121377   if( pExpr && SQLITE_OK==*pRc ){
121378     if( pExpr->eType==FTSQUERY_PHRASE ){
121379       int i;
121380       int nToken = pExpr->pPhrase->nToken;
121381       *pnToken += nToken;
121382       for(i=0; i<nToken; i++){
121383         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
121384         int rc = fts3TermSegReaderCursor(pCsr, 
121385             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
121386         );
121387         if( rc!=SQLITE_OK ){
121388           *pRc = rc;
121389           return;
121390         }
121391       }
121392       assert( pExpr->pPhrase->iDoclistToken==0 );
121393       pExpr->pPhrase->iDoclistToken = -1;
121394     }else{
121395       *pnOr += (pExpr->eType==FTSQUERY_OR);
121396       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
121397       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
121398     }
121399   }
121400 }
121401
121402 /*
121403 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
121404 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
121405 **
121406 ** This function assumes that pList points to a buffer allocated using
121407 ** sqlite3_malloc(). This function takes responsibility for eventually
121408 ** freeing the buffer.
121409 */
121410 static void fts3EvalPhraseMergeToken(
121411   Fts3Table *pTab,                /* FTS Table pointer */
121412   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
121413   int iToken,                     /* Token pList/nList corresponds to */
121414   char *pList,                    /* Pointer to doclist */
121415   int nList                       /* Number of bytes in pList */
121416 ){
121417   assert( iToken!=p->iDoclistToken );
121418
121419   if( pList==0 ){
121420     sqlite3_free(p->doclist.aAll);
121421     p->doclist.aAll = 0;
121422     p->doclist.nAll = 0;
121423   }
121424
121425   else if( p->iDoclistToken<0 ){
121426     p->doclist.aAll = pList;
121427     p->doclist.nAll = nList;
121428   }
121429
121430   else if( p->doclist.aAll==0 ){
121431     sqlite3_free(pList);
121432   }
121433
121434   else {
121435     char *pLeft;
121436     char *pRight;
121437     int nLeft;
121438     int nRight;
121439     int nDiff;
121440
121441     if( p->iDoclistToken<iToken ){
121442       pLeft = p->doclist.aAll;
121443       nLeft = p->doclist.nAll;
121444       pRight = pList;
121445       nRight = nList;
121446       nDiff = iToken - p->iDoclistToken;
121447     }else{
121448       pRight = p->doclist.aAll;
121449       nRight = p->doclist.nAll;
121450       pLeft = pList;
121451       nLeft = nList;
121452       nDiff = p->iDoclistToken - iToken;
121453     }
121454
121455     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
121456     sqlite3_free(pLeft);
121457     p->doclist.aAll = pRight;
121458     p->doclist.nAll = nRight;
121459   }
121460
121461   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
121462 }
121463
121464 /*
121465 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
121466 ** does not take deferred tokens into account.
121467 **
121468 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
121469 */
121470 static int fts3EvalPhraseLoad(
121471   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121472   Fts3Phrase *p                   /* Phrase object */
121473 ){
121474   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121475   int iToken;
121476   int rc = SQLITE_OK;
121477
121478   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
121479     Fts3PhraseToken *pToken = &p->aToken[iToken];
121480     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
121481
121482     if( pToken->pSegcsr ){
121483       int nThis = 0;
121484       char *pThis = 0;
121485       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
121486       if( rc==SQLITE_OK ){
121487         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
121488       }
121489     }
121490     assert( pToken->pSegcsr==0 );
121491   }
121492
121493   return rc;
121494 }
121495
121496 /*
121497 ** This function is called on each phrase after the position lists for
121498 ** any deferred tokens have been loaded into memory. It updates the phrases
121499 ** current position list to include only those positions that are really
121500 ** instances of the phrase (after considering deferred tokens). If this
121501 ** means that the phrase does not appear in the current row, doclist.pList
121502 ** and doclist.nList are both zeroed.
121503 **
121504 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
121505 */
121506 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
121507   int iToken;                     /* Used to iterate through phrase tokens */
121508   char *aPoslist = 0;             /* Position list for deferred tokens */
121509   int nPoslist = 0;               /* Number of bytes in aPoslist */
121510   int iPrev = -1;                 /* Token number of previous deferred token */
121511
121512   assert( pPhrase->doclist.bFreeList==0 );
121513
121514   for(iToken=0; iToken<pPhrase->nToken; iToken++){
121515     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
121516     Fts3DeferredToken *pDeferred = pToken->pDeferred;
121517
121518     if( pDeferred ){
121519       char *pList;
121520       int nList;
121521       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
121522       if( rc!=SQLITE_OK ) return rc;
121523
121524       if( pList==0 ){
121525         sqlite3_free(aPoslist);
121526         pPhrase->doclist.pList = 0;
121527         pPhrase->doclist.nList = 0;
121528         return SQLITE_OK;
121529
121530       }else if( aPoslist==0 ){
121531         aPoslist = pList;
121532         nPoslist = nList;
121533
121534       }else{
121535         char *aOut = pList;
121536         char *p1 = aPoslist;
121537         char *p2 = aOut;
121538
121539         assert( iPrev>=0 );
121540         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
121541         sqlite3_free(aPoslist);
121542         aPoslist = pList;
121543         nPoslist = (int)(aOut - aPoslist);
121544         if( nPoslist==0 ){
121545           sqlite3_free(aPoslist);
121546           pPhrase->doclist.pList = 0;
121547           pPhrase->doclist.nList = 0;
121548           return SQLITE_OK;
121549         }
121550       }
121551       iPrev = iToken;
121552     }
121553   }
121554
121555   if( iPrev>=0 ){
121556     int nMaxUndeferred = pPhrase->iDoclistToken;
121557     if( nMaxUndeferred<0 ){
121558       pPhrase->doclist.pList = aPoslist;
121559       pPhrase->doclist.nList = nPoslist;
121560       pPhrase->doclist.iDocid = pCsr->iPrevId;
121561       pPhrase->doclist.bFreeList = 1;
121562     }else{
121563       int nDistance;
121564       char *p1;
121565       char *p2;
121566       char *aOut;
121567
121568       if( nMaxUndeferred>iPrev ){
121569         p1 = aPoslist;
121570         p2 = pPhrase->doclist.pList;
121571         nDistance = nMaxUndeferred - iPrev;
121572       }else{
121573         p1 = pPhrase->doclist.pList;
121574         p2 = aPoslist;
121575         nDistance = iPrev - nMaxUndeferred;
121576       }
121577
121578       aOut = (char *)sqlite3_malloc(nPoslist+8);
121579       if( !aOut ){
121580         sqlite3_free(aPoslist);
121581         return SQLITE_NOMEM;
121582       }
121583       
121584       pPhrase->doclist.pList = aOut;
121585       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
121586         pPhrase->doclist.bFreeList = 1;
121587         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
121588       }else{
121589         sqlite3_free(aOut);
121590         pPhrase->doclist.pList = 0;
121591         pPhrase->doclist.nList = 0;
121592       }
121593       sqlite3_free(aPoslist);
121594     }
121595   }
121596
121597   return SQLITE_OK;
121598 }
121599
121600 /*
121601 ** This function is called for each Fts3Phrase in a full-text query 
121602 ** expression to initialize the mechanism for returning rows. Once this
121603 ** function has been called successfully on an Fts3Phrase, it may be
121604 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
121605 **
121606 ** If parameter bOptOk is true, then the phrase may (or may not) use the
121607 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
121608 ** memory within this call.
121609 **
121610 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
121611 */
121612 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
121613   int rc;                         /* Error code */
121614   Fts3PhraseToken *pFirst = &p->aToken[0];
121615   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121616
121617   if( pCsr->bDesc==pTab->bDescIdx 
121618    && bOptOk==1 
121619    && p->nToken==1 
121620    && pFirst->pSegcsr 
121621    && pFirst->pSegcsr->bLookup 
121622    && pFirst->bFirst==0
121623   ){
121624     /* Use the incremental approach. */
121625     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
121626     rc = sqlite3Fts3MsrIncrStart(
121627         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
121628     p->bIncr = 1;
121629
121630   }else{
121631     /* Load the full doclist for the phrase into memory. */
121632     rc = fts3EvalPhraseLoad(pCsr, p);
121633     p->bIncr = 0;
121634   }
121635
121636   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
121637   return rc;
121638 }
121639
121640 /*
121641 ** This function is used to iterate backwards (from the end to start) 
121642 ** through doclists. It is used by this module to iterate through phrase
121643 ** doclists in reverse and by the fts3_write.c module to iterate through
121644 ** pending-terms lists when writing to databases with "order=desc".
121645 **
121646 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
121647 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
121648 ** function iterates from the end of the doclist to the beginning.
121649 */
121650 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
121651   int bDescIdx,                   /* True if the doclist is desc */
121652   char *aDoclist,                 /* Pointer to entire doclist */
121653   int nDoclist,                   /* Length of aDoclist in bytes */
121654   char **ppIter,                  /* IN/OUT: Iterator pointer */
121655   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
121656   int *pnList,                    /* OUT: List length pointer */
121657   u8 *pbEof                       /* OUT: End-of-file flag */
121658 ){
121659   char *p = *ppIter;
121660
121661   assert( nDoclist>0 );
121662   assert( *pbEof==0 );
121663   assert( p || *piDocid==0 );
121664   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
121665
121666   if( p==0 ){
121667     sqlite3_int64 iDocid = 0;
121668     char *pNext = 0;
121669     char *pDocid = aDoclist;
121670     char *pEnd = &aDoclist[nDoclist];
121671     int iMul = 1;
121672
121673     while( pDocid<pEnd ){
121674       sqlite3_int64 iDelta;
121675       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
121676       iDocid += (iMul * iDelta);
121677       pNext = pDocid;
121678       fts3PoslistCopy(0, &pDocid);
121679       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
121680       iMul = (bDescIdx ? -1 : 1);
121681     }
121682
121683     *pnList = (int)(pEnd - pNext);
121684     *ppIter = pNext;
121685     *piDocid = iDocid;
121686   }else{
121687     int iMul = (bDescIdx ? -1 : 1);
121688     sqlite3_int64 iDelta;
121689     fts3GetReverseVarint(&p, aDoclist, &iDelta);
121690     *piDocid -= (iMul * iDelta);
121691
121692     if( p==aDoclist ){
121693       *pbEof = 1;
121694     }else{
121695       char *pSave = p;
121696       fts3ReversePoslist(aDoclist, &p);
121697       *pnList = (int)(pSave - p);
121698     }
121699     *ppIter = p;
121700   }
121701 }
121702
121703 /*
121704 ** Iterate forwards through a doclist.
121705 */
121706 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
121707   int bDescIdx,                   /* True if the doclist is desc */
121708   char *aDoclist,                 /* Pointer to entire doclist */
121709   int nDoclist,                   /* Length of aDoclist in bytes */
121710   char **ppIter,                  /* IN/OUT: Iterator pointer */
121711   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
121712   u8 *pbEof                       /* OUT: End-of-file flag */
121713 ){
121714   char *p = *ppIter;
121715
121716   assert( nDoclist>0 );
121717   assert( *pbEof==0 );
121718   assert( p || *piDocid==0 );
121719   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
121720
121721   if( p==0 ){
121722     p = aDoclist;
121723     p += sqlite3Fts3GetVarint(p, piDocid);
121724   }else{
121725     fts3PoslistCopy(0, &p);
121726     if( p>=&aDoclist[nDoclist] ){
121727       *pbEof = 1;
121728     }else{
121729       sqlite3_int64 iVar;
121730       p += sqlite3Fts3GetVarint(p, &iVar);
121731       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
121732     }
121733   }
121734
121735   *ppIter = p;
121736 }
121737
121738 /*
121739 ** Attempt to move the phrase iterator to point to the next matching docid. 
121740 ** If an error occurs, return an SQLite error code. Otherwise, return 
121741 ** SQLITE_OK.
121742 **
121743 ** If there is no "next" entry and no error occurs, then *pbEof is set to
121744 ** 1 before returning. Otherwise, if no error occurs and the iterator is
121745 ** successfully advanced, *pbEof is set to 0.
121746 */
121747 static int fts3EvalPhraseNext(
121748   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121749   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
121750   u8 *pbEof                       /* OUT: Set to 1 if EOF */
121751 ){
121752   int rc = SQLITE_OK;
121753   Fts3Doclist *pDL = &p->doclist;
121754   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121755
121756   if( p->bIncr ){
121757     assert( p->nToken==1 );
121758     assert( pDL->pNextDocid==0 );
121759     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
121760         &pDL->iDocid, &pDL->pList, &pDL->nList
121761     );
121762     if( rc==SQLITE_OK && !pDL->pList ){
121763       *pbEof = 1;
121764     }
121765   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
121766     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
121767         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
121768     );
121769     pDL->pList = pDL->pNextDocid;
121770   }else{
121771     char *pIter;                            /* Used to iterate through aAll */
121772     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
121773     if( pDL->pNextDocid ){
121774       pIter = pDL->pNextDocid;
121775     }else{
121776       pIter = pDL->aAll;
121777     }
121778
121779     if( pIter>=pEnd ){
121780       /* We have already reached the end of this doclist. EOF. */
121781       *pbEof = 1;
121782     }else{
121783       sqlite3_int64 iDelta;
121784       pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
121785       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
121786         pDL->iDocid += iDelta;
121787       }else{
121788         pDL->iDocid -= iDelta;
121789       }
121790       pDL->pList = pIter;
121791       fts3PoslistCopy(0, &pIter);
121792       pDL->nList = (int)(pIter - pDL->pList);
121793
121794       /* pIter now points just past the 0x00 that terminates the position-
121795       ** list for document pDL->iDocid. However, if this position-list was
121796       ** edited in place by fts3EvalNearTrim(), then pIter may not actually
121797       ** point to the start of the next docid value. The following line deals
121798       ** with this case by advancing pIter past the zero-padding added by
121799       ** fts3EvalNearTrim().  */
121800       while( pIter<pEnd && *pIter==0 ) pIter++;
121801
121802       pDL->pNextDocid = pIter;
121803       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
121804       *pbEof = 0;
121805     }
121806   }
121807
121808   return rc;
121809 }
121810
121811 /*
121812 **
121813 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
121814 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
121815 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
121816 ** expressions for which all descendent tokens are deferred.
121817 **
121818 ** If parameter bOptOk is zero, then it is guaranteed that the
121819 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
121820 ** each phrase in the expression (subject to deferred token processing).
121821 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
121822 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
121823 **
121824 ** If an error occurs within this function, *pRc is set to an SQLite error
121825 ** code before returning.
121826 */
121827 static void fts3EvalStartReaders(
121828   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121829   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
121830   int bOptOk,                     /* True to enable incremental loading */
121831   int *pRc                        /* IN/OUT: Error code */
121832 ){
121833   if( pExpr && SQLITE_OK==*pRc ){
121834     if( pExpr->eType==FTSQUERY_PHRASE ){
121835       int i;
121836       int nToken = pExpr->pPhrase->nToken;
121837       for(i=0; i<nToken; i++){
121838         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
121839       }
121840       pExpr->bDeferred = (i==nToken);
121841       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
121842     }else{
121843       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
121844       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
121845       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
121846     }
121847   }
121848 }
121849
121850 /*
121851 ** An array of the following structures is assembled as part of the process
121852 ** of selecting tokens to defer before the query starts executing (as part
121853 ** of the xFilter() method). There is one element in the array for each
121854 ** token in the FTS expression.
121855 **
121856 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
121857 ** to phrases that are connected only by AND and NEAR operators (not OR or
121858 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
121859 ** separately. The root of a tokens AND/NEAR cluster is stored in 
121860 ** Fts3TokenAndCost.pRoot.
121861 */
121862 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
121863 struct Fts3TokenAndCost {
121864   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
121865   int iToken;                     /* Position of token in phrase */
121866   Fts3PhraseToken *pToken;        /* The token itself */
121867   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
121868   int nOvfl;                      /* Number of overflow pages to load doclist */
121869   int iCol;                       /* The column the token must match */
121870 };
121871
121872 /*
121873 ** This function is used to populate an allocated Fts3TokenAndCost array.
121874 **
121875 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
121876 ** Otherwise, if an error occurs during execution, *pRc is set to an
121877 ** SQLite error code.
121878 */
121879 static void fts3EvalTokenCosts(
121880   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121881   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
121882   Fts3Expr *pExpr,                /* Expression to consider */
121883   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
121884   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
121885   int *pRc                        /* IN/OUT: Error code */
121886 ){
121887   if( *pRc==SQLITE_OK ){
121888     if( pExpr->eType==FTSQUERY_PHRASE ){
121889       Fts3Phrase *pPhrase = pExpr->pPhrase;
121890       int i;
121891       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
121892         Fts3TokenAndCost *pTC = (*ppTC)++;
121893         pTC->pPhrase = pPhrase;
121894         pTC->iToken = i;
121895         pTC->pRoot = pRoot;
121896         pTC->pToken = &pPhrase->aToken[i];
121897         pTC->iCol = pPhrase->iColumn;
121898         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
121899       }
121900     }else if( pExpr->eType!=FTSQUERY_NOT ){
121901       assert( pExpr->eType==FTSQUERY_OR
121902            || pExpr->eType==FTSQUERY_AND
121903            || pExpr->eType==FTSQUERY_NEAR
121904       );
121905       assert( pExpr->pLeft && pExpr->pRight );
121906       if( pExpr->eType==FTSQUERY_OR ){
121907         pRoot = pExpr->pLeft;
121908         **ppOr = pRoot;
121909         (*ppOr)++;
121910       }
121911       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
121912       if( pExpr->eType==FTSQUERY_OR ){
121913         pRoot = pExpr->pRight;
121914         **ppOr = pRoot;
121915         (*ppOr)++;
121916       }
121917       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
121918     }
121919   }
121920 }
121921
121922 /*
121923 ** Determine the average document (row) size in pages. If successful,
121924 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
121925 ** an SQLite error code.
121926 **
121927 ** The average document size in pages is calculated by first calculating 
121928 ** determining the average size in bytes, B. If B is less than the amount
121929 ** of data that will fit on a single leaf page of an intkey table in
121930 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
121931 ** the number of overflow pages consumed by a record B bytes in size.
121932 */
121933 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
121934   if( pCsr->nRowAvg==0 ){
121935     /* The average document size, which is required to calculate the cost
121936     ** of each doclist, has not yet been determined. Read the required 
121937     ** data from the %_stat table to calculate it.
121938     **
121939     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
121940     ** varints, where nCol is the number of columns in the FTS3 table.
121941     ** The first varint is the number of documents currently stored in
121942     ** the table. The following nCol varints contain the total amount of
121943     ** data stored in all rows of each column of the table, from left
121944     ** to right.
121945     */
121946     int rc;
121947     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
121948     sqlite3_stmt *pStmt;
121949     sqlite3_int64 nDoc = 0;
121950     sqlite3_int64 nByte = 0;
121951     const char *pEnd;
121952     const char *a;
121953
121954     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
121955     if( rc!=SQLITE_OK ) return rc;
121956     a = sqlite3_column_blob(pStmt, 0);
121957     assert( a );
121958
121959     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
121960     a += sqlite3Fts3GetVarint(a, &nDoc);
121961     while( a<pEnd ){
121962       a += sqlite3Fts3GetVarint(a, &nByte);
121963     }
121964     if( nDoc==0 || nByte==0 ){
121965       sqlite3_reset(pStmt);
121966       return FTS_CORRUPT_VTAB;
121967     }
121968
121969     pCsr->nDoc = nDoc;
121970     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
121971     assert( pCsr->nRowAvg>0 ); 
121972     rc = sqlite3_reset(pStmt);
121973     if( rc!=SQLITE_OK ) return rc;
121974   }
121975
121976   *pnPage = pCsr->nRowAvg;
121977   return SQLITE_OK;
121978 }
121979
121980 /*
121981 ** This function is called to select the tokens (if any) that will be 
121982 ** deferred. The array aTC[] has already been populated when this is
121983 ** called.
121984 **
121985 ** This function is called once for each AND/NEAR cluster in the 
121986 ** expression. Each invocation determines which tokens to defer within
121987 ** the cluster with root node pRoot. See comments above the definition
121988 ** of struct Fts3TokenAndCost for more details.
121989 **
121990 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
121991 ** called on each token to defer. Otherwise, an SQLite error code is
121992 ** returned.
121993 */
121994 static int fts3EvalSelectDeferred(
121995   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121996   Fts3Expr *pRoot,                /* Consider tokens with this root node */
121997   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
121998   int nTC                         /* Number of entries in aTC[] */
121999 ){
122000   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122001   int nDocSize = 0;               /* Number of pages per doc loaded */
122002   int rc = SQLITE_OK;             /* Return code */
122003   int ii;                         /* Iterator variable for various purposes */
122004   int nOvfl = 0;                  /* Total overflow pages used by doclists */
122005   int nToken = 0;                 /* Total number of tokens in cluster */
122006
122007   int nMinEst = 0;                /* The minimum count for any phrase so far. */
122008   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
122009
122010   /* Tokens are never deferred for FTS tables created using the content=xxx
122011   ** option. The reason being that it is not guaranteed that the content
122012   ** table actually contains the same data as the index. To prevent this from
122013   ** causing any problems, the deferred token optimization is completely
122014   ** disabled for content=xxx tables. */
122015   if( pTab->zContentTbl ){
122016     return SQLITE_OK;
122017   }
122018
122019   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
122020   ** associated with the tokens spill onto overflow pages, or if there is
122021   ** only 1 token, exit early. No tokens to defer in this case. */
122022   for(ii=0; ii<nTC; ii++){
122023     if( aTC[ii].pRoot==pRoot ){
122024       nOvfl += aTC[ii].nOvfl;
122025       nToken++;
122026     }
122027   }
122028   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
122029
122030   /* Obtain the average docsize (in pages). */
122031   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
122032   assert( rc!=SQLITE_OK || nDocSize>0 );
122033
122034
122035   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
122036   ** of the number of overflow pages that will be loaded by the pager layer 
122037   ** to retrieve the entire doclist for the token from the full-text index.
122038   ** Load the doclists for tokens that are either:
122039   **
122040   **   a. The cheapest token in the entire query (i.e. the one visited by the
122041   **      first iteration of this loop), or
122042   **
122043   **   b. Part of a multi-token phrase.
122044   **
122045   ** After each token doclist is loaded, merge it with the others from the
122046   ** same phrase and count the number of documents that the merged doclist
122047   ** contains. Set variable "nMinEst" to the smallest number of documents in 
122048   ** any phrase doclist for which 1 or more token doclists have been loaded.
122049   ** Let nOther be the number of other phrases for which it is certain that
122050   ** one or more tokens will not be deferred.
122051   **
122052   ** Then, for each token, defer it if loading the doclist would result in
122053   ** loading N or more overflow pages into memory, where N is computed as:
122054   **
122055   **    (nMinEst + 4^nOther - 1) / (4^nOther)
122056   */
122057   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
122058     int iTC;                      /* Used to iterate through aTC[] array. */
122059     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
122060
122061     /* Set pTC to point to the cheapest remaining token. */
122062     for(iTC=0; iTC<nTC; iTC++){
122063       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
122064        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
122065       ){
122066         pTC = &aTC[iTC];
122067       }
122068     }
122069     assert( pTC );
122070
122071     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
122072       /* The number of overflow pages to load for this (and therefore all
122073       ** subsequent) tokens is greater than the estimated number of pages 
122074       ** that will be loaded if all subsequent tokens are deferred.
122075       */
122076       Fts3PhraseToken *pToken = pTC->pToken;
122077       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
122078       fts3SegReaderCursorFree(pToken->pSegcsr);
122079       pToken->pSegcsr = 0;
122080     }else{
122081       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
122082       ** for-loop. Except, limit the value to 2^24 to prevent it from 
122083       ** overflowing the 32-bit integer it is stored in. */
122084       if( ii<12 ) nLoad4 = nLoad4*4;
122085
122086       if( ii==0 || pTC->pPhrase->nToken>1 ){
122087         /* Either this is the cheapest token in the entire query, or it is
122088         ** part of a multi-token phrase. Either way, the entire doclist will
122089         ** (eventually) be loaded into memory. It may as well be now. */
122090         Fts3PhraseToken *pToken = pTC->pToken;
122091         int nList = 0;
122092         char *pList = 0;
122093         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
122094         assert( rc==SQLITE_OK || pList==0 );
122095         if( rc==SQLITE_OK ){
122096           int nCount;
122097           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
122098           nCount = fts3DoclistCountDocids(
122099               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
122100           );
122101           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
122102         }
122103       }
122104     }
122105     pTC->pToken = 0;
122106   }
122107
122108   return rc;
122109 }
122110
122111 /*
122112 ** This function is called from within the xFilter method. It initializes
122113 ** the full-text query currently stored in pCsr->pExpr. To iterate through
122114 ** the results of a query, the caller does:
122115 **
122116 **    fts3EvalStart(pCsr);
122117 **    while( 1 ){
122118 **      fts3EvalNext(pCsr);
122119 **      if( pCsr->bEof ) break;
122120 **      ... return row pCsr->iPrevId to the caller ...
122121 **    }
122122 */
122123 static int fts3EvalStart(Fts3Cursor *pCsr){
122124   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122125   int rc = SQLITE_OK;
122126   int nToken = 0;
122127   int nOr = 0;
122128
122129   /* Allocate a MultiSegReader for each token in the expression. */
122130   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
122131
122132   /* Determine which, if any, tokens in the expression should be deferred. */
122133 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
122134   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
122135     Fts3TokenAndCost *aTC;
122136     Fts3Expr **apOr;
122137     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
122138         sizeof(Fts3TokenAndCost) * nToken
122139       + sizeof(Fts3Expr *) * nOr * 2
122140     );
122141     apOr = (Fts3Expr **)&aTC[nToken];
122142
122143     if( !aTC ){
122144       rc = SQLITE_NOMEM;
122145     }else{
122146       int ii;
122147       Fts3TokenAndCost *pTC = aTC;
122148       Fts3Expr **ppOr = apOr;
122149
122150       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
122151       nToken = (int)(pTC-aTC);
122152       nOr = (int)(ppOr-apOr);
122153
122154       if( rc==SQLITE_OK ){
122155         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
122156         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
122157           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
122158         }
122159       }
122160
122161       sqlite3_free(aTC);
122162     }
122163   }
122164 #endif
122165
122166   fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
122167   return rc;
122168 }
122169
122170 /*
122171 ** Invalidate the current position list for phrase pPhrase.
122172 */
122173 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
122174   if( pPhrase->doclist.bFreeList ){
122175     sqlite3_free(pPhrase->doclist.pList);
122176   }
122177   pPhrase->doclist.pList = 0;
122178   pPhrase->doclist.nList = 0;
122179   pPhrase->doclist.bFreeList = 0;
122180 }
122181
122182 /*
122183 ** This function is called to edit the position list associated with
122184 ** the phrase object passed as the fifth argument according to a NEAR
122185 ** condition. For example:
122186 **
122187 **     abc NEAR/5 "def ghi"
122188 **
122189 ** Parameter nNear is passed the NEAR distance of the expression (5 in
122190 ** the example above). When this function is called, *paPoslist points to
122191 ** the position list, and *pnToken is the number of phrase tokens in, the
122192 ** phrase on the other side of the NEAR operator to pPhrase. For example,
122193 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
122194 ** the position list associated with phrase "abc".
122195 **
122196 ** All positions in the pPhrase position list that are not sufficiently
122197 ** close to a position in the *paPoslist position list are removed. If this
122198 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
122199 **
122200 ** Before returning, *paPoslist is set to point to the position lsit 
122201 ** associated with pPhrase. And *pnToken is set to the number of tokens in
122202 ** pPhrase.
122203 */
122204 static int fts3EvalNearTrim(
122205   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
122206   char *aTmp,                     /* Temporary space to use */
122207   char **paPoslist,               /* IN/OUT: Position list */
122208   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
122209   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
122210 ){
122211   int nParam1 = nNear + pPhrase->nToken;
122212   int nParam2 = nNear + *pnToken;
122213   int nNew;
122214   char *p2; 
122215   char *pOut; 
122216   int res;
122217
122218   assert( pPhrase->doclist.pList );
122219
122220   p2 = pOut = pPhrase->doclist.pList;
122221   res = fts3PoslistNearMerge(
122222     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
122223   );
122224   if( res ){
122225     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
122226     assert( pPhrase->doclist.pList[nNew]=='\0' );
122227     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
122228     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
122229     pPhrase->doclist.nList = nNew;
122230     *paPoslist = pPhrase->doclist.pList;
122231     *pnToken = pPhrase->nToken;
122232   }
122233
122234   return res;
122235 }
122236
122237 /*
122238 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
122239 ** Otherwise, it advances the expression passed as the second argument to
122240 ** point to the next matching row in the database. Expressions iterate through
122241 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
122242 ** or descending if it is non-zero.
122243 **
122244 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
122245 ** successful, the following variables in pExpr are set:
122246 **
122247 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
122248 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
122249 **
122250 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
122251 ** at EOF, then the following variables are populated with the position list
122252 ** for the phrase for the visited row:
122253 **
122254 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
122255 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
122256 **
122257 ** It says above that this function advances the expression to the next
122258 ** matching row. This is usually true, but there are the following exceptions:
122259 **
122260 **   1. Deferred tokens are not taken into account. If a phrase consists
122261 **      entirely of deferred tokens, it is assumed to match every row in
122262 **      the db. In this case the position-list is not populated at all. 
122263 **
122264 **      Or, if a phrase contains one or more deferred tokens and one or
122265 **      more non-deferred tokens, then the expression is advanced to the 
122266 **      next possible match, considering only non-deferred tokens. In other
122267 **      words, if the phrase is "A B C", and "B" is deferred, the expression
122268 **      is advanced to the next row that contains an instance of "A * C", 
122269 **      where "*" may match any single token. The position list in this case
122270 **      is populated as for "A * C" before returning.
122271 **
122272 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
122273 **      advanced to point to the next row that matches "x AND y".
122274 ** 
122275 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
122276 ** really a match, taking into account deferred tokens and NEAR operators.
122277 */
122278 static void fts3EvalNextRow(
122279   Fts3Cursor *pCsr,               /* FTS Cursor handle */
122280   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
122281   int *pRc                        /* IN/OUT: Error code */
122282 ){
122283   if( *pRc==SQLITE_OK ){
122284     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
122285     assert( pExpr->bEof==0 );
122286     pExpr->bStart = 1;
122287
122288     switch( pExpr->eType ){
122289       case FTSQUERY_NEAR:
122290       case FTSQUERY_AND: {
122291         Fts3Expr *pLeft = pExpr->pLeft;
122292         Fts3Expr *pRight = pExpr->pRight;
122293         assert( !pLeft->bDeferred || !pRight->bDeferred );
122294
122295         if( pLeft->bDeferred ){
122296           /* LHS is entirely deferred. So we assume it matches every row.
122297           ** Advance the RHS iterator to find the next row visited. */
122298           fts3EvalNextRow(pCsr, pRight, pRc);
122299           pExpr->iDocid = pRight->iDocid;
122300           pExpr->bEof = pRight->bEof;
122301         }else if( pRight->bDeferred ){
122302           /* RHS is entirely deferred. So we assume it matches every row.
122303           ** Advance the LHS iterator to find the next row visited. */
122304           fts3EvalNextRow(pCsr, pLeft, pRc);
122305           pExpr->iDocid = pLeft->iDocid;
122306           pExpr->bEof = pLeft->bEof;
122307         }else{
122308           /* Neither the RHS or LHS are deferred. */
122309           fts3EvalNextRow(pCsr, pLeft, pRc);
122310           fts3EvalNextRow(pCsr, pRight, pRc);
122311           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
122312             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
122313             if( iDiff==0 ) break;
122314             if( iDiff<0 ){
122315               fts3EvalNextRow(pCsr, pLeft, pRc);
122316             }else{
122317               fts3EvalNextRow(pCsr, pRight, pRc);
122318             }
122319           }
122320           pExpr->iDocid = pLeft->iDocid;
122321           pExpr->bEof = (pLeft->bEof || pRight->bEof);
122322         }
122323         break;
122324       }
122325   
122326       case FTSQUERY_OR: {
122327         Fts3Expr *pLeft = pExpr->pLeft;
122328         Fts3Expr *pRight = pExpr->pRight;
122329         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
122330
122331         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
122332         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
122333
122334         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
122335           fts3EvalNextRow(pCsr, pLeft, pRc);
122336         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
122337           fts3EvalNextRow(pCsr, pRight, pRc);
122338         }else{
122339           fts3EvalNextRow(pCsr, pLeft, pRc);
122340           fts3EvalNextRow(pCsr, pRight, pRc);
122341         }
122342
122343         pExpr->bEof = (pLeft->bEof && pRight->bEof);
122344         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
122345         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
122346           pExpr->iDocid = pLeft->iDocid;
122347         }else{
122348           pExpr->iDocid = pRight->iDocid;
122349         }
122350
122351         break;
122352       }
122353
122354       case FTSQUERY_NOT: {
122355         Fts3Expr *pLeft = pExpr->pLeft;
122356         Fts3Expr *pRight = pExpr->pRight;
122357
122358         if( pRight->bStart==0 ){
122359           fts3EvalNextRow(pCsr, pRight, pRc);
122360           assert( *pRc!=SQLITE_OK || pRight->bStart );
122361         }
122362
122363         fts3EvalNextRow(pCsr, pLeft, pRc);
122364         if( pLeft->bEof==0 ){
122365           while( !*pRc 
122366               && !pRight->bEof 
122367               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
122368           ){
122369             fts3EvalNextRow(pCsr, pRight, pRc);
122370           }
122371         }
122372         pExpr->iDocid = pLeft->iDocid;
122373         pExpr->bEof = pLeft->bEof;
122374         break;
122375       }
122376
122377       default: {
122378         Fts3Phrase *pPhrase = pExpr->pPhrase;
122379         fts3EvalInvalidatePoslist(pPhrase);
122380         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
122381         pExpr->iDocid = pPhrase->doclist.iDocid;
122382         break;
122383       }
122384     }
122385   }
122386 }
122387
122388 /*
122389 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
122390 ** cluster, then this function returns 1 immediately.
122391 **
122392 ** Otherwise, it checks if the current row really does match the NEAR 
122393 ** expression, using the data currently stored in the position lists 
122394 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
122395 **
122396 ** If the current row is a match, the position list associated with each
122397 ** phrase in the NEAR expression is edited in place to contain only those
122398 ** phrase instances sufficiently close to their peers to satisfy all NEAR
122399 ** constraints. In this case it returns 1. If the NEAR expression does not 
122400 ** match the current row, 0 is returned. The position lists may or may not
122401 ** be edited if 0 is returned.
122402 */
122403 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
122404   int res = 1;
122405
122406   /* The following block runs if pExpr is the root of a NEAR query.
122407   ** For example, the query:
122408   **
122409   **         "w" NEAR "x" NEAR "y" NEAR "z"
122410   **
122411   ** which is represented in tree form as:
122412   **
122413   **                               |
122414   **                          +--NEAR--+      <-- root of NEAR query
122415   **                          |        |
122416   **                     +--NEAR--+   "z"
122417   **                     |        |
122418   **                +--NEAR--+   "y"
122419   **                |        |
122420   **               "w"      "x"
122421   **
122422   ** The right-hand child of a NEAR node is always a phrase. The 
122423   ** left-hand child may be either a phrase or a NEAR node. There are
122424   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
122425   */
122426   if( *pRc==SQLITE_OK 
122427    && pExpr->eType==FTSQUERY_NEAR 
122428    && pExpr->bEof==0
122429    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
122430   ){
122431     Fts3Expr *p; 
122432     int nTmp = 0;                 /* Bytes of temp space */
122433     char *aTmp;                   /* Temp space for PoslistNearMerge() */
122434
122435     /* Allocate temporary working space. */
122436     for(p=pExpr; p->pLeft; p=p->pLeft){
122437       nTmp += p->pRight->pPhrase->doclist.nList;
122438     }
122439     nTmp += p->pPhrase->doclist.nList;
122440     if( nTmp==0 ){
122441       res = 0;
122442     }else{
122443       aTmp = sqlite3_malloc(nTmp*2);
122444       if( !aTmp ){
122445         *pRc = SQLITE_NOMEM;
122446         res = 0;
122447       }else{
122448         char *aPoslist = p->pPhrase->doclist.pList;
122449         int nToken = p->pPhrase->nToken;
122450
122451         for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
122452           Fts3Phrase *pPhrase = p->pRight->pPhrase;
122453           int nNear = p->nNear;
122454           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
122455         }
122456
122457         aPoslist = pExpr->pRight->pPhrase->doclist.pList;
122458         nToken = pExpr->pRight->pPhrase->nToken;
122459         for(p=pExpr->pLeft; p && res; p=p->pLeft){
122460           int nNear;
122461           Fts3Phrase *pPhrase;
122462           assert( p->pParent && p->pParent->pLeft==p );
122463           nNear = p->pParent->nNear;
122464           pPhrase = (
122465               p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
122466               );
122467           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
122468         }
122469       }
122470
122471       sqlite3_free(aTmp);
122472     }
122473   }
122474
122475   return res;
122476 }
122477
122478 /*
122479 ** This function is a helper function for fts3EvalTestDeferredAndNear().
122480 ** Assuming no error occurs or has occurred, It returns non-zero if the
122481 ** expression passed as the second argument matches the row that pCsr 
122482 ** currently points to, or zero if it does not.
122483 **
122484 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
122485 ** If an error occurs during execution of this function, *pRc is set to 
122486 ** the appropriate SQLite error code. In this case the returned value is 
122487 ** undefined.
122488 */
122489 static int fts3EvalTestExpr(
122490   Fts3Cursor *pCsr,               /* FTS cursor handle */
122491   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
122492   int *pRc                        /* IN/OUT: Error code */
122493 ){
122494   int bHit = 1;                   /* Return value */
122495   if( *pRc==SQLITE_OK ){
122496     switch( pExpr->eType ){
122497       case FTSQUERY_NEAR:
122498       case FTSQUERY_AND:
122499         bHit = (
122500             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
122501          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
122502          && fts3EvalNearTest(pExpr, pRc)
122503         );
122504
122505         /* If the NEAR expression does not match any rows, zero the doclist for 
122506         ** all phrases involved in the NEAR. This is because the snippet(),
122507         ** offsets() and matchinfo() functions are not supposed to recognize 
122508         ** any instances of phrases that are part of unmatched NEAR queries. 
122509         ** For example if this expression:
122510         **
122511         **    ... MATCH 'a OR (b NEAR c)'
122512         **
122513         ** is matched against a row containing:
122514         **
122515         **        'a b d e'
122516         **
122517         ** then any snippet() should ony highlight the "a" term, not the "b"
122518         ** (as "b" is part of a non-matching NEAR clause).
122519         */
122520         if( bHit==0 
122521          && pExpr->eType==FTSQUERY_NEAR 
122522          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
122523         ){
122524           Fts3Expr *p;
122525           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
122526             if( p->pRight->iDocid==pCsr->iPrevId ){
122527               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
122528             }
122529           }
122530           if( p->iDocid==pCsr->iPrevId ){
122531             fts3EvalInvalidatePoslist(p->pPhrase);
122532           }
122533         }
122534
122535         break;
122536
122537       case FTSQUERY_OR: {
122538         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
122539         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
122540         bHit = bHit1 || bHit2;
122541         break;
122542       }
122543
122544       case FTSQUERY_NOT:
122545         bHit = (
122546             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
122547          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
122548         );
122549         break;
122550
122551       default: {
122552 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
122553         if( pCsr->pDeferred 
122554          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
122555         ){
122556           Fts3Phrase *pPhrase = pExpr->pPhrase;
122557           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
122558           if( pExpr->bDeferred ){
122559             fts3EvalInvalidatePoslist(pPhrase);
122560           }
122561           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
122562           bHit = (pPhrase->doclist.pList!=0);
122563           pExpr->iDocid = pCsr->iPrevId;
122564         }else
122565 #endif
122566         {
122567           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
122568         }
122569         break;
122570       }
122571     }
122572   }
122573   return bHit;
122574 }
122575
122576 /*
122577 ** This function is called as the second part of each xNext operation when
122578 ** iterating through the results of a full-text query. At this point the
122579 ** cursor points to a row that matches the query expression, with the
122580 ** following caveats:
122581 **
122582 **   * Up until this point, "NEAR" operators in the expression have been
122583 **     treated as "AND".
122584 **
122585 **   * Deferred tokens have not yet been considered.
122586 **
122587 ** If *pRc is not SQLITE_OK when this function is called, it immediately
122588 ** returns 0. Otherwise, it tests whether or not after considering NEAR
122589 ** operators and deferred tokens the current row is still a match for the
122590 ** expression. It returns 1 if both of the following are true:
122591 **
122592 **   1. *pRc is SQLITE_OK when this function returns, and
122593 **
122594 **   2. After scanning the current FTS table row for the deferred tokens,
122595 **      it is determined that the row does *not* match the query.
122596 **
122597 ** Or, if no error occurs and it seems the current row does match the FTS
122598 ** query, return 0.
122599 */
122600 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
122601   int rc = *pRc;
122602   int bMiss = 0;
122603   if( rc==SQLITE_OK ){
122604
122605     /* If there are one or more deferred tokens, load the current row into
122606     ** memory and scan it to determine the position list for each deferred
122607     ** token. Then, see if this row is really a match, considering deferred
122608     ** tokens and NEAR operators (neither of which were taken into account
122609     ** earlier, by fts3EvalNextRow()). 
122610     */
122611     if( pCsr->pDeferred ){
122612       rc = fts3CursorSeek(0, pCsr);
122613       if( rc==SQLITE_OK ){
122614         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
122615       }
122616     }
122617     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
122618
122619     /* Free the position-lists accumulated for each deferred token above. */
122620     sqlite3Fts3FreeDeferredDoclists(pCsr);
122621     *pRc = rc;
122622   }
122623   return (rc==SQLITE_OK && bMiss);
122624 }
122625
122626 /*
122627 ** Advance to the next document that matches the FTS expression in
122628 ** Fts3Cursor.pExpr.
122629 */
122630 static int fts3EvalNext(Fts3Cursor *pCsr){
122631   int rc = SQLITE_OK;             /* Return Code */
122632   Fts3Expr *pExpr = pCsr->pExpr;
122633   assert( pCsr->isEof==0 );
122634   if( pExpr==0 ){
122635     pCsr->isEof = 1;
122636   }else{
122637     do {
122638       if( pCsr->isRequireSeek==0 ){
122639         sqlite3_reset(pCsr->pStmt);
122640       }
122641       assert( sqlite3_data_count(pCsr->pStmt)==0 );
122642       fts3EvalNextRow(pCsr, pExpr, &rc);
122643       pCsr->isEof = pExpr->bEof;
122644       pCsr->isRequireSeek = 1;
122645       pCsr->isMatchinfoNeeded = 1;
122646       pCsr->iPrevId = pExpr->iDocid;
122647     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
122648   }
122649   return rc;
122650 }
122651
122652 /*
122653 ** Restart interation for expression pExpr so that the next call to
122654 ** fts3EvalNext() visits the first row. Do not allow incremental 
122655 ** loading or merging of phrase doclists for this iteration.
122656 **
122657 ** If *pRc is other than SQLITE_OK when this function is called, it is
122658 ** a no-op. If an error occurs within this function, *pRc is set to an
122659 ** SQLite error code before returning.
122660 */
122661 static void fts3EvalRestart(
122662   Fts3Cursor *pCsr,
122663   Fts3Expr *pExpr,
122664   int *pRc
122665 ){
122666   if( pExpr && *pRc==SQLITE_OK ){
122667     Fts3Phrase *pPhrase = pExpr->pPhrase;
122668
122669     if( pPhrase ){
122670       fts3EvalInvalidatePoslist(pPhrase);
122671       if( pPhrase->bIncr ){
122672         assert( pPhrase->nToken==1 );
122673         assert( pPhrase->aToken[0].pSegcsr );
122674         sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
122675         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
122676       }
122677
122678       pPhrase->doclist.pNextDocid = 0;
122679       pPhrase->doclist.iDocid = 0;
122680     }
122681
122682     pExpr->iDocid = 0;
122683     pExpr->bEof = 0;
122684     pExpr->bStart = 0;
122685
122686     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
122687     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
122688   }
122689 }
122690
122691 /*
122692 ** After allocating the Fts3Expr.aMI[] array for each phrase in the 
122693 ** expression rooted at pExpr, the cursor iterates through all rows matched
122694 ** by pExpr, calling this function for each row. This function increments
122695 ** the values in Fts3Expr.aMI[] according to the position-list currently
122696 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
122697 ** expression nodes.
122698 */
122699 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
122700   if( pExpr ){
122701     Fts3Phrase *pPhrase = pExpr->pPhrase;
122702     if( pPhrase && pPhrase->doclist.pList ){
122703       int iCol = 0;
122704       char *p = pPhrase->doclist.pList;
122705
122706       assert( *p );
122707       while( 1 ){
122708         u8 c = 0;
122709         int iCnt = 0;
122710         while( 0xFE & (*p | c) ){
122711           if( (c&0x80)==0 ) iCnt++;
122712           c = *p++ & 0x80;
122713         }
122714
122715         /* aMI[iCol*3 + 1] = Number of occurrences
122716         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
122717         */
122718         pExpr->aMI[iCol*3 + 1] += iCnt;
122719         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
122720         if( *p==0x00 ) break;
122721         p++;
122722         p += sqlite3Fts3GetVarint32(p, &iCol);
122723       }
122724     }
122725
122726     fts3EvalUpdateCounts(pExpr->pLeft);
122727     fts3EvalUpdateCounts(pExpr->pRight);
122728   }
122729 }
122730
122731 /*
122732 ** Expression pExpr must be of type FTSQUERY_PHRASE.
122733 **
122734 ** If it is not already allocated and populated, this function allocates and
122735 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
122736 ** of a NEAR expression, then it also allocates and populates the same array
122737 ** for all other phrases that are part of the NEAR expression.
122738 **
122739 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
122740 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
122741 */
122742 static int fts3EvalGatherStats(
122743   Fts3Cursor *pCsr,               /* Cursor object */
122744   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
122745 ){
122746   int rc = SQLITE_OK;             /* Return code */
122747
122748   assert( pExpr->eType==FTSQUERY_PHRASE );
122749   if( pExpr->aMI==0 ){
122750     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122751     Fts3Expr *pRoot;                /* Root of NEAR expression */
122752     Fts3Expr *p;                    /* Iterator used for several purposes */
122753
122754     sqlite3_int64 iPrevId = pCsr->iPrevId;
122755     sqlite3_int64 iDocid;
122756     u8 bEof;
122757
122758     /* Find the root of the NEAR expression */
122759     pRoot = pExpr;
122760     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
122761       pRoot = pRoot->pParent;
122762     }
122763     iDocid = pRoot->iDocid;
122764     bEof = pRoot->bEof;
122765     assert( pRoot->bStart );
122766
122767     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
122768     for(p=pRoot; p; p=p->pLeft){
122769       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
122770       assert( pE->aMI==0 );
122771       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
122772       if( !pE->aMI ) return SQLITE_NOMEM;
122773       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
122774     }
122775
122776     fts3EvalRestart(pCsr, pRoot, &rc);
122777
122778     while( pCsr->isEof==0 && rc==SQLITE_OK ){
122779
122780       do {
122781         /* Ensure the %_content statement is reset. */
122782         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
122783         assert( sqlite3_data_count(pCsr->pStmt)==0 );
122784
122785         /* Advance to the next document */
122786         fts3EvalNextRow(pCsr, pRoot, &rc);
122787         pCsr->isEof = pRoot->bEof;
122788         pCsr->isRequireSeek = 1;
122789         pCsr->isMatchinfoNeeded = 1;
122790         pCsr->iPrevId = pRoot->iDocid;
122791       }while( pCsr->isEof==0 
122792            && pRoot->eType==FTSQUERY_NEAR 
122793            && fts3EvalTestDeferredAndNear(pCsr, &rc) 
122794       );
122795
122796       if( rc==SQLITE_OK && pCsr->isEof==0 ){
122797         fts3EvalUpdateCounts(pRoot);
122798       }
122799     }
122800
122801     pCsr->isEof = 0;
122802     pCsr->iPrevId = iPrevId;
122803
122804     if( bEof ){
122805       pRoot->bEof = bEof;
122806     }else{
122807       /* Caution: pRoot may iterate through docids in ascending or descending
122808       ** order. For this reason, even though it seems more defensive, the 
122809       ** do loop can not be written:
122810       **
122811       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
122812       */
122813       fts3EvalRestart(pCsr, pRoot, &rc);
122814       do {
122815         fts3EvalNextRow(pCsr, pRoot, &rc);
122816         assert( pRoot->bEof==0 );
122817       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
122818       fts3EvalTestDeferredAndNear(pCsr, &rc);
122819     }
122820   }
122821   return rc;
122822 }
122823
122824 /*
122825 ** This function is used by the matchinfo() module to query a phrase 
122826 ** expression node for the following information:
122827 **
122828 **   1. The total number of occurrences of the phrase in each column of 
122829 **      the FTS table (considering all rows), and
122830 **
122831 **   2. For each column, the number of rows in the table for which the
122832 **      column contains at least one instance of the phrase.
122833 **
122834 ** If no error occurs, SQLITE_OK is returned and the values for each column
122835 ** written into the array aiOut as follows:
122836 **
122837 **   aiOut[iCol*3 + 1] = Number of occurrences
122838 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
122839 **
122840 ** Caveats:
122841 **
122842 **   * If a phrase consists entirely of deferred tokens, then all output 
122843 **     values are set to the number of documents in the table. In other
122844 **     words we assume that very common tokens occur exactly once in each 
122845 **     column of each row of the table.
122846 **
122847 **   * If a phrase contains some deferred tokens (and some non-deferred 
122848 **     tokens), count the potential occurrence identified by considering
122849 **     the non-deferred tokens instead of actual phrase occurrences.
122850 **
122851 **   * If the phrase is part of a NEAR expression, then only phrase instances
122852 **     that meet the NEAR constraint are included in the counts.
122853 */
122854 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
122855   Fts3Cursor *pCsr,               /* FTS cursor handle */
122856   Fts3Expr *pExpr,                /* Phrase expression */
122857   u32 *aiOut                      /* Array to write results into (see above) */
122858 ){
122859   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122860   int rc = SQLITE_OK;
122861   int iCol;
122862
122863   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
122864     assert( pCsr->nDoc>0 );
122865     for(iCol=0; iCol<pTab->nColumn; iCol++){
122866       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
122867       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
122868     }
122869   }else{
122870     rc = fts3EvalGatherStats(pCsr, pExpr);
122871     if( rc==SQLITE_OK ){
122872       assert( pExpr->aMI );
122873       for(iCol=0; iCol<pTab->nColumn; iCol++){
122874         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
122875         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
122876       }
122877     }
122878   }
122879
122880   return rc;
122881 }
122882
122883 /*
122884 ** The expression pExpr passed as the second argument to this function
122885 ** must be of type FTSQUERY_PHRASE. 
122886 **
122887 ** The returned value is either NULL or a pointer to a buffer containing
122888 ** a position-list indicating the occurrences of the phrase in column iCol
122889 ** of the current row. 
122890 **
122891 ** More specifically, the returned buffer contains 1 varint for each 
122892 ** occurrence of the phrase in the column, stored using the normal (delta+2) 
122893 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
122894 ** if the requested column contains "a b X c d X X" and the position-list
122895 ** for 'X' is requested, the buffer returned may contain:
122896 **
122897 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
122898 **
122899 ** This function works regardless of whether or not the phrase is deferred,
122900 ** incremental, or neither.
122901 */
122902 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
122903   Fts3Cursor *pCsr,               /* FTS3 cursor object */
122904   Fts3Expr *pExpr,                /* Phrase to return doclist for */
122905   int iCol,                       /* Column to return position list for */
122906   char **ppOut                    /* OUT: Pointer to position list */
122907 ){
122908   Fts3Phrase *pPhrase = pExpr->pPhrase;
122909   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122910   char *pIter;
122911   int iThis;
122912   sqlite3_int64 iDocid;
122913
122914   /* If this phrase is applies specifically to some column other than 
122915   ** column iCol, return a NULL pointer.  */
122916   *ppOut = 0;
122917   assert( iCol>=0 && iCol<pTab->nColumn );
122918   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
122919     return SQLITE_OK;
122920   }
122921
122922   iDocid = pExpr->iDocid;
122923   pIter = pPhrase->doclist.pList;
122924   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
122925     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
122926     int bOr = 0;
122927     u8 bEof = 0;
122928     Fts3Expr *p;
122929
122930     /* Check if this phrase descends from an OR expression node. If not, 
122931     ** return NULL. Otherwise, the entry that corresponds to docid 
122932     ** pCsr->iPrevId may lie earlier in the doclist buffer. */
122933     for(p=pExpr->pParent; p; p=p->pParent){
122934       if( p->eType==FTSQUERY_OR ) bOr = 1;
122935     }
122936     if( bOr==0 ) return SQLITE_OK;
122937
122938     /* This is the descendent of an OR node. In this case we cannot use
122939     ** an incremental phrase. Load the entire doclist for the phrase
122940     ** into memory in this case.  */
122941     if( pPhrase->bIncr ){
122942       int rc = SQLITE_OK;
122943       int bEofSave = pExpr->bEof;
122944       fts3EvalRestart(pCsr, pExpr, &rc);
122945       while( rc==SQLITE_OK && !pExpr->bEof ){
122946         fts3EvalNextRow(pCsr, pExpr, &rc);
122947         if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
122948       }
122949       pIter = pPhrase->doclist.pList;
122950       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
122951       if( rc!=SQLITE_OK ) return rc;
122952     }
122953
122954     if( pExpr->bEof ){
122955       pIter = 0;
122956       iDocid = 0;
122957     }
122958     bEof = (pPhrase->doclist.nAll==0);
122959     assert( bDescDoclist==0 || bDescDoclist==1 );
122960     assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
122961
122962     if( pCsr->bDesc==bDescDoclist ){
122963       int dummy;
122964       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
122965         sqlite3Fts3DoclistPrev(
122966             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
122967             &pIter, &iDocid, &dummy, &bEof
122968         );
122969       }
122970     }else{
122971       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
122972         sqlite3Fts3DoclistNext(
122973             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
122974             &pIter, &iDocid, &bEof
122975         );
122976       }
122977     }
122978
122979     if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
122980   }
122981   if( pIter==0 ) return SQLITE_OK;
122982
122983   if( *pIter==0x01 ){
122984     pIter++;
122985     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
122986   }else{
122987     iThis = 0;
122988   }
122989   while( iThis<iCol ){
122990     fts3ColumnlistCopy(0, &pIter);
122991     if( *pIter==0x00 ) return 0;
122992     pIter++;
122993     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
122994   }
122995
122996   *ppOut = ((iCol==iThis)?pIter:0);
122997   return SQLITE_OK;
122998 }
122999
123000 /*
123001 ** Free all components of the Fts3Phrase structure that were allocated by
123002 ** the eval module. Specifically, this means to free:
123003 **
123004 **   * the contents of pPhrase->doclist, and
123005 **   * any Fts3MultiSegReader objects held by phrase tokens.
123006 */
123007 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
123008   if( pPhrase ){
123009     int i;
123010     sqlite3_free(pPhrase->doclist.aAll);
123011     fts3EvalInvalidatePoslist(pPhrase);
123012     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
123013     for(i=0; i<pPhrase->nToken; i++){
123014       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
123015       pPhrase->aToken[i].pSegcsr = 0;
123016     }
123017   }
123018 }
123019
123020
123021 /*
123022 ** Return SQLITE_CORRUPT_VTAB.
123023 */
123024 #ifdef SQLITE_DEBUG
123025 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
123026   return SQLITE_CORRUPT_VTAB;
123027 }
123028 #endif
123029
123030 #if !SQLITE_CORE
123031 /*
123032 ** Initialize API pointer table, if required.
123033 */
123034 SQLITE_API int sqlite3_extension_init(
123035   sqlite3 *db, 
123036   char **pzErrMsg,
123037   const sqlite3_api_routines *pApi
123038 ){
123039   SQLITE_EXTENSION_INIT2(pApi)
123040   return sqlite3Fts3Init(db);
123041 }
123042 #endif
123043
123044 #endif
123045
123046 /************** End of fts3.c ************************************************/
123047 /************** Begin file fts3_aux.c ****************************************/
123048 /*
123049 ** 2011 Jan 27
123050 **
123051 ** The author disclaims copyright to this source code.  In place of
123052 ** a legal notice, here is a blessing:
123053 **
123054 **    May you do good and not evil.
123055 **    May you find forgiveness for yourself and forgive others.
123056 **    May you share freely, never taking more than you give.
123057 **
123058 ******************************************************************************
123059 **
123060 */
123061 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123062
123063 /* #include <string.h> */
123064 /* #include <assert.h> */
123065
123066 typedef struct Fts3auxTable Fts3auxTable;
123067 typedef struct Fts3auxCursor Fts3auxCursor;
123068
123069 struct Fts3auxTable {
123070   sqlite3_vtab base;              /* Base class used by SQLite core */
123071   Fts3Table *pFts3Tab;
123072 };
123073
123074 struct Fts3auxCursor {
123075   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
123076   Fts3MultiSegReader csr;        /* Must be right after "base" */
123077   Fts3SegFilter filter;
123078   char *zStop;
123079   int nStop;                      /* Byte-length of string zStop */
123080   int isEof;                      /* True if cursor is at EOF */
123081   sqlite3_int64 iRowid;           /* Current rowid */
123082
123083   int iCol;                       /* Current value of 'col' column */
123084   int nStat;                      /* Size of aStat[] array */
123085   struct Fts3auxColstats {
123086     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
123087     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
123088   } *aStat;
123089 };
123090
123091 /*
123092 ** Schema of the terms table.
123093 */
123094 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
123095
123096 /*
123097 ** This function does all the work for both the xConnect and xCreate methods.
123098 ** These tables have no persistent representation of their own, so xConnect
123099 ** and xCreate are identical operations.
123100 */
123101 static int fts3auxConnectMethod(
123102   sqlite3 *db,                    /* Database connection */
123103   void *pUnused,                  /* Unused */
123104   int argc,                       /* Number of elements in argv array */
123105   const char * const *argv,       /* xCreate/xConnect argument array */
123106   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
123107   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
123108 ){
123109   char const *zDb;                /* Name of database (e.g. "main") */
123110   char const *zFts3;              /* Name of fts3 table */
123111   int nDb;                        /* Result of strlen(zDb) */
123112   int nFts3;                      /* Result of strlen(zFts3) */
123113   int nByte;                      /* Bytes of space to allocate here */
123114   int rc;                         /* value returned by declare_vtab() */
123115   Fts3auxTable *p;                /* Virtual table object to return */
123116
123117   UNUSED_PARAMETER(pUnused);
123118
123119   /* The user should specify a single argument - the name of an fts3 table. */
123120   if( argc!=4 ){
123121     *pzErr = sqlite3_mprintf(
123122         "wrong number of arguments to fts4aux constructor"
123123     );
123124     return SQLITE_ERROR;
123125   }
123126
123127   zDb = argv[1]; 
123128   nDb = (int)strlen(zDb);
123129   zFts3 = argv[3];
123130   nFts3 = (int)strlen(zFts3);
123131
123132   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
123133   if( rc!=SQLITE_OK ) return rc;
123134
123135   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
123136   p = (Fts3auxTable *)sqlite3_malloc(nByte);
123137   if( !p ) return SQLITE_NOMEM;
123138   memset(p, 0, nByte);
123139
123140   p->pFts3Tab = (Fts3Table *)&p[1];
123141   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
123142   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
123143   p->pFts3Tab->db = db;
123144   p->pFts3Tab->nIndex = 1;
123145
123146   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
123147   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
123148   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
123149
123150   *ppVtab = (sqlite3_vtab *)p;
123151   return SQLITE_OK;
123152 }
123153
123154 /*
123155 ** This function does the work for both the xDisconnect and xDestroy methods.
123156 ** These tables have no persistent representation of their own, so xDisconnect
123157 ** and xDestroy are identical operations.
123158 */
123159 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
123160   Fts3auxTable *p = (Fts3auxTable *)pVtab;
123161   Fts3Table *pFts3 = p->pFts3Tab;
123162   int i;
123163
123164   /* Free any prepared statements held */
123165   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
123166     sqlite3_finalize(pFts3->aStmt[i]);
123167   }
123168   sqlite3_free(pFts3->zSegmentsTbl);
123169   sqlite3_free(p);
123170   return SQLITE_OK;
123171 }
123172
123173 #define FTS4AUX_EQ_CONSTRAINT 1
123174 #define FTS4AUX_GE_CONSTRAINT 2
123175 #define FTS4AUX_LE_CONSTRAINT 4
123176
123177 /*
123178 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
123179 */
123180 static int fts3auxBestIndexMethod(
123181   sqlite3_vtab *pVTab, 
123182   sqlite3_index_info *pInfo
123183 ){
123184   int i;
123185   int iEq = -1;
123186   int iGe = -1;
123187   int iLe = -1;
123188
123189   UNUSED_PARAMETER(pVTab);
123190
123191   /* This vtab delivers always results in "ORDER BY term ASC" order. */
123192   if( pInfo->nOrderBy==1 
123193    && pInfo->aOrderBy[0].iColumn==0 
123194    && pInfo->aOrderBy[0].desc==0
123195   ){
123196     pInfo->orderByConsumed = 1;
123197   }
123198
123199   /* Search for equality and range constraints on the "term" column. */
123200   for(i=0; i<pInfo->nConstraint; i++){
123201     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
123202       int op = pInfo->aConstraint[i].op;
123203       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
123204       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
123205       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
123206       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
123207       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
123208     }
123209   }
123210
123211   if( iEq>=0 ){
123212     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
123213     pInfo->aConstraintUsage[iEq].argvIndex = 1;
123214     pInfo->estimatedCost = 5;
123215   }else{
123216     pInfo->idxNum = 0;
123217     pInfo->estimatedCost = 20000;
123218     if( iGe>=0 ){
123219       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
123220       pInfo->aConstraintUsage[iGe].argvIndex = 1;
123221       pInfo->estimatedCost /= 2;
123222     }
123223     if( iLe>=0 ){
123224       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
123225       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
123226       pInfo->estimatedCost /= 2;
123227     }
123228   }
123229
123230   return SQLITE_OK;
123231 }
123232
123233 /*
123234 ** xOpen - Open a cursor.
123235 */
123236 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
123237   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
123238
123239   UNUSED_PARAMETER(pVTab);
123240
123241   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
123242   if( !pCsr ) return SQLITE_NOMEM;
123243   memset(pCsr, 0, sizeof(Fts3auxCursor));
123244
123245   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
123246   return SQLITE_OK;
123247 }
123248
123249 /*
123250 ** xClose - Close a cursor.
123251 */
123252 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
123253   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
123254   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123255
123256   sqlite3Fts3SegmentsClose(pFts3);
123257   sqlite3Fts3SegReaderFinish(&pCsr->csr);
123258   sqlite3_free((void *)pCsr->filter.zTerm);
123259   sqlite3_free(pCsr->zStop);
123260   sqlite3_free(pCsr->aStat);
123261   sqlite3_free(pCsr);
123262   return SQLITE_OK;
123263 }
123264
123265 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
123266   if( nSize>pCsr->nStat ){
123267     struct Fts3auxColstats *aNew;
123268     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, 
123269         sizeof(struct Fts3auxColstats) * nSize
123270     );
123271     if( aNew==0 ) return SQLITE_NOMEM;
123272     memset(&aNew[pCsr->nStat], 0, 
123273         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
123274     );
123275     pCsr->aStat = aNew;
123276     pCsr->nStat = nSize;
123277   }
123278   return SQLITE_OK;
123279 }
123280
123281 /*
123282 ** xNext - Advance the cursor to the next row, if any.
123283 */
123284 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
123285   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123286   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
123287   int rc;
123288
123289   /* Increment our pretend rowid value. */
123290   pCsr->iRowid++;
123291
123292   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
123293     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
123294   }
123295
123296   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
123297   if( rc==SQLITE_ROW ){
123298     int i = 0;
123299     int nDoclist = pCsr->csr.nDoclist;
123300     char *aDoclist = pCsr->csr.aDoclist;
123301     int iCol;
123302
123303     int eState = 0;
123304
123305     if( pCsr->zStop ){
123306       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
123307       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
123308       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
123309         pCsr->isEof = 1;
123310         return SQLITE_OK;
123311       }
123312     }
123313
123314     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
123315     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
123316     iCol = 0;
123317
123318     while( i<nDoclist ){
123319       sqlite3_int64 v = 0;
123320
123321       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
123322       switch( eState ){
123323         /* State 0. In this state the integer just read was a docid. */
123324         case 0:
123325           pCsr->aStat[0].nDoc++;
123326           eState = 1;
123327           iCol = 0;
123328           break;
123329
123330         /* State 1. In this state we are expecting either a 1, indicating
123331         ** that the following integer will be a column number, or the
123332         ** start of a position list for column 0.  
123333         ** 
123334         ** The only difference between state 1 and state 2 is that if the
123335         ** integer encountered in state 1 is not 0 or 1, then we need to
123336         ** increment the column 0 "nDoc" count for this term.
123337         */
123338         case 1:
123339           assert( iCol==0 );
123340           if( v>1 ){
123341             pCsr->aStat[1].nDoc++;
123342           }
123343           eState = 2;
123344           /* fall through */
123345
123346         case 2:
123347           if( v==0 ){       /* 0x00. Next integer will be a docid. */
123348             eState = 0;
123349           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
123350             eState = 3;
123351           }else{            /* 2 or greater. A position. */
123352             pCsr->aStat[iCol+1].nOcc++;
123353             pCsr->aStat[0].nOcc++;
123354           }
123355           break;
123356
123357         /* State 3. The integer just read is a column number. */
123358         default: assert( eState==3 );
123359           iCol = (int)v;
123360           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
123361           pCsr->aStat[iCol+1].nDoc++;
123362           eState = 2;
123363           break;
123364       }
123365     }
123366
123367     pCsr->iCol = 0;
123368     rc = SQLITE_OK;
123369   }else{
123370     pCsr->isEof = 1;
123371   }
123372   return rc;
123373 }
123374
123375 /*
123376 ** xFilter - Initialize a cursor to point at the start of its data.
123377 */
123378 static int fts3auxFilterMethod(
123379   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
123380   int idxNum,                     /* Strategy index */
123381   const char *idxStr,             /* Unused */
123382   int nVal,                       /* Number of elements in apVal */
123383   sqlite3_value **apVal           /* Arguments for the indexing scheme */
123384 ){
123385   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123386   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
123387   int rc;
123388   int isScan;
123389
123390   UNUSED_PARAMETER(nVal);
123391   UNUSED_PARAMETER(idxStr);
123392
123393   assert( idxStr==0 );
123394   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
123395        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
123396        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
123397   );
123398   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
123399
123400   /* In case this cursor is being reused, close and zero it. */
123401   testcase(pCsr->filter.zTerm);
123402   sqlite3Fts3SegReaderFinish(&pCsr->csr);
123403   sqlite3_free((void *)pCsr->filter.zTerm);
123404   sqlite3_free(pCsr->aStat);
123405   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
123406
123407   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
123408   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
123409
123410   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
123411     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
123412     if( zStr ){
123413       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
123414       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
123415       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
123416     }
123417   }
123418   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
123419     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
123420     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
123421     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
123422     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
123423   }
123424
123425   rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
123426       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
123427   );
123428   if( rc==SQLITE_OK ){
123429     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
123430   }
123431
123432   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
123433   return rc;
123434 }
123435
123436 /*
123437 ** xEof - Return true if the cursor is at EOF, or false otherwise.
123438 */
123439 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
123440   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123441   return pCsr->isEof;
123442 }
123443
123444 /*
123445 ** xColumn - Return a column value.
123446 */
123447 static int fts3auxColumnMethod(
123448   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
123449   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
123450   int iCol                        /* Index of column to read value from */
123451 ){
123452   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
123453
123454   assert( p->isEof==0 );
123455   if( iCol==0 ){        /* Column "term" */
123456     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
123457   }else if( iCol==1 ){  /* Column "col" */
123458     if( p->iCol ){
123459       sqlite3_result_int(pContext, p->iCol-1);
123460     }else{
123461       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
123462     }
123463   }else if( iCol==2 ){  /* Column "documents" */
123464     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
123465   }else{                /* Column "occurrences" */
123466     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
123467   }
123468
123469   return SQLITE_OK;
123470 }
123471
123472 /*
123473 ** xRowid - Return the current rowid for the cursor.
123474 */
123475 static int fts3auxRowidMethod(
123476   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
123477   sqlite_int64 *pRowid            /* OUT: Rowid value */
123478 ){
123479   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123480   *pRowid = pCsr->iRowid;
123481   return SQLITE_OK;
123482 }
123483
123484 /*
123485 ** Register the fts3aux module with database connection db. Return SQLITE_OK
123486 ** if successful or an error code if sqlite3_create_module() fails.
123487 */
123488 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
123489   static const sqlite3_module fts3aux_module = {
123490      0,                           /* iVersion      */
123491      fts3auxConnectMethod,        /* xCreate       */
123492      fts3auxConnectMethod,        /* xConnect      */
123493      fts3auxBestIndexMethod,      /* xBestIndex    */
123494      fts3auxDisconnectMethod,     /* xDisconnect   */
123495      fts3auxDisconnectMethod,     /* xDestroy      */
123496      fts3auxOpenMethod,           /* xOpen         */
123497      fts3auxCloseMethod,          /* xClose        */
123498      fts3auxFilterMethod,         /* xFilter       */
123499      fts3auxNextMethod,           /* xNext         */
123500      fts3auxEofMethod,            /* xEof          */
123501      fts3auxColumnMethod,         /* xColumn       */
123502      fts3auxRowidMethod,          /* xRowid        */
123503      0,                           /* xUpdate       */
123504      0,                           /* xBegin        */
123505      0,                           /* xSync         */
123506      0,                           /* xCommit       */
123507      0,                           /* xRollback     */
123508      0,                           /* xFindFunction */
123509      0,                           /* xRename       */
123510      0,                           /* xSavepoint    */
123511      0,                           /* xRelease      */
123512      0                            /* xRollbackTo   */
123513   };
123514   int rc;                         /* Return code */
123515
123516   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
123517   return rc;
123518 }
123519
123520 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
123521
123522 /************** End of fts3_aux.c ********************************************/
123523 /************** Begin file fts3_expr.c ***************************************/
123524 /*
123525 ** 2008 Nov 28
123526 **
123527 ** The author disclaims copyright to this source code.  In place of
123528 ** a legal notice, here is a blessing:
123529 **
123530 **    May you do good and not evil.
123531 **    May you find forgiveness for yourself and forgive others.
123532 **    May you share freely, never taking more than you give.
123533 **
123534 ******************************************************************************
123535 **
123536 ** This module contains code that implements a parser for fts3 query strings
123537 ** (the right-hand argument to the MATCH operator). Because the supported 
123538 ** syntax is relatively simple, the whole tokenizer/parser system is
123539 ** hand-coded. 
123540 */
123541 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123542
123543 /*
123544 ** By default, this module parses the legacy syntax that has been 
123545 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
123546 ** is defined, then it uses the new syntax. The differences between
123547 ** the new and the old syntaxes are:
123548 **
123549 **  a) The new syntax supports parenthesis. The old does not.
123550 **
123551 **  b) The new syntax supports the AND and NOT operators. The old does not.
123552 **
123553 **  c) The old syntax supports the "-" token qualifier. This is not 
123554 **     supported by the new syntax (it is replaced by the NOT operator).
123555 **
123556 **  d) When using the old syntax, the OR operator has a greater precedence
123557 **     than an implicit AND. When using the new, both implicity and explicit
123558 **     AND operators have a higher precedence than OR.
123559 **
123560 ** If compiled with SQLITE_TEST defined, then this module exports the
123561 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
123562 ** to zero causes the module to use the old syntax. If it is set to 
123563 ** non-zero the new syntax is activated. This is so both syntaxes can
123564 ** be tested using a single build of testfixture.
123565 **
123566 ** The following describes the syntax supported by the fts3 MATCH
123567 ** operator in a similar format to that used by the lemon parser
123568 ** generator. This module does not use actually lemon, it uses a
123569 ** custom parser.
123570 **
123571 **   query ::= andexpr (OR andexpr)*.
123572 **
123573 **   andexpr ::= notexpr (AND? notexpr)*.
123574 **
123575 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
123576 **   notexpr ::= LP query RP.
123577 **
123578 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
123579 **
123580 **   distance_opt ::= .
123581 **   distance_opt ::= / INTEGER.
123582 **
123583 **   phrase ::= TOKEN.
123584 **   phrase ::= COLUMN:TOKEN.
123585 **   phrase ::= "TOKEN TOKEN TOKEN...".
123586 */
123587
123588 #ifdef SQLITE_TEST
123589 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
123590 #else
123591 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
123592 #  define sqlite3_fts3_enable_parentheses 1
123593 # else
123594 #  define sqlite3_fts3_enable_parentheses 0
123595 # endif
123596 #endif
123597
123598 /*
123599 ** Default span for NEAR operators.
123600 */
123601 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
123602
123603 /* #include <string.h> */
123604 /* #include <assert.h> */
123605
123606 /*
123607 ** isNot:
123608 **   This variable is used by function getNextNode(). When getNextNode() is
123609 **   called, it sets ParseContext.isNot to true if the 'next node' is a 
123610 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
123611 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
123612 **   zero.
123613 */
123614 typedef struct ParseContext ParseContext;
123615 struct ParseContext {
123616   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
123617   int iLangid;                        /* Language id used with tokenizer */
123618   const char **azCol;                 /* Array of column names for fts3 table */
123619   int bFts4;                          /* True to allow FTS4-only syntax */
123620   int nCol;                           /* Number of entries in azCol[] */
123621   int iDefaultCol;                    /* Default column to query */
123622   int isNot;                          /* True if getNextNode() sees a unary - */
123623   sqlite3_context *pCtx;              /* Write error message here */
123624   int nNest;                          /* Number of nested brackets */
123625 };
123626
123627 /*
123628 ** This function is equivalent to the standard isspace() function. 
123629 **
123630 ** The standard isspace() can be awkward to use safely, because although it
123631 ** is defined to accept an argument of type int, its behavior when passed
123632 ** an integer that falls outside of the range of the unsigned char type
123633 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
123634 ** is defined to accept an argument of type char, and always returns 0 for
123635 ** any values that fall outside of the range of the unsigned char type (i.e.
123636 ** negative values).
123637 */
123638 static int fts3isspace(char c){
123639   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
123640 }
123641
123642 /*
123643 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
123644 ** zero the memory before returning a pointer to it. If unsuccessful, 
123645 ** return NULL.
123646 */
123647 static void *fts3MallocZero(int nByte){
123648   void *pRet = sqlite3_malloc(nByte);
123649   if( pRet ) memset(pRet, 0, nByte);
123650   return pRet;
123651 }
123652
123653 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
123654   sqlite3_tokenizer *pTokenizer,
123655   int iLangid,
123656   const char *z,
123657   int n,
123658   sqlite3_tokenizer_cursor **ppCsr
123659 ){
123660   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
123661   sqlite3_tokenizer_cursor *pCsr = 0;
123662   int rc;
123663
123664   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
123665   assert( rc==SQLITE_OK || pCsr==0 );
123666   if( rc==SQLITE_OK ){
123667     pCsr->pTokenizer = pTokenizer;
123668     if( pModule->iVersion>=1 ){
123669       rc = pModule->xLanguageid(pCsr, iLangid);
123670       if( rc!=SQLITE_OK ){
123671         pModule->xClose(pCsr);
123672         pCsr = 0;
123673       }
123674     }
123675   }
123676   *ppCsr = pCsr;
123677   return rc;
123678 }
123679
123680
123681 /*
123682 ** Extract the next token from buffer z (length n) using the tokenizer
123683 ** and other information (column names etc.) in pParse. Create an Fts3Expr
123684 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
123685 ** single token and set *ppExpr to point to it. If the end of the buffer is
123686 ** reached before a token is found, set *ppExpr to zero. It is the
123687 ** responsibility of the caller to eventually deallocate the allocated 
123688 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
123689 **
123690 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
123691 ** fails.
123692 */
123693 static int getNextToken(
123694   ParseContext *pParse,                   /* fts3 query parse context */
123695   int iCol,                               /* Value for Fts3Phrase.iColumn */
123696   const char *z, int n,                   /* Input string */
123697   Fts3Expr **ppExpr,                      /* OUT: expression */
123698   int *pnConsumed                         /* OUT: Number of bytes consumed */
123699 ){
123700   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
123701   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
123702   int rc;
123703   sqlite3_tokenizer_cursor *pCursor;
123704   Fts3Expr *pRet = 0;
123705   int nConsumed = 0;
123706
123707   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
123708   if( rc==SQLITE_OK ){
123709     const char *zToken;
123710     int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
123711     int nByte;                               /* total space to allocate */
123712
123713     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
123714     if( rc==SQLITE_OK ){
123715       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
123716       pRet = (Fts3Expr *)fts3MallocZero(nByte);
123717       if( !pRet ){
123718         rc = SQLITE_NOMEM;
123719       }else{
123720         pRet->eType = FTSQUERY_PHRASE;
123721         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
123722         pRet->pPhrase->nToken = 1;
123723         pRet->pPhrase->iColumn = iCol;
123724         pRet->pPhrase->aToken[0].n = nToken;
123725         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
123726         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
123727
123728         if( iEnd<n && z[iEnd]=='*' ){
123729           pRet->pPhrase->aToken[0].isPrefix = 1;
123730           iEnd++;
123731         }
123732
123733         while( 1 ){
123734           if( !sqlite3_fts3_enable_parentheses 
123735            && iStart>0 && z[iStart-1]=='-' 
123736           ){
123737             pParse->isNot = 1;
123738             iStart--;
123739           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
123740             pRet->pPhrase->aToken[0].bFirst = 1;
123741             iStart--;
123742           }else{
123743             break;
123744           }
123745         }
123746
123747       }
123748       nConsumed = iEnd;
123749     }
123750
123751     pModule->xClose(pCursor);
123752   }
123753   
123754   *pnConsumed = nConsumed;
123755   *ppExpr = pRet;
123756   return rc;
123757 }
123758
123759
123760 /*
123761 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
123762 ** then free the old allocation.
123763 */
123764 static void *fts3ReallocOrFree(void *pOrig, int nNew){
123765   void *pRet = sqlite3_realloc(pOrig, nNew);
123766   if( !pRet ){
123767     sqlite3_free(pOrig);
123768   }
123769   return pRet;
123770 }
123771
123772 /*
123773 ** Buffer zInput, length nInput, contains the contents of a quoted string
123774 ** that appeared as part of an fts3 query expression. Neither quote character
123775 ** is included in the buffer. This function attempts to tokenize the entire
123776 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
123777 ** containing the results.
123778 **
123779 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
123780 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
123781 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
123782 ** to 0.
123783 */
123784 static int getNextString(
123785   ParseContext *pParse,                   /* fts3 query parse context */
123786   const char *zInput, int nInput,         /* Input string */
123787   Fts3Expr **ppExpr                       /* OUT: expression */
123788 ){
123789   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
123790   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
123791   int rc;
123792   Fts3Expr *p = 0;
123793   sqlite3_tokenizer_cursor *pCursor = 0;
123794   char *zTemp = 0;
123795   int nTemp = 0;
123796
123797   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
123798   int nToken = 0;
123799
123800   /* The final Fts3Expr data structure, including the Fts3Phrase,
123801   ** Fts3PhraseToken structures token buffers are all stored as a single 
123802   ** allocation so that the expression can be freed with a single call to
123803   ** sqlite3_free(). Setting this up requires a two pass approach.
123804   **
123805   ** The first pass, in the block below, uses a tokenizer cursor to iterate
123806   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
123807   ** to assemble data in two dynamic buffers:
123808   **
123809   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
123810   **             structure, followed by the array of Fts3PhraseToken 
123811   **             structures. This pass only populates the Fts3PhraseToken array.
123812   **
123813   **   Buffer zTemp: Contains copies of all tokens.
123814   **
123815   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
123816   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
123817   ** structures.
123818   */
123819   rc = sqlite3Fts3OpenTokenizer(
123820       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
123821   if( rc==SQLITE_OK ){
123822     int ii;
123823     for(ii=0; rc==SQLITE_OK; ii++){
123824       const char *zByte;
123825       int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
123826       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
123827       if( rc==SQLITE_OK ){
123828         Fts3PhraseToken *pToken;
123829
123830         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
123831         if( !p ) goto no_mem;
123832
123833         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
123834         if( !zTemp ) goto no_mem;
123835
123836         assert( nToken==ii );
123837         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
123838         memset(pToken, 0, sizeof(Fts3PhraseToken));
123839
123840         memcpy(&zTemp[nTemp], zByte, nByte);
123841         nTemp += nByte;
123842
123843         pToken->n = nByte;
123844         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
123845         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
123846         nToken = ii+1;
123847       }
123848     }
123849
123850     pModule->xClose(pCursor);
123851     pCursor = 0;
123852   }
123853
123854   if( rc==SQLITE_DONE ){
123855     int jj;
123856     char *zBuf = 0;
123857
123858     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
123859     if( !p ) goto no_mem;
123860     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
123861     p->eType = FTSQUERY_PHRASE;
123862     p->pPhrase = (Fts3Phrase *)&p[1];
123863     p->pPhrase->iColumn = pParse->iDefaultCol;
123864     p->pPhrase->nToken = nToken;
123865
123866     zBuf = (char *)&p->pPhrase->aToken[nToken];
123867     if( zTemp ){
123868       memcpy(zBuf, zTemp, nTemp);
123869       sqlite3_free(zTemp);
123870     }else{
123871       assert( nTemp==0 );
123872     }
123873
123874     for(jj=0; jj<p->pPhrase->nToken; jj++){
123875       p->pPhrase->aToken[jj].z = zBuf;
123876       zBuf += p->pPhrase->aToken[jj].n;
123877     }
123878     rc = SQLITE_OK;
123879   }
123880
123881   *ppExpr = p;
123882   return rc;
123883 no_mem:
123884
123885   if( pCursor ){
123886     pModule->xClose(pCursor);
123887   }
123888   sqlite3_free(zTemp);
123889   sqlite3_free(p);
123890   *ppExpr = 0;
123891   return SQLITE_NOMEM;
123892 }
123893
123894 /*
123895 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
123896 ** call fts3ExprParse(). So this forward declaration is required.
123897 */
123898 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
123899
123900 /*
123901 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
123902 ** structure, or set to 0 if the end of the input buffer is reached.
123903 **
123904 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
123905 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
123906 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
123907 */
123908 static int getNextNode(
123909   ParseContext *pParse,                   /* fts3 query parse context */
123910   const char *z, int n,                   /* Input string */
123911   Fts3Expr **ppExpr,                      /* OUT: expression */
123912   int *pnConsumed                         /* OUT: Number of bytes consumed */
123913 ){
123914   static const struct Fts3Keyword {
123915     char *z;                              /* Keyword text */
123916     unsigned char n;                      /* Length of the keyword */
123917     unsigned char parenOnly;              /* Only valid in paren mode */
123918     unsigned char eType;                  /* Keyword code */
123919   } aKeyword[] = {
123920     { "OR" ,  2, 0, FTSQUERY_OR   },
123921     { "AND",  3, 1, FTSQUERY_AND  },
123922     { "NOT",  3, 1, FTSQUERY_NOT  },
123923     { "NEAR", 4, 0, FTSQUERY_NEAR }
123924   };
123925   int ii;
123926   int iCol;
123927   int iColLen;
123928   int rc;
123929   Fts3Expr *pRet = 0;
123930
123931   const char *zInput = z;
123932   int nInput = n;
123933
123934   pParse->isNot = 0;
123935
123936   /* Skip over any whitespace before checking for a keyword, an open or
123937   ** close bracket, or a quoted string. 
123938   */
123939   while( nInput>0 && fts3isspace(*zInput) ){
123940     nInput--;
123941     zInput++;
123942   }
123943   if( nInput==0 ){
123944     return SQLITE_DONE;
123945   }
123946
123947   /* See if we are dealing with a keyword. */
123948   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
123949     const struct Fts3Keyword *pKey = &aKeyword[ii];
123950
123951     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
123952       continue;
123953     }
123954
123955     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
123956       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
123957       int nKey = pKey->n;
123958       char cNext;
123959
123960       /* If this is a "NEAR" keyword, check for an explicit nearness. */
123961       if( pKey->eType==FTSQUERY_NEAR ){
123962         assert( nKey==4 );
123963         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
123964           nNear = 0;
123965           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
123966             nNear = nNear * 10 + (zInput[nKey] - '0');
123967           }
123968         }
123969       }
123970
123971       /* At this point this is probably a keyword. But for that to be true,
123972       ** the next byte must contain either whitespace, an open or close
123973       ** parenthesis, a quote character, or EOF. 
123974       */
123975       cNext = zInput[nKey];
123976       if( fts3isspace(cNext) 
123977        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
123978       ){
123979         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
123980         if( !pRet ){
123981           return SQLITE_NOMEM;
123982         }
123983         pRet->eType = pKey->eType;
123984         pRet->nNear = nNear;
123985         *ppExpr = pRet;
123986         *pnConsumed = (int)((zInput - z) + nKey);
123987         return SQLITE_OK;
123988       }
123989
123990       /* Turns out that wasn't a keyword after all. This happens if the
123991       ** user has supplied a token such as "ORacle". Continue.
123992       */
123993     }
123994   }
123995
123996   /* Check for an open bracket. */
123997   if( sqlite3_fts3_enable_parentheses ){
123998     if( *zInput=='(' ){
123999       int nConsumed;
124000       pParse->nNest++;
124001       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
124002       if( rc==SQLITE_OK && !*ppExpr ){
124003         rc = SQLITE_DONE;
124004       }
124005       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
124006       return rc;
124007     }
124008   
124009     /* Check for a close bracket. */
124010     if( *zInput==')' ){
124011       pParse->nNest--;
124012       *pnConsumed = (int)((zInput - z) + 1);
124013       return SQLITE_DONE;
124014     }
124015   }
124016
124017   /* See if we are dealing with a quoted phrase. If this is the case, then
124018   ** search for the closing quote and pass the whole string to getNextString()
124019   ** for processing. This is easy to do, as fts3 has no syntax for escaping
124020   ** a quote character embedded in a string.
124021   */
124022   if( *zInput=='"' ){
124023     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
124024     *pnConsumed = (int)((zInput - z) + ii + 1);
124025     if( ii==nInput ){
124026       return SQLITE_ERROR;
124027     }
124028     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
124029   }
124030
124031
124032   /* If control flows to this point, this must be a regular token, or 
124033   ** the end of the input. Read a regular token using the sqlite3_tokenizer
124034   ** interface. Before doing so, figure out if there is an explicit
124035   ** column specifier for the token. 
124036   **
124037   ** TODO: Strangely, it is not possible to associate a column specifier
124038   ** with a quoted phrase, only with a single token. Not sure if this was
124039   ** an implementation artifact or an intentional decision when fts3 was
124040   ** first implemented. Whichever it was, this module duplicates the 
124041   ** limitation.
124042   */
124043   iCol = pParse->iDefaultCol;
124044   iColLen = 0;
124045   for(ii=0; ii<pParse->nCol; ii++){
124046     const char *zStr = pParse->azCol[ii];
124047     int nStr = (int)strlen(zStr);
124048     if( nInput>nStr && zInput[nStr]==':' 
124049      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
124050     ){
124051       iCol = ii;
124052       iColLen = (int)((zInput - z) + nStr + 1);
124053       break;
124054     }
124055   }
124056   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
124057   *pnConsumed += iColLen;
124058   return rc;
124059 }
124060
124061 /*
124062 ** The argument is an Fts3Expr structure for a binary operator (any type
124063 ** except an FTSQUERY_PHRASE). Return an integer value representing the
124064 ** precedence of the operator. Lower values have a higher precedence (i.e.
124065 ** group more tightly). For example, in the C language, the == operator
124066 ** groups more tightly than ||, and would therefore have a higher precedence.
124067 **
124068 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
124069 ** is defined), the order of the operators in precedence from highest to
124070 ** lowest is:
124071 **
124072 **   NEAR
124073 **   NOT
124074 **   AND (including implicit ANDs)
124075 **   OR
124076 **
124077 ** Note that when using the old query syntax, the OR operator has a higher
124078 ** precedence than the AND operator.
124079 */
124080 static int opPrecedence(Fts3Expr *p){
124081   assert( p->eType!=FTSQUERY_PHRASE );
124082   if( sqlite3_fts3_enable_parentheses ){
124083     return p->eType;
124084   }else if( p->eType==FTSQUERY_NEAR ){
124085     return 1;
124086   }else if( p->eType==FTSQUERY_OR ){
124087     return 2;
124088   }
124089   assert( p->eType==FTSQUERY_AND );
124090   return 3;
124091 }
124092
124093 /*
124094 ** Argument ppHead contains a pointer to the current head of a query 
124095 ** expression tree being parsed. pPrev is the expression node most recently
124096 ** inserted into the tree. This function adds pNew, which is always a binary
124097 ** operator node, into the expression tree based on the relative precedence
124098 ** of pNew and the existing nodes of the tree. This may result in the head
124099 ** of the tree changing, in which case *ppHead is set to the new root node.
124100 */
124101 static void insertBinaryOperator(
124102   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
124103   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
124104   Fts3Expr *pNew           /* New binary node to insert into expression tree */
124105 ){
124106   Fts3Expr *pSplit = pPrev;
124107   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
124108     pSplit = pSplit->pParent;
124109   }
124110
124111   if( pSplit->pParent ){
124112     assert( pSplit->pParent->pRight==pSplit );
124113     pSplit->pParent->pRight = pNew;
124114     pNew->pParent = pSplit->pParent;
124115   }else{
124116     *ppHead = pNew;
124117   }
124118   pNew->pLeft = pSplit;
124119   pSplit->pParent = pNew;
124120 }
124121
124122 /*
124123 ** Parse the fts3 query expression found in buffer z, length n. This function
124124 ** returns either when the end of the buffer is reached or an unmatched 
124125 ** closing bracket - ')' - is encountered.
124126 **
124127 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
124128 ** parsed form of the expression and *pnConsumed is set to the number of
124129 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
124130 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
124131 */
124132 static int fts3ExprParse(
124133   ParseContext *pParse,                   /* fts3 query parse context */
124134   const char *z, int n,                   /* Text of MATCH query */
124135   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
124136   int *pnConsumed                         /* OUT: Number of bytes consumed */
124137 ){
124138   Fts3Expr *pRet = 0;
124139   Fts3Expr *pPrev = 0;
124140   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
124141   int nIn = n;
124142   const char *zIn = z;
124143   int rc = SQLITE_OK;
124144   int isRequirePhrase = 1;
124145
124146   while( rc==SQLITE_OK ){
124147     Fts3Expr *p = 0;
124148     int nByte = 0;
124149     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
124150     if( rc==SQLITE_OK ){
124151       int isPhrase;
124152
124153       if( !sqlite3_fts3_enable_parentheses 
124154        && p->eType==FTSQUERY_PHRASE && pParse->isNot 
124155       ){
124156         /* Create an implicit NOT operator. */
124157         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
124158         if( !pNot ){
124159           sqlite3Fts3ExprFree(p);
124160           rc = SQLITE_NOMEM;
124161           goto exprparse_out;
124162         }
124163         pNot->eType = FTSQUERY_NOT;
124164         pNot->pRight = p;
124165         if( pNotBranch ){
124166           pNot->pLeft = pNotBranch;
124167         }
124168         pNotBranch = pNot;
124169         p = pPrev;
124170       }else{
124171         int eType = p->eType;
124172         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
124173
124174         /* The isRequirePhrase variable is set to true if a phrase or
124175         ** an expression contained in parenthesis is required. If a
124176         ** binary operator (AND, OR, NOT or NEAR) is encounted when
124177         ** isRequirePhrase is set, this is a syntax error.
124178         */
124179         if( !isPhrase && isRequirePhrase ){
124180           sqlite3Fts3ExprFree(p);
124181           rc = SQLITE_ERROR;
124182           goto exprparse_out;
124183         }
124184   
124185         if( isPhrase && !isRequirePhrase ){
124186           /* Insert an implicit AND operator. */
124187           Fts3Expr *pAnd;
124188           assert( pRet && pPrev );
124189           pAnd = fts3MallocZero(sizeof(Fts3Expr));
124190           if( !pAnd ){
124191             sqlite3Fts3ExprFree(p);
124192             rc = SQLITE_NOMEM;
124193             goto exprparse_out;
124194           }
124195           pAnd->eType = FTSQUERY_AND;
124196           insertBinaryOperator(&pRet, pPrev, pAnd);
124197           pPrev = pAnd;
124198         }
124199
124200         /* This test catches attempts to make either operand of a NEAR
124201         ** operator something other than a phrase. For example, either of
124202         ** the following:
124203         **
124204         **    (bracketed expression) NEAR phrase
124205         **    phrase NEAR (bracketed expression)
124206         **
124207         ** Return an error in either case.
124208         */
124209         if( pPrev && (
124210             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
124211          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
124212         )){
124213           sqlite3Fts3ExprFree(p);
124214           rc = SQLITE_ERROR;
124215           goto exprparse_out;
124216         }
124217   
124218         if( isPhrase ){
124219           if( pRet ){
124220             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
124221             pPrev->pRight = p;
124222             p->pParent = pPrev;
124223           }else{
124224             pRet = p;
124225           }
124226         }else{
124227           insertBinaryOperator(&pRet, pPrev, p);
124228         }
124229         isRequirePhrase = !isPhrase;
124230       }
124231       assert( nByte>0 );
124232     }
124233     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
124234     nIn -= nByte;
124235     zIn += nByte;
124236     pPrev = p;
124237   }
124238
124239   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
124240     rc = SQLITE_ERROR;
124241   }
124242
124243   if( rc==SQLITE_DONE ){
124244     rc = SQLITE_OK;
124245     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
124246       if( !pRet ){
124247         rc = SQLITE_ERROR;
124248       }else{
124249         Fts3Expr *pIter = pNotBranch;
124250         while( pIter->pLeft ){
124251           pIter = pIter->pLeft;
124252         }
124253         pIter->pLeft = pRet;
124254         pRet = pNotBranch;
124255       }
124256     }
124257   }
124258   *pnConsumed = n - nIn;
124259
124260 exprparse_out:
124261   if( rc!=SQLITE_OK ){
124262     sqlite3Fts3ExprFree(pRet);
124263     sqlite3Fts3ExprFree(pNotBranch);
124264     pRet = 0;
124265   }
124266   *ppExpr = pRet;
124267   return rc;
124268 }
124269
124270 /*
124271 ** Parameters z and n contain a pointer to and length of a buffer containing
124272 ** an fts3 query expression, respectively. This function attempts to parse the
124273 ** query expression and create a tree of Fts3Expr structures representing the
124274 ** parsed expression. If successful, *ppExpr is set to point to the head
124275 ** of the parsed expression tree and SQLITE_OK is returned. If an error
124276 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
124277 ** error) is returned and *ppExpr is set to 0.
124278 **
124279 ** If parameter n is a negative number, then z is assumed to point to a
124280 ** nul-terminated string and the length is determined using strlen().
124281 **
124282 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
124283 ** use to normalize query tokens while parsing the expression. The azCol[]
124284 ** array, which is assumed to contain nCol entries, should contain the names
124285 ** of each column in the target fts3 table, in order from left to right. 
124286 ** Column names must be nul-terminated strings.
124287 **
124288 ** The iDefaultCol parameter should be passed the index of the table column
124289 ** that appears on the left-hand-side of the MATCH operator (the default
124290 ** column to match against for tokens for which a column name is not explicitly
124291 ** specified as part of the query string), or -1 if tokens may by default
124292 ** match any table column.
124293 */
124294 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
124295   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
124296   int iLangid,                        /* Language id for tokenizer */
124297   char **azCol,                       /* Array of column names for fts3 table */
124298   int bFts4,                          /* True to allow FTS4-only syntax */
124299   int nCol,                           /* Number of entries in azCol[] */
124300   int iDefaultCol,                    /* Default column to query */
124301   const char *z, int n,               /* Text of MATCH query */
124302   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
124303 ){
124304   int nParsed;
124305   int rc;
124306   ParseContext sParse;
124307
124308   memset(&sParse, 0, sizeof(ParseContext));
124309   sParse.pTokenizer = pTokenizer;
124310   sParse.iLangid = iLangid;
124311   sParse.azCol = (const char **)azCol;
124312   sParse.nCol = nCol;
124313   sParse.iDefaultCol = iDefaultCol;
124314   sParse.bFts4 = bFts4;
124315   if( z==0 ){
124316     *ppExpr = 0;
124317     return SQLITE_OK;
124318   }
124319   if( n<0 ){
124320     n = (int)strlen(z);
124321   }
124322   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
124323
124324   /* Check for mismatched parenthesis */
124325   if( rc==SQLITE_OK && sParse.nNest ){
124326     rc = SQLITE_ERROR;
124327     sqlite3Fts3ExprFree(*ppExpr);
124328     *ppExpr = 0;
124329   }
124330
124331   return rc;
124332 }
124333
124334 /*
124335 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
124336 */
124337 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
124338   if( p ){
124339     assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
124340     sqlite3Fts3ExprFree(p->pLeft);
124341     sqlite3Fts3ExprFree(p->pRight);
124342     sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
124343     sqlite3_free(p->aMI);
124344     sqlite3_free(p);
124345   }
124346 }
124347
124348 /****************************************************************************
124349 *****************************************************************************
124350 ** Everything after this point is just test code.
124351 */
124352
124353 #ifdef SQLITE_TEST
124354
124355 /* #include <stdio.h> */
124356
124357 /*
124358 ** Function to query the hash-table of tokenizers (see README.tokenizers).
124359 */
124360 static int queryTestTokenizer(
124361   sqlite3 *db, 
124362   const char *zName,  
124363   const sqlite3_tokenizer_module **pp
124364 ){
124365   int rc;
124366   sqlite3_stmt *pStmt;
124367   const char zSql[] = "SELECT fts3_tokenizer(?)";
124368
124369   *pp = 0;
124370   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124371   if( rc!=SQLITE_OK ){
124372     return rc;
124373   }
124374
124375   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
124376   if( SQLITE_ROW==sqlite3_step(pStmt) ){
124377     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
124378       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
124379     }
124380   }
124381
124382   return sqlite3_finalize(pStmt);
124383 }
124384
124385 /*
124386 ** Return a pointer to a buffer containing a text representation of the
124387 ** expression passed as the first argument. The buffer is obtained from
124388 ** sqlite3_malloc(). It is the responsibility of the caller to use 
124389 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
124390 ** NULL is returned.
124391 **
124392 ** If the second argument is not NULL, then its contents are prepended to 
124393 ** the returned expression text and then freed using sqlite3_free().
124394 */
124395 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
124396   switch( pExpr->eType ){
124397     case FTSQUERY_PHRASE: {
124398       Fts3Phrase *pPhrase = pExpr->pPhrase;
124399       int i;
124400       zBuf = sqlite3_mprintf(
124401           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
124402       for(i=0; zBuf && i<pPhrase->nToken; i++){
124403         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
124404             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
124405             (pPhrase->aToken[i].isPrefix?"+":"")
124406         );
124407       }
124408       return zBuf;
124409     }
124410
124411     case FTSQUERY_NEAR:
124412       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
124413       break;
124414     case FTSQUERY_NOT:
124415       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
124416       break;
124417     case FTSQUERY_AND:
124418       zBuf = sqlite3_mprintf("%zAND ", zBuf);
124419       break;
124420     case FTSQUERY_OR:
124421       zBuf = sqlite3_mprintf("%zOR ", zBuf);
124422       break;
124423   }
124424
124425   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
124426   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
124427   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
124428
124429   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
124430   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
124431
124432   return zBuf;
124433 }
124434
124435 /*
124436 ** This is the implementation of a scalar SQL function used to test the 
124437 ** expression parser. It should be called as follows:
124438 **
124439 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
124440 **
124441 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
124442 ** to parse the query expression (see README.tokenizers). The second argument
124443 ** is the query expression to parse. Each subsequent argument is the name
124444 ** of a column of the fts3 table that the query expression may refer to.
124445 ** For example:
124446 **
124447 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
124448 */
124449 static void fts3ExprTest(
124450   sqlite3_context *context,
124451   int argc,
124452   sqlite3_value **argv
124453 ){
124454   sqlite3_tokenizer_module const *pModule = 0;
124455   sqlite3_tokenizer *pTokenizer = 0;
124456   int rc;
124457   char **azCol = 0;
124458   const char *zExpr;
124459   int nExpr;
124460   int nCol;
124461   int ii;
124462   Fts3Expr *pExpr;
124463   char *zBuf = 0;
124464   sqlite3 *db = sqlite3_context_db_handle(context);
124465
124466   if( argc<3 ){
124467     sqlite3_result_error(context, 
124468         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
124469     );
124470     return;
124471   }
124472
124473   rc = queryTestTokenizer(db,
124474                           (const char *)sqlite3_value_text(argv[0]), &pModule);
124475   if( rc==SQLITE_NOMEM ){
124476     sqlite3_result_error_nomem(context);
124477     goto exprtest_out;
124478   }else if( !pModule ){
124479     sqlite3_result_error(context, "No such tokenizer module", -1);
124480     goto exprtest_out;
124481   }
124482
124483   rc = pModule->xCreate(0, 0, &pTokenizer);
124484   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
124485   if( rc==SQLITE_NOMEM ){
124486     sqlite3_result_error_nomem(context);
124487     goto exprtest_out;
124488   }
124489   pTokenizer->pModule = pModule;
124490
124491   zExpr = (const char *)sqlite3_value_text(argv[1]);
124492   nExpr = sqlite3_value_bytes(argv[1]);
124493   nCol = argc-2;
124494   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
124495   if( !azCol ){
124496     sqlite3_result_error_nomem(context);
124497     goto exprtest_out;
124498   }
124499   for(ii=0; ii<nCol; ii++){
124500     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
124501   }
124502
124503   rc = sqlite3Fts3ExprParse(
124504       pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
124505   );
124506   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
124507     sqlite3_result_error(context, "Error parsing expression", -1);
124508   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
124509     sqlite3_result_error_nomem(context);
124510   }else{
124511     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
124512     sqlite3_free(zBuf);
124513   }
124514
124515   sqlite3Fts3ExprFree(pExpr);
124516
124517 exprtest_out:
124518   if( pModule && pTokenizer ){
124519     rc = pModule->xDestroy(pTokenizer);
124520   }
124521   sqlite3_free(azCol);
124522 }
124523
124524 /*
124525 ** Register the query expression parser test function fts3_exprtest() 
124526 ** with database connection db. 
124527 */
124528 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
124529   return sqlite3_create_function(
124530       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
124531   );
124532 }
124533
124534 #endif
124535 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124536
124537 /************** End of fts3_expr.c *******************************************/
124538 /************** Begin file fts3_hash.c ***************************************/
124539 /*
124540 ** 2001 September 22
124541 **
124542 ** The author disclaims copyright to this source code.  In place of
124543 ** a legal notice, here is a blessing:
124544 **
124545 **    May you do good and not evil.
124546 **    May you find forgiveness for yourself and forgive others.
124547 **    May you share freely, never taking more than you give.
124548 **
124549 *************************************************************************
124550 ** This is the implementation of generic hash-tables used in SQLite.
124551 ** We've modified it slightly to serve as a standalone hash table
124552 ** implementation for the full-text indexing module.
124553 */
124554
124555 /*
124556 ** The code in this file is only compiled if:
124557 **
124558 **     * The FTS3 module is being built as an extension
124559 **       (in which case SQLITE_CORE is not defined), or
124560 **
124561 **     * The FTS3 module is being built into the core of
124562 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124563 */
124564 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124565
124566 /* #include <assert.h> */
124567 /* #include <stdlib.h> */
124568 /* #include <string.h> */
124569
124570
124571 /*
124572 ** Malloc and Free functions
124573 */
124574 static void *fts3HashMalloc(int n){
124575   void *p = sqlite3_malloc(n);
124576   if( p ){
124577     memset(p, 0, n);
124578   }
124579   return p;
124580 }
124581 static void fts3HashFree(void *p){
124582   sqlite3_free(p);
124583 }
124584
124585 /* Turn bulk memory into a hash table object by initializing the
124586 ** fields of the Hash structure.
124587 **
124588 ** "pNew" is a pointer to the hash table that is to be initialized.
124589 ** keyClass is one of the constants 
124590 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
124591 ** determines what kind of key the hash table will use.  "copyKey" is
124592 ** true if the hash table should make its own private copy of keys and
124593 ** false if it should just use the supplied pointer.
124594 */
124595 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
124596   assert( pNew!=0 );
124597   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
124598   pNew->keyClass = keyClass;
124599   pNew->copyKey = copyKey;
124600   pNew->first = 0;
124601   pNew->count = 0;
124602   pNew->htsize = 0;
124603   pNew->ht = 0;
124604 }
124605
124606 /* Remove all entries from a hash table.  Reclaim all memory.
124607 ** Call this routine to delete a hash table or to reset a hash table
124608 ** to the empty state.
124609 */
124610 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
124611   Fts3HashElem *elem;         /* For looping over all elements of the table */
124612
124613   assert( pH!=0 );
124614   elem = pH->first;
124615   pH->first = 0;
124616   fts3HashFree(pH->ht);
124617   pH->ht = 0;
124618   pH->htsize = 0;
124619   while( elem ){
124620     Fts3HashElem *next_elem = elem->next;
124621     if( pH->copyKey && elem->pKey ){
124622       fts3HashFree(elem->pKey);
124623     }
124624     fts3HashFree(elem);
124625     elem = next_elem;
124626   }
124627   pH->count = 0;
124628 }
124629
124630 /*
124631 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
124632 */
124633 static int fts3StrHash(const void *pKey, int nKey){
124634   const char *z = (const char *)pKey;
124635   int h = 0;
124636   if( nKey<=0 ) nKey = (int) strlen(z);
124637   while( nKey > 0  ){
124638     h = (h<<3) ^ h ^ *z++;
124639     nKey--;
124640   }
124641   return h & 0x7fffffff;
124642 }
124643 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
124644   if( n1!=n2 ) return 1;
124645   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
124646 }
124647
124648 /*
124649 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
124650 */
124651 static int fts3BinHash(const void *pKey, int nKey){
124652   int h = 0;
124653   const char *z = (const char *)pKey;
124654   while( nKey-- > 0 ){
124655     h = (h<<3) ^ h ^ *(z++);
124656   }
124657   return h & 0x7fffffff;
124658 }
124659 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
124660   if( n1!=n2 ) return 1;
124661   return memcmp(pKey1,pKey2,n1);
124662 }
124663
124664 /*
124665 ** Return a pointer to the appropriate hash function given the key class.
124666 **
124667 ** The C syntax in this function definition may be unfamilar to some 
124668 ** programmers, so we provide the following additional explanation:
124669 **
124670 ** The name of the function is "ftsHashFunction".  The function takes a
124671 ** single parameter "keyClass".  The return value of ftsHashFunction()
124672 ** is a pointer to another function.  Specifically, the return value
124673 ** of ftsHashFunction() is a pointer to a function that takes two parameters
124674 ** with types "const void*" and "int" and returns an "int".
124675 */
124676 static int (*ftsHashFunction(int keyClass))(const void*,int){
124677   if( keyClass==FTS3_HASH_STRING ){
124678     return &fts3StrHash;
124679   }else{
124680     assert( keyClass==FTS3_HASH_BINARY );
124681     return &fts3BinHash;
124682   }
124683 }
124684
124685 /*
124686 ** Return a pointer to the appropriate hash function given the key class.
124687 **
124688 ** For help in interpreted the obscure C code in the function definition,
124689 ** see the header comment on the previous function.
124690 */
124691 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
124692   if( keyClass==FTS3_HASH_STRING ){
124693     return &fts3StrCompare;
124694   }else{
124695     assert( keyClass==FTS3_HASH_BINARY );
124696     return &fts3BinCompare;
124697   }
124698 }
124699
124700 /* Link an element into the hash table
124701 */
124702 static void fts3HashInsertElement(
124703   Fts3Hash *pH,            /* The complete hash table */
124704   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
124705   Fts3HashElem *pNew       /* The element to be inserted */
124706 ){
124707   Fts3HashElem *pHead;     /* First element already in pEntry */
124708   pHead = pEntry->chain;
124709   if( pHead ){
124710     pNew->next = pHead;
124711     pNew->prev = pHead->prev;
124712     if( pHead->prev ){ pHead->prev->next = pNew; }
124713     else             { pH->first = pNew; }
124714     pHead->prev = pNew;
124715   }else{
124716     pNew->next = pH->first;
124717     if( pH->first ){ pH->first->prev = pNew; }
124718     pNew->prev = 0;
124719     pH->first = pNew;
124720   }
124721   pEntry->count++;
124722   pEntry->chain = pNew;
124723 }
124724
124725
124726 /* Resize the hash table so that it cantains "new_size" buckets.
124727 ** "new_size" must be a power of 2.  The hash table might fail 
124728 ** to resize if sqliteMalloc() fails.
124729 **
124730 ** Return non-zero if a memory allocation error occurs.
124731 */
124732 static int fts3Rehash(Fts3Hash *pH, int new_size){
124733   struct _fts3ht *new_ht;          /* The new hash table */
124734   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
124735   int (*xHash)(const void*,int);   /* The hash function */
124736
124737   assert( (new_size & (new_size-1))==0 );
124738   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
124739   if( new_ht==0 ) return 1;
124740   fts3HashFree(pH->ht);
124741   pH->ht = new_ht;
124742   pH->htsize = new_size;
124743   xHash = ftsHashFunction(pH->keyClass);
124744   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
124745     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
124746     next_elem = elem->next;
124747     fts3HashInsertElement(pH, &new_ht[h], elem);
124748   }
124749   return 0;
124750 }
124751
124752 /* This function (for internal use only) locates an element in an
124753 ** hash table that matches the given key.  The hash for this key has
124754 ** already been computed and is passed as the 4th parameter.
124755 */
124756 static Fts3HashElem *fts3FindElementByHash(
124757   const Fts3Hash *pH, /* The pH to be searched */
124758   const void *pKey,   /* The key we are searching for */
124759   int nKey,
124760   int h               /* The hash for this key. */
124761 ){
124762   Fts3HashElem *elem;            /* Used to loop thru the element list */
124763   int count;                     /* Number of elements left to test */
124764   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
124765
124766   if( pH->ht ){
124767     struct _fts3ht *pEntry = &pH->ht[h];
124768     elem = pEntry->chain;
124769     count = pEntry->count;
124770     xCompare = ftsCompareFunction(pH->keyClass);
124771     while( count-- && elem ){
124772       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
124773         return elem;
124774       }
124775       elem = elem->next;
124776     }
124777   }
124778   return 0;
124779 }
124780
124781 /* Remove a single entry from the hash table given a pointer to that
124782 ** element and a hash on the element's key.
124783 */
124784 static void fts3RemoveElementByHash(
124785   Fts3Hash *pH,         /* The pH containing "elem" */
124786   Fts3HashElem* elem,   /* The element to be removed from the pH */
124787   int h                 /* Hash value for the element */
124788 ){
124789   struct _fts3ht *pEntry;
124790   if( elem->prev ){
124791     elem->prev->next = elem->next; 
124792   }else{
124793     pH->first = elem->next;
124794   }
124795   if( elem->next ){
124796     elem->next->prev = elem->prev;
124797   }
124798   pEntry = &pH->ht[h];
124799   if( pEntry->chain==elem ){
124800     pEntry->chain = elem->next;
124801   }
124802   pEntry->count--;
124803   if( pEntry->count<=0 ){
124804     pEntry->chain = 0;
124805   }
124806   if( pH->copyKey && elem->pKey ){
124807     fts3HashFree(elem->pKey);
124808   }
124809   fts3HashFree( elem );
124810   pH->count--;
124811   if( pH->count<=0 ){
124812     assert( pH->first==0 );
124813     assert( pH->count==0 );
124814     fts3HashClear(pH);
124815   }
124816 }
124817
124818 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
124819   const Fts3Hash *pH, 
124820   const void *pKey, 
124821   int nKey
124822 ){
124823   int h;                          /* A hash on key */
124824   int (*xHash)(const void*,int);  /* The hash function */
124825
124826   if( pH==0 || pH->ht==0 ) return 0;
124827   xHash = ftsHashFunction(pH->keyClass);
124828   assert( xHash!=0 );
124829   h = (*xHash)(pKey,nKey);
124830   assert( (pH->htsize & (pH->htsize-1))==0 );
124831   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
124832 }
124833
124834 /* 
124835 ** Attempt to locate an element of the hash table pH with a key
124836 ** that matches pKey,nKey.  Return the data for this element if it is
124837 ** found, or NULL if there is no match.
124838 */
124839 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
124840   Fts3HashElem *pElem;            /* The element that matches key (if any) */
124841
124842   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
124843   return pElem ? pElem->data : 0;
124844 }
124845
124846 /* Insert an element into the hash table pH.  The key is pKey,nKey
124847 ** and the data is "data".
124848 **
124849 ** If no element exists with a matching key, then a new
124850 ** element is created.  A copy of the key is made if the copyKey
124851 ** flag is set.  NULL is returned.
124852 **
124853 ** If another element already exists with the same key, then the
124854 ** new data replaces the old data and the old data is returned.
124855 ** The key is not copied in this instance.  If a malloc fails, then
124856 ** the new data is returned and the hash table is unchanged.
124857 **
124858 ** If the "data" parameter to this function is NULL, then the
124859 ** element corresponding to "key" is removed from the hash table.
124860 */
124861 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
124862   Fts3Hash *pH,        /* The hash table to insert into */
124863   const void *pKey,    /* The key */
124864   int nKey,            /* Number of bytes in the key */
124865   void *data           /* The data */
124866 ){
124867   int hraw;                 /* Raw hash value of the key */
124868   int h;                    /* the hash of the key modulo hash table size */
124869   Fts3HashElem *elem;       /* Used to loop thru the element list */
124870   Fts3HashElem *new_elem;   /* New element added to the pH */
124871   int (*xHash)(const void*,int);  /* The hash function */
124872
124873   assert( pH!=0 );
124874   xHash = ftsHashFunction(pH->keyClass);
124875   assert( xHash!=0 );
124876   hraw = (*xHash)(pKey, nKey);
124877   assert( (pH->htsize & (pH->htsize-1))==0 );
124878   h = hraw & (pH->htsize-1);
124879   elem = fts3FindElementByHash(pH,pKey,nKey,h);
124880   if( elem ){
124881     void *old_data = elem->data;
124882     if( data==0 ){
124883       fts3RemoveElementByHash(pH,elem,h);
124884     }else{
124885       elem->data = data;
124886     }
124887     return old_data;
124888   }
124889   if( data==0 ) return 0;
124890   if( (pH->htsize==0 && fts3Rehash(pH,8))
124891    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
124892   ){
124893     pH->count = 0;
124894     return data;
124895   }
124896   assert( pH->htsize>0 );
124897   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
124898   if( new_elem==0 ) return data;
124899   if( pH->copyKey && pKey!=0 ){
124900     new_elem->pKey = fts3HashMalloc( nKey );
124901     if( new_elem->pKey==0 ){
124902       fts3HashFree(new_elem);
124903       return data;
124904     }
124905     memcpy((void*)new_elem->pKey, pKey, nKey);
124906   }else{
124907     new_elem->pKey = (void*)pKey;
124908   }
124909   new_elem->nKey = nKey;
124910   pH->count++;
124911   assert( pH->htsize>0 );
124912   assert( (pH->htsize & (pH->htsize-1))==0 );
124913   h = hraw & (pH->htsize-1);
124914   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
124915   new_elem->data = data;
124916   return 0;
124917 }
124918
124919 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124920
124921 /************** End of fts3_hash.c *******************************************/
124922 /************** Begin file fts3_porter.c *************************************/
124923 /*
124924 ** 2006 September 30
124925 **
124926 ** The author disclaims copyright to this source code.  In place of
124927 ** a legal notice, here is a blessing:
124928 **
124929 **    May you do good and not evil.
124930 **    May you find forgiveness for yourself and forgive others.
124931 **    May you share freely, never taking more than you give.
124932 **
124933 *************************************************************************
124934 ** Implementation of the full-text-search tokenizer that implements
124935 ** a Porter stemmer.
124936 */
124937
124938 /*
124939 ** The code in this file is only compiled if:
124940 **
124941 **     * The FTS3 module is being built as an extension
124942 **       (in which case SQLITE_CORE is not defined), or
124943 **
124944 **     * The FTS3 module is being built into the core of
124945 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124946 */
124947 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124948
124949 /* #include <assert.h> */
124950 /* #include <stdlib.h> */
124951 /* #include <stdio.h> */
124952 /* #include <string.h> */
124953
124954
124955 /*
124956 ** Class derived from sqlite3_tokenizer
124957 */
124958 typedef struct porter_tokenizer {
124959   sqlite3_tokenizer base;      /* Base class */
124960 } porter_tokenizer;
124961
124962 /*
124963 ** Class derived from sqlite3_tokenizer_cursor
124964 */
124965 typedef struct porter_tokenizer_cursor {
124966   sqlite3_tokenizer_cursor base;
124967   const char *zInput;          /* input we are tokenizing */
124968   int nInput;                  /* size of the input */
124969   int iOffset;                 /* current position in zInput */
124970   int iToken;                  /* index of next token to be returned */
124971   char *zToken;                /* storage for current token */
124972   int nAllocated;              /* space allocated to zToken buffer */
124973 } porter_tokenizer_cursor;
124974
124975
124976 /*
124977 ** Create a new tokenizer instance.
124978 */
124979 static int porterCreate(
124980   int argc, const char * const *argv,
124981   sqlite3_tokenizer **ppTokenizer
124982 ){
124983   porter_tokenizer *t;
124984
124985   UNUSED_PARAMETER(argc);
124986   UNUSED_PARAMETER(argv);
124987
124988   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
124989   if( t==NULL ) return SQLITE_NOMEM;
124990   memset(t, 0, sizeof(*t));
124991   *ppTokenizer = &t->base;
124992   return SQLITE_OK;
124993 }
124994
124995 /*
124996 ** Destroy a tokenizer
124997 */
124998 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
124999   sqlite3_free(pTokenizer);
125000   return SQLITE_OK;
125001 }
125002
125003 /*
125004 ** Prepare to begin tokenizing a particular string.  The input
125005 ** string to be tokenized is zInput[0..nInput-1].  A cursor
125006 ** used to incrementally tokenize this string is returned in 
125007 ** *ppCursor.
125008 */
125009 static int porterOpen(
125010   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
125011   const char *zInput, int nInput,        /* String to be tokenized */
125012   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
125013 ){
125014   porter_tokenizer_cursor *c;
125015
125016   UNUSED_PARAMETER(pTokenizer);
125017
125018   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
125019   if( c==NULL ) return SQLITE_NOMEM;
125020
125021   c->zInput = zInput;
125022   if( zInput==0 ){
125023     c->nInput = 0;
125024   }else if( nInput<0 ){
125025     c->nInput = (int)strlen(zInput);
125026   }else{
125027     c->nInput = nInput;
125028   }
125029   c->iOffset = 0;                 /* start tokenizing at the beginning */
125030   c->iToken = 0;
125031   c->zToken = NULL;               /* no space allocated, yet. */
125032   c->nAllocated = 0;
125033
125034   *ppCursor = &c->base;
125035   return SQLITE_OK;
125036 }
125037
125038 /*
125039 ** Close a tokenization cursor previously opened by a call to
125040 ** porterOpen() above.
125041 */
125042 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
125043   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
125044   sqlite3_free(c->zToken);
125045   sqlite3_free(c);
125046   return SQLITE_OK;
125047 }
125048 /*
125049 ** Vowel or consonant
125050 */
125051 static const char cType[] = {
125052    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
125053    1, 1, 1, 2, 1
125054 };
125055
125056 /*
125057 ** isConsonant() and isVowel() determine if their first character in
125058 ** the string they point to is a consonant or a vowel, according
125059 ** to Porter ruls.  
125060 **
125061 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
125062 ** 'Y' is a consonant unless it follows another consonant,
125063 ** in which case it is a vowel.
125064 **
125065 ** In these routine, the letters are in reverse order.  So the 'y' rule
125066 ** is that 'y' is a consonant unless it is followed by another
125067 ** consonent.
125068 */
125069 static int isVowel(const char*);
125070 static int isConsonant(const char *z){
125071   int j;
125072   char x = *z;
125073   if( x==0 ) return 0;
125074   assert( x>='a' && x<='z' );
125075   j = cType[x-'a'];
125076   if( j<2 ) return j;
125077   return z[1]==0 || isVowel(z + 1);
125078 }
125079 static int isVowel(const char *z){
125080   int j;
125081   char x = *z;
125082   if( x==0 ) return 0;
125083   assert( x>='a' && x<='z' );
125084   j = cType[x-'a'];
125085   if( j<2 ) return 1-j;
125086   return isConsonant(z + 1);
125087 }
125088
125089 /*
125090 ** Let any sequence of one or more vowels be represented by V and let
125091 ** C be sequence of one or more consonants.  Then every word can be
125092 ** represented as:
125093 **
125094 **           [C] (VC){m} [V]
125095 **
125096 ** In prose:  A word is an optional consonant followed by zero or
125097 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
125098 ** number of vowel consonant pairs.  This routine computes the value
125099 ** of m for the first i bytes of a word.
125100 **
125101 ** Return true if the m-value for z is 1 or more.  In other words,
125102 ** return true if z contains at least one vowel that is followed
125103 ** by a consonant.
125104 **
125105 ** In this routine z[] is in reverse order.  So we are really looking
125106 ** for an instance of of a consonant followed by a vowel.
125107 */
125108 static int m_gt_0(const char *z){
125109   while( isVowel(z) ){ z++; }
125110   if( *z==0 ) return 0;
125111   while( isConsonant(z) ){ z++; }
125112   return *z!=0;
125113 }
125114
125115 /* Like mgt0 above except we are looking for a value of m which is
125116 ** exactly 1
125117 */
125118 static int m_eq_1(const char *z){
125119   while( isVowel(z) ){ z++; }
125120   if( *z==0 ) return 0;
125121   while( isConsonant(z) ){ z++; }
125122   if( *z==0 ) return 0;
125123   while( isVowel(z) ){ z++; }
125124   if( *z==0 ) return 1;
125125   while( isConsonant(z) ){ z++; }
125126   return *z==0;
125127 }
125128
125129 /* Like mgt0 above except we are looking for a value of m>1 instead
125130 ** or m>0
125131 */
125132 static int m_gt_1(const char *z){
125133   while( isVowel(z) ){ z++; }
125134   if( *z==0 ) return 0;
125135   while( isConsonant(z) ){ z++; }
125136   if( *z==0 ) return 0;
125137   while( isVowel(z) ){ z++; }
125138   if( *z==0 ) return 0;
125139   while( isConsonant(z) ){ z++; }
125140   return *z!=0;
125141 }
125142
125143 /*
125144 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
125145 */
125146 static int hasVowel(const char *z){
125147   while( isConsonant(z) ){ z++; }
125148   return *z!=0;
125149 }
125150
125151 /*
125152 ** Return TRUE if the word ends in a double consonant.
125153 **
125154 ** The text is reversed here. So we are really looking at
125155 ** the first two characters of z[].
125156 */
125157 static int doubleConsonant(const char *z){
125158   return isConsonant(z) && z[0]==z[1];
125159 }
125160
125161 /*
125162 ** Return TRUE if the word ends with three letters which
125163 ** are consonant-vowel-consonent and where the final consonant
125164 ** is not 'w', 'x', or 'y'.
125165 **
125166 ** The word is reversed here.  So we are really checking the
125167 ** first three letters and the first one cannot be in [wxy].
125168 */
125169 static int star_oh(const char *z){
125170   return
125171     isConsonant(z) &&
125172     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
125173     isVowel(z+1) &&
125174     isConsonant(z+2);
125175 }
125176
125177 /*
125178 ** If the word ends with zFrom and xCond() is true for the stem
125179 ** of the word that preceeds the zFrom ending, then change the 
125180 ** ending to zTo.
125181 **
125182 ** The input word *pz and zFrom are both in reverse order.  zTo
125183 ** is in normal order. 
125184 **
125185 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
125186 ** match.  Not that TRUE is returned even if xCond() fails and
125187 ** no substitution occurs.
125188 */
125189 static int stem(
125190   char **pz,             /* The word being stemmed (Reversed) */
125191   const char *zFrom,     /* If the ending matches this... (Reversed) */
125192   const char *zTo,       /* ... change the ending to this (not reversed) */
125193   int (*xCond)(const char*)   /* Condition that must be true */
125194 ){
125195   char *z = *pz;
125196   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
125197   if( *zFrom!=0 ) return 0;
125198   if( xCond && !xCond(z) ) return 1;
125199   while( *zTo ){
125200     *(--z) = *(zTo++);
125201   }
125202   *pz = z;
125203   return 1;
125204 }
125205
125206 /*
125207 ** This is the fallback stemmer used when the porter stemmer is
125208 ** inappropriate.  The input word is copied into the output with
125209 ** US-ASCII case folding.  If the input word is too long (more
125210 ** than 20 bytes if it contains no digits or more than 6 bytes if
125211 ** it contains digits) then word is truncated to 20 or 6 bytes
125212 ** by taking 10 or 3 bytes from the beginning and end.
125213 */
125214 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
125215   int i, mx, j;
125216   int hasDigit = 0;
125217   for(i=0; i<nIn; i++){
125218     char c = zIn[i];
125219     if( c>='A' && c<='Z' ){
125220       zOut[i] = c - 'A' + 'a';
125221     }else{
125222       if( c>='0' && c<='9' ) hasDigit = 1;
125223       zOut[i] = c;
125224     }
125225   }
125226   mx = hasDigit ? 3 : 10;
125227   if( nIn>mx*2 ){
125228     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
125229       zOut[j] = zOut[i];
125230     }
125231     i = j;
125232   }
125233   zOut[i] = 0;
125234   *pnOut = i;
125235 }
125236
125237
125238 /*
125239 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
125240 ** zOut is at least big enough to hold nIn bytes.  Write the actual
125241 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
125242 **
125243 ** Any upper-case characters in the US-ASCII character set ([A-Z])
125244 ** are converted to lower case.  Upper-case UTF characters are
125245 ** unchanged.
125246 **
125247 ** Words that are longer than about 20 bytes are stemmed by retaining
125248 ** a few bytes from the beginning and the end of the word.  If the
125249 ** word contains digits, 3 bytes are taken from the beginning and
125250 ** 3 bytes from the end.  For long words without digits, 10 bytes
125251 ** are taken from each end.  US-ASCII case folding still applies.
125252 ** 
125253 ** If the input word contains not digits but does characters not 
125254 ** in [a-zA-Z] then no stemming is attempted and this routine just 
125255 ** copies the input into the input into the output with US-ASCII
125256 ** case folding.
125257 **
125258 ** Stemming never increases the length of the word.  So there is
125259 ** no chance of overflowing the zOut buffer.
125260 */
125261 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
125262   int i, j;
125263   char zReverse[28];
125264   char *z, *z2;
125265   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
125266     /* The word is too big or too small for the porter stemmer.
125267     ** Fallback to the copy stemmer */
125268     copy_stemmer(zIn, nIn, zOut, pnOut);
125269     return;
125270   }
125271   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
125272     char c = zIn[i];
125273     if( c>='A' && c<='Z' ){
125274       zReverse[j] = c + 'a' - 'A';
125275     }else if( c>='a' && c<='z' ){
125276       zReverse[j] = c;
125277     }else{
125278       /* The use of a character not in [a-zA-Z] means that we fallback
125279       ** to the copy stemmer */
125280       copy_stemmer(zIn, nIn, zOut, pnOut);
125281       return;
125282     }
125283   }
125284   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
125285   z = &zReverse[j+1];
125286
125287
125288   /* Step 1a */
125289   if( z[0]=='s' ){
125290     if(
125291      !stem(&z, "sess", "ss", 0) &&
125292      !stem(&z, "sei", "i", 0)  &&
125293      !stem(&z, "ss", "ss", 0)
125294     ){
125295       z++;
125296     }
125297   }
125298
125299   /* Step 1b */  
125300   z2 = z;
125301   if( stem(&z, "dee", "ee", m_gt_0) ){
125302     /* Do nothing.  The work was all in the test */
125303   }else if( 
125304      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
125305       && z!=z2
125306   ){
125307      if( stem(&z, "ta", "ate", 0) ||
125308          stem(&z, "lb", "ble", 0) ||
125309          stem(&z, "zi", "ize", 0) ){
125310        /* Do nothing.  The work was all in the test */
125311      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
125312        z++;
125313      }else if( m_eq_1(z) && star_oh(z) ){
125314        *(--z) = 'e';
125315      }
125316   }
125317
125318   /* Step 1c */
125319   if( z[0]=='y' && hasVowel(z+1) ){
125320     z[0] = 'i';
125321   }
125322
125323   /* Step 2 */
125324   switch( z[1] ){
125325    case 'a':
125326      stem(&z, "lanoita", "ate", m_gt_0) ||
125327      stem(&z, "lanoit", "tion", m_gt_0);
125328      break;
125329    case 'c':
125330      stem(&z, "icne", "ence", m_gt_0) ||
125331      stem(&z, "icna", "ance", m_gt_0);
125332      break;
125333    case 'e':
125334      stem(&z, "rezi", "ize", m_gt_0);
125335      break;
125336    case 'g':
125337      stem(&z, "igol", "log", m_gt_0);
125338      break;
125339    case 'l':
125340      stem(&z, "ilb", "ble", m_gt_0) ||
125341      stem(&z, "illa", "al", m_gt_0) ||
125342      stem(&z, "iltne", "ent", m_gt_0) ||
125343      stem(&z, "ile", "e", m_gt_0) ||
125344      stem(&z, "ilsuo", "ous", m_gt_0);
125345      break;
125346    case 'o':
125347      stem(&z, "noitazi", "ize", m_gt_0) ||
125348      stem(&z, "noita", "ate", m_gt_0) ||
125349      stem(&z, "rota", "ate", m_gt_0);
125350      break;
125351    case 's':
125352      stem(&z, "msila", "al", m_gt_0) ||
125353      stem(&z, "ssenevi", "ive", m_gt_0) ||
125354      stem(&z, "ssenluf", "ful", m_gt_0) ||
125355      stem(&z, "ssensuo", "ous", m_gt_0);
125356      break;
125357    case 't':
125358      stem(&z, "itila", "al", m_gt_0) ||
125359      stem(&z, "itivi", "ive", m_gt_0) ||
125360      stem(&z, "itilib", "ble", m_gt_0);
125361      break;
125362   }
125363
125364   /* Step 3 */
125365   switch( z[0] ){
125366    case 'e':
125367      stem(&z, "etaci", "ic", m_gt_0) ||
125368      stem(&z, "evita", "", m_gt_0)   ||
125369      stem(&z, "ezila", "al", m_gt_0);
125370      break;
125371    case 'i':
125372      stem(&z, "itici", "ic", m_gt_0);
125373      break;
125374    case 'l':
125375      stem(&z, "laci", "ic", m_gt_0) ||
125376      stem(&z, "luf", "", m_gt_0);
125377      break;
125378    case 's':
125379      stem(&z, "ssen", "", m_gt_0);
125380      break;
125381   }
125382
125383   /* Step 4 */
125384   switch( z[1] ){
125385    case 'a':
125386      if( z[0]=='l' && m_gt_1(z+2) ){
125387        z += 2;
125388      }
125389      break;
125390    case 'c':
125391      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
125392        z += 4;
125393      }
125394      break;
125395    case 'e':
125396      if( z[0]=='r' && m_gt_1(z+2) ){
125397        z += 2;
125398      }
125399      break;
125400    case 'i':
125401      if( z[0]=='c' && m_gt_1(z+2) ){
125402        z += 2;
125403      }
125404      break;
125405    case 'l':
125406      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
125407        z += 4;
125408      }
125409      break;
125410    case 'n':
125411      if( z[0]=='t' ){
125412        if( z[2]=='a' ){
125413          if( m_gt_1(z+3) ){
125414            z += 3;
125415          }
125416        }else if( z[2]=='e' ){
125417          stem(&z, "tneme", "", m_gt_1) ||
125418          stem(&z, "tnem", "", m_gt_1) ||
125419          stem(&z, "tne", "", m_gt_1);
125420        }
125421      }
125422      break;
125423    case 'o':
125424      if( z[0]=='u' ){
125425        if( m_gt_1(z+2) ){
125426          z += 2;
125427        }
125428      }else if( z[3]=='s' || z[3]=='t' ){
125429        stem(&z, "noi", "", m_gt_1);
125430      }
125431      break;
125432    case 's':
125433      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
125434        z += 3;
125435      }
125436      break;
125437    case 't':
125438      stem(&z, "eta", "", m_gt_1) ||
125439      stem(&z, "iti", "", m_gt_1);
125440      break;
125441    case 'u':
125442      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
125443        z += 3;
125444      }
125445      break;
125446    case 'v':
125447    case 'z':
125448      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
125449        z += 3;
125450      }
125451      break;
125452   }
125453
125454   /* Step 5a */
125455   if( z[0]=='e' ){
125456     if( m_gt_1(z+1) ){
125457       z++;
125458     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
125459       z++;
125460     }
125461   }
125462
125463   /* Step 5b */
125464   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
125465     z++;
125466   }
125467
125468   /* z[] is now the stemmed word in reverse order.  Flip it back
125469   ** around into forward order and return.
125470   */
125471   *pnOut = i = (int)strlen(z);
125472   zOut[i] = 0;
125473   while( *z ){
125474     zOut[--i] = *(z++);
125475   }
125476 }
125477
125478 /*
125479 ** Characters that can be part of a token.  We assume any character
125480 ** whose value is greater than 0x80 (any UTF character) can be
125481 ** part of a token.  In other words, delimiters all must have
125482 ** values of 0x7f or lower.
125483 */
125484 static const char porterIdChar[] = {
125485 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
125486     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
125487     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
125488     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
125489     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
125490     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
125491 };
125492 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
125493
125494 /*
125495 ** Extract the next token from a tokenization cursor.  The cursor must
125496 ** have been opened by a prior call to porterOpen().
125497 */
125498 static int porterNext(
125499   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
125500   const char **pzToken,               /* OUT: *pzToken is the token text */
125501   int *pnBytes,                       /* OUT: Number of bytes in token */
125502   int *piStartOffset,                 /* OUT: Starting offset of token */
125503   int *piEndOffset,                   /* OUT: Ending offset of token */
125504   int *piPosition                     /* OUT: Position integer of token */
125505 ){
125506   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
125507   const char *z = c->zInput;
125508
125509   while( c->iOffset<c->nInput ){
125510     int iStartOffset, ch;
125511
125512     /* Scan past delimiter characters */
125513     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
125514       c->iOffset++;
125515     }
125516
125517     /* Count non-delimiter characters. */
125518     iStartOffset = c->iOffset;
125519     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
125520       c->iOffset++;
125521     }
125522
125523     if( c->iOffset>iStartOffset ){
125524       int n = c->iOffset-iStartOffset;
125525       if( n>c->nAllocated ){
125526         char *pNew;
125527         c->nAllocated = n+20;
125528         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
125529         if( !pNew ) return SQLITE_NOMEM;
125530         c->zToken = pNew;
125531       }
125532       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
125533       *pzToken = c->zToken;
125534       *piStartOffset = iStartOffset;
125535       *piEndOffset = c->iOffset;
125536       *piPosition = c->iToken++;
125537       return SQLITE_OK;
125538     }
125539   }
125540   return SQLITE_DONE;
125541 }
125542
125543 /*
125544 ** The set of routines that implement the porter-stemmer tokenizer
125545 */
125546 static const sqlite3_tokenizer_module porterTokenizerModule = {
125547   0,
125548   porterCreate,
125549   porterDestroy,
125550   porterOpen,
125551   porterClose,
125552   porterNext,
125553   0
125554 };
125555
125556 /*
125557 ** Allocate a new porter tokenizer.  Return a pointer to the new
125558 ** tokenizer in *ppModule
125559 */
125560 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
125561   sqlite3_tokenizer_module const**ppModule
125562 ){
125563   *ppModule = &porterTokenizerModule;
125564 }
125565
125566 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125567
125568 /************** End of fts3_porter.c *****************************************/
125569 /************** Begin file fts3_tokenizer.c **********************************/
125570 /*
125571 ** 2007 June 22
125572 **
125573 ** The author disclaims copyright to this source code.  In place of
125574 ** a legal notice, here is a blessing:
125575 **
125576 **    May you do good and not evil.
125577 **    May you find forgiveness for yourself and forgive others.
125578 **    May you share freely, never taking more than you give.
125579 **
125580 ******************************************************************************
125581 **
125582 ** This is part of an SQLite module implementing full-text search.
125583 ** This particular file implements the generic tokenizer interface.
125584 */
125585
125586 /*
125587 ** The code in this file is only compiled if:
125588 **
125589 **     * The FTS3 module is being built as an extension
125590 **       (in which case SQLITE_CORE is not defined), or
125591 **
125592 **     * The FTS3 module is being built into the core of
125593 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
125594 */
125595 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125596
125597 /* #include <assert.h> */
125598 /* #include <string.h> */
125599
125600 /*
125601 ** Implementation of the SQL scalar function for accessing the underlying 
125602 ** hash table. This function may be called as follows:
125603 **
125604 **   SELECT <function-name>(<key-name>);
125605 **   SELECT <function-name>(<key-name>, <pointer>);
125606 **
125607 ** where <function-name> is the name passed as the second argument
125608 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
125609 **
125610 ** If the <pointer> argument is specified, it must be a blob value
125611 ** containing a pointer to be stored as the hash data corresponding
125612 ** to the string <key-name>. If <pointer> is not specified, then
125613 ** the string <key-name> must already exist in the has table. Otherwise,
125614 ** an error is returned.
125615 **
125616 ** Whether or not the <pointer> argument is specified, the value returned
125617 ** is a blob containing the pointer stored as the hash data corresponding
125618 ** to string <key-name> (after the hash-table is updated, if applicable).
125619 */
125620 static void scalarFunc(
125621   sqlite3_context *context,
125622   int argc,
125623   sqlite3_value **argv
125624 ){
125625   Fts3Hash *pHash;
125626   void *pPtr = 0;
125627   const unsigned char *zName;
125628   int nName;
125629
125630   assert( argc==1 || argc==2 );
125631
125632   pHash = (Fts3Hash *)sqlite3_user_data(context);
125633
125634   zName = sqlite3_value_text(argv[0]);
125635   nName = sqlite3_value_bytes(argv[0])+1;
125636
125637   if( argc==2 ){
125638     void *pOld;
125639     int n = sqlite3_value_bytes(argv[1]);
125640     if( n!=sizeof(pPtr) ){
125641       sqlite3_result_error(context, "argument type mismatch", -1);
125642       return;
125643     }
125644     pPtr = *(void **)sqlite3_value_blob(argv[1]);
125645     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
125646     if( pOld==pPtr ){
125647       sqlite3_result_error(context, "out of memory", -1);
125648       return;
125649     }
125650   }else{
125651     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
125652     if( !pPtr ){
125653       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
125654       sqlite3_result_error(context, zErr, -1);
125655       sqlite3_free(zErr);
125656       return;
125657     }
125658   }
125659
125660   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
125661 }
125662
125663 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
125664   static const char isFtsIdChar[] = {
125665       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
125666       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
125667       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
125668       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
125669       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
125670       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
125671       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
125672       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
125673   };
125674   return (c&0x80 || isFtsIdChar[(int)(c)]);
125675 }
125676
125677 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
125678   const char *z1;
125679   const char *z2 = 0;
125680
125681   /* Find the start of the next token. */
125682   z1 = zStr;
125683   while( z2==0 ){
125684     char c = *z1;
125685     switch( c ){
125686       case '\0': return 0;        /* No more tokens here */
125687       case '\'':
125688       case '"':
125689       case '`': {
125690         z2 = z1;
125691         while( *++z2 && (*z2!=c || *++z2==c) );
125692         break;
125693       }
125694       case '[':
125695         z2 = &z1[1];
125696         while( *z2 && z2[0]!=']' ) z2++;
125697         if( *z2 ) z2++;
125698         break;
125699
125700       default:
125701         if( sqlite3Fts3IsIdChar(*z1) ){
125702           z2 = &z1[1];
125703           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
125704         }else{
125705           z1++;
125706         }
125707     }
125708   }
125709
125710   *pn = (int)(z2-z1);
125711   return z1;
125712 }
125713
125714 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
125715   Fts3Hash *pHash,                /* Tokenizer hash table */
125716   const char *zArg,               /* Tokenizer name */
125717   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
125718   char **pzErr                    /* OUT: Set to malloced error message */
125719 ){
125720   int rc;
125721   char *z = (char *)zArg;
125722   int n = 0;
125723   char *zCopy;
125724   char *zEnd;                     /* Pointer to nul-term of zCopy */
125725   sqlite3_tokenizer_module *m;
125726
125727   zCopy = sqlite3_mprintf("%s", zArg);
125728   if( !zCopy ) return SQLITE_NOMEM;
125729   zEnd = &zCopy[strlen(zCopy)];
125730
125731   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
125732   z[n] = '\0';
125733   sqlite3Fts3Dequote(z);
125734
125735   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
125736   if( !m ){
125737     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
125738     rc = SQLITE_ERROR;
125739   }else{
125740     char const **aArg = 0;
125741     int iArg = 0;
125742     z = &z[n+1];
125743     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
125744       int nNew = sizeof(char *)*(iArg+1);
125745       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
125746       if( !aNew ){
125747         sqlite3_free(zCopy);
125748         sqlite3_free((void *)aArg);
125749         return SQLITE_NOMEM;
125750       }
125751       aArg = aNew;
125752       aArg[iArg++] = z;
125753       z[n] = '\0';
125754       sqlite3Fts3Dequote(z);
125755       z = &z[n+1];
125756     }
125757     rc = m->xCreate(iArg, aArg, ppTok);
125758     assert( rc!=SQLITE_OK || *ppTok );
125759     if( rc!=SQLITE_OK ){
125760       *pzErr = sqlite3_mprintf("unknown tokenizer");
125761     }else{
125762       (*ppTok)->pModule = m; 
125763     }
125764     sqlite3_free((void *)aArg);
125765   }
125766
125767   sqlite3_free(zCopy);
125768   return rc;
125769 }
125770
125771
125772 #ifdef SQLITE_TEST
125773
125774 /* #include <tcl.h> */
125775 /* #include <string.h> */
125776
125777 /*
125778 ** Implementation of a special SQL scalar function for testing tokenizers 
125779 ** designed to be used in concert with the Tcl testing framework. This
125780 ** function must be called with two or more arguments:
125781 **
125782 **   SELECT <function-name>(<key-name>, ..., <input-string>);
125783 **
125784 ** where <function-name> is the name passed as the second argument
125785 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
125786 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
125787 **
125788 ** The return value is a string that may be interpreted as a Tcl
125789 ** list. For each token in the <input-string>, three elements are
125790 ** added to the returned list. The first is the token position, the 
125791 ** second is the token text (folded, stemmed, etc.) and the third is the
125792 ** substring of <input-string> associated with the token. For example, 
125793 ** using the built-in "simple" tokenizer:
125794 **
125795 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
125796 **
125797 ** will return the string:
125798 **
125799 **   "{0 i I 1 dont don't 2 see see 3 how how}"
125800 **   
125801 */
125802 static void testFunc(
125803   sqlite3_context *context,
125804   int argc,
125805   sqlite3_value **argv
125806 ){
125807   Fts3Hash *pHash;
125808   sqlite3_tokenizer_module *p;
125809   sqlite3_tokenizer *pTokenizer = 0;
125810   sqlite3_tokenizer_cursor *pCsr = 0;
125811
125812   const char *zErr = 0;
125813
125814   const char *zName;
125815   int nName;
125816   const char *zInput;
125817   int nInput;
125818
125819   const char *azArg[64];
125820
125821   const char *zToken;
125822   int nToken = 0;
125823   int iStart = 0;
125824   int iEnd = 0;
125825   int iPos = 0;
125826   int i;
125827
125828   Tcl_Obj *pRet;
125829
125830   if( argc<2 ){
125831     sqlite3_result_error(context, "insufficient arguments", -1);
125832     return;
125833   }
125834
125835   nName = sqlite3_value_bytes(argv[0]);
125836   zName = (const char *)sqlite3_value_text(argv[0]);
125837   nInput = sqlite3_value_bytes(argv[argc-1]);
125838   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
125839
125840   pHash = (Fts3Hash *)sqlite3_user_data(context);
125841   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
125842
125843   if( !p ){
125844     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
125845     sqlite3_result_error(context, zErr, -1);
125846     sqlite3_free(zErr);
125847     return;
125848   }
125849
125850   pRet = Tcl_NewObj();
125851   Tcl_IncrRefCount(pRet);
125852
125853   for(i=1; i<argc-1; i++){
125854     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
125855   }
125856
125857   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
125858     zErr = "error in xCreate()";
125859     goto finish;
125860   }
125861   pTokenizer->pModule = p;
125862   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
125863     zErr = "error in xOpen()";
125864     goto finish;
125865   }
125866
125867   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
125868     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
125869     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
125870     zToken = &zInput[iStart];
125871     nToken = iEnd-iStart;
125872     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
125873   }
125874
125875   if( SQLITE_OK!=p->xClose(pCsr) ){
125876     zErr = "error in xClose()";
125877     goto finish;
125878   }
125879   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
125880     zErr = "error in xDestroy()";
125881     goto finish;
125882   }
125883
125884 finish:
125885   if( zErr ){
125886     sqlite3_result_error(context, zErr, -1);
125887   }else{
125888     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
125889   }
125890   Tcl_DecrRefCount(pRet);
125891 }
125892
125893 static
125894 int registerTokenizer(
125895   sqlite3 *db, 
125896   char *zName, 
125897   const sqlite3_tokenizer_module *p
125898 ){
125899   int rc;
125900   sqlite3_stmt *pStmt;
125901   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
125902
125903   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
125904   if( rc!=SQLITE_OK ){
125905     return rc;
125906   }
125907
125908   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
125909   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
125910   sqlite3_step(pStmt);
125911
125912   return sqlite3_finalize(pStmt);
125913 }
125914
125915 static
125916 int queryTokenizer(
125917   sqlite3 *db, 
125918   char *zName,  
125919   const sqlite3_tokenizer_module **pp
125920 ){
125921   int rc;
125922   sqlite3_stmt *pStmt;
125923   const char zSql[] = "SELECT fts3_tokenizer(?)";
125924
125925   *pp = 0;
125926   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
125927   if( rc!=SQLITE_OK ){
125928     return rc;
125929   }
125930
125931   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
125932   if( SQLITE_ROW==sqlite3_step(pStmt) ){
125933     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
125934       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
125935     }
125936   }
125937
125938   return sqlite3_finalize(pStmt);
125939 }
125940
125941 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
125942
125943 /*
125944 ** Implementation of the scalar function fts3_tokenizer_internal_test().
125945 ** This function is used for testing only, it is not included in the
125946 ** build unless SQLITE_TEST is defined.
125947 **
125948 ** The purpose of this is to test that the fts3_tokenizer() function
125949 ** can be used as designed by the C-code in the queryTokenizer and
125950 ** registerTokenizer() functions above. These two functions are repeated
125951 ** in the README.tokenizer file as an example, so it is important to
125952 ** test them.
125953 **
125954 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
125955 ** function with no arguments. An assert() will fail if a problem is
125956 ** detected. i.e.:
125957 **
125958 **     SELECT fts3_tokenizer_internal_test();
125959 **
125960 */
125961 static void intTestFunc(
125962   sqlite3_context *context,
125963   int argc,
125964   sqlite3_value **argv
125965 ){
125966   int rc;
125967   const sqlite3_tokenizer_module *p1;
125968   const sqlite3_tokenizer_module *p2;
125969   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
125970
125971   UNUSED_PARAMETER(argc);
125972   UNUSED_PARAMETER(argv);
125973
125974   /* Test the query function */
125975   sqlite3Fts3SimpleTokenizerModule(&p1);
125976   rc = queryTokenizer(db, "simple", &p2);
125977   assert( rc==SQLITE_OK );
125978   assert( p1==p2 );
125979   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
125980   assert( rc==SQLITE_ERROR );
125981   assert( p2==0 );
125982   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
125983
125984   /* Test the storage function */
125985   rc = registerTokenizer(db, "nosuchtokenizer", p1);
125986   assert( rc==SQLITE_OK );
125987   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
125988   assert( rc==SQLITE_OK );
125989   assert( p2==p1 );
125990
125991   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
125992 }
125993
125994 #endif
125995
125996 /*
125997 ** Set up SQL objects in database db used to access the contents of
125998 ** the hash table pointed to by argument pHash. The hash table must
125999 ** been initialized to use string keys, and to take a private copy 
126000 ** of the key when a value is inserted. i.e. by a call similar to:
126001 **
126002 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
126003 **
126004 ** This function adds a scalar function (see header comment above
126005 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
126006 ** defined at compilation time, a temporary virtual table (see header 
126007 ** comment above struct HashTableVtab) to the database schema. Both 
126008 ** provide read/write access to the contents of *pHash.
126009 **
126010 ** The third argument to this function, zName, is used as the name
126011 ** of both the scalar and, if created, the virtual table.
126012 */
126013 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
126014   sqlite3 *db, 
126015   Fts3Hash *pHash, 
126016   const char *zName
126017 ){
126018   int rc = SQLITE_OK;
126019   void *p = (void *)pHash;
126020   const int any = SQLITE_ANY;
126021
126022 #ifdef SQLITE_TEST
126023   char *zTest = 0;
126024   char *zTest2 = 0;
126025   void *pdb = (void *)db;
126026   zTest = sqlite3_mprintf("%s_test", zName);
126027   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
126028   if( !zTest || !zTest2 ){
126029     rc = SQLITE_NOMEM;
126030   }
126031 #endif
126032
126033   if( SQLITE_OK==rc ){
126034     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
126035   }
126036   if( SQLITE_OK==rc ){
126037     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
126038   }
126039 #ifdef SQLITE_TEST
126040   if( SQLITE_OK==rc ){
126041     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
126042   }
126043   if( SQLITE_OK==rc ){
126044     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
126045   }
126046 #endif
126047
126048 #ifdef SQLITE_TEST
126049   sqlite3_free(zTest);
126050   sqlite3_free(zTest2);
126051 #endif
126052
126053   return rc;
126054 }
126055
126056 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126057
126058 /************** End of fts3_tokenizer.c **************************************/
126059 /************** Begin file fts3_tokenizer1.c *********************************/
126060 /*
126061 ** 2006 Oct 10
126062 **
126063 ** The author disclaims copyright to this source code.  In place of
126064 ** a legal notice, here is a blessing:
126065 **
126066 **    May you do good and not evil.
126067 **    May you find forgiveness for yourself and forgive others.
126068 **    May you share freely, never taking more than you give.
126069 **
126070 ******************************************************************************
126071 **
126072 ** Implementation of the "simple" full-text-search tokenizer.
126073 */
126074
126075 /*
126076 ** The code in this file is only compiled if:
126077 **
126078 **     * The FTS3 module is being built as an extension
126079 **       (in which case SQLITE_CORE is not defined), or
126080 **
126081 **     * The FTS3 module is being built into the core of
126082 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
126083 */
126084 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126085
126086 /* #include <assert.h> */
126087 /* #include <stdlib.h> */
126088 /* #include <stdio.h> */
126089 /* #include <string.h> */
126090
126091
126092 typedef struct simple_tokenizer {
126093   sqlite3_tokenizer base;
126094   char delim[128];             /* flag ASCII delimiters */
126095 } simple_tokenizer;
126096
126097 typedef struct simple_tokenizer_cursor {
126098   sqlite3_tokenizer_cursor base;
126099   const char *pInput;          /* input we are tokenizing */
126100   int nBytes;                  /* size of the input */
126101   int iOffset;                 /* current position in pInput */
126102   int iToken;                  /* index of next token to be returned */
126103   char *pToken;                /* storage for current token */
126104   int nTokenAllocated;         /* space allocated to zToken buffer */
126105 } simple_tokenizer_cursor;
126106
126107
126108 static int simpleDelim(simple_tokenizer *t, unsigned char c){
126109   return c<0x80 && t->delim[c];
126110 }
126111 static int fts3_isalnum(int x){
126112   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
126113 }
126114
126115 /*
126116 ** Create a new tokenizer instance.
126117 */
126118 static int simpleCreate(
126119   int argc, const char * const *argv,
126120   sqlite3_tokenizer **ppTokenizer
126121 ){
126122   simple_tokenizer *t;
126123
126124   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
126125   if( t==NULL ) return SQLITE_NOMEM;
126126   memset(t, 0, sizeof(*t));
126127
126128   /* TODO(shess) Delimiters need to remain the same from run to run,
126129   ** else we need to reindex.  One solution would be a meta-table to
126130   ** track such information in the database, then we'd only want this
126131   ** information on the initial create.
126132   */
126133   if( argc>1 ){
126134     int i, n = (int)strlen(argv[1]);
126135     for(i=0; i<n; i++){
126136       unsigned char ch = argv[1][i];
126137       /* We explicitly don't support UTF-8 delimiters for now. */
126138       if( ch>=0x80 ){
126139         sqlite3_free(t);
126140         return SQLITE_ERROR;
126141       }
126142       t->delim[ch] = 1;
126143     }
126144   } else {
126145     /* Mark non-alphanumeric ASCII characters as delimiters */
126146     int i;
126147     for(i=1; i<0x80; i++){
126148       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
126149     }
126150   }
126151
126152   *ppTokenizer = &t->base;
126153   return SQLITE_OK;
126154 }
126155
126156 /*
126157 ** Destroy a tokenizer
126158 */
126159 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
126160   sqlite3_free(pTokenizer);
126161   return SQLITE_OK;
126162 }
126163
126164 /*
126165 ** Prepare to begin tokenizing a particular string.  The input
126166 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
126167 ** used to incrementally tokenize this string is returned in 
126168 ** *ppCursor.
126169 */
126170 static int simpleOpen(
126171   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
126172   const char *pInput, int nBytes,        /* String to be tokenized */
126173   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
126174 ){
126175   simple_tokenizer_cursor *c;
126176
126177   UNUSED_PARAMETER(pTokenizer);
126178
126179   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
126180   if( c==NULL ) return SQLITE_NOMEM;
126181
126182   c->pInput = pInput;
126183   if( pInput==0 ){
126184     c->nBytes = 0;
126185   }else if( nBytes<0 ){
126186     c->nBytes = (int)strlen(pInput);
126187   }else{
126188     c->nBytes = nBytes;
126189   }
126190   c->iOffset = 0;                 /* start tokenizing at the beginning */
126191   c->iToken = 0;
126192   c->pToken = NULL;               /* no space allocated, yet. */
126193   c->nTokenAllocated = 0;
126194
126195   *ppCursor = &c->base;
126196   return SQLITE_OK;
126197 }
126198
126199 /*
126200 ** Close a tokenization cursor previously opened by a call to
126201 ** simpleOpen() above.
126202 */
126203 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
126204   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
126205   sqlite3_free(c->pToken);
126206   sqlite3_free(c);
126207   return SQLITE_OK;
126208 }
126209
126210 /*
126211 ** Extract the next token from a tokenization cursor.  The cursor must
126212 ** have been opened by a prior call to simpleOpen().
126213 */
126214 static int simpleNext(
126215   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
126216   const char **ppToken,               /* OUT: *ppToken is the token text */
126217   int *pnBytes,                       /* OUT: Number of bytes in token */
126218   int *piStartOffset,                 /* OUT: Starting offset of token */
126219   int *piEndOffset,                   /* OUT: Ending offset of token */
126220   int *piPosition                     /* OUT: Position integer of token */
126221 ){
126222   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
126223   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
126224   unsigned char *p = (unsigned char *)c->pInput;
126225
126226   while( c->iOffset<c->nBytes ){
126227     int iStartOffset;
126228
126229     /* Scan past delimiter characters */
126230     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
126231       c->iOffset++;
126232     }
126233
126234     /* Count non-delimiter characters. */
126235     iStartOffset = c->iOffset;
126236     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
126237       c->iOffset++;
126238     }
126239
126240     if( c->iOffset>iStartOffset ){
126241       int i, n = c->iOffset-iStartOffset;
126242       if( n>c->nTokenAllocated ){
126243         char *pNew;
126244         c->nTokenAllocated = n+20;
126245         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
126246         if( !pNew ) return SQLITE_NOMEM;
126247         c->pToken = pNew;
126248       }
126249       for(i=0; i<n; i++){
126250         /* TODO(shess) This needs expansion to handle UTF-8
126251         ** case-insensitivity.
126252         */
126253         unsigned char ch = p[iStartOffset+i];
126254         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
126255       }
126256       *ppToken = c->pToken;
126257       *pnBytes = n;
126258       *piStartOffset = iStartOffset;
126259       *piEndOffset = c->iOffset;
126260       *piPosition = c->iToken++;
126261
126262       return SQLITE_OK;
126263     }
126264   }
126265   return SQLITE_DONE;
126266 }
126267
126268 /*
126269 ** The set of routines that implement the simple tokenizer
126270 */
126271 static const sqlite3_tokenizer_module simpleTokenizerModule = {
126272   0,
126273   simpleCreate,
126274   simpleDestroy,
126275   simpleOpen,
126276   simpleClose,
126277   simpleNext,
126278   0,
126279 };
126280
126281 /*
126282 ** Allocate a new simple tokenizer.  Return a pointer to the new
126283 ** tokenizer in *ppModule
126284 */
126285 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
126286   sqlite3_tokenizer_module const**ppModule
126287 ){
126288   *ppModule = &simpleTokenizerModule;
126289 }
126290
126291 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126292
126293 /************** End of fts3_tokenizer1.c *************************************/
126294 /************** Begin file fts3_write.c **************************************/
126295 /*
126296 ** 2009 Oct 23
126297 **
126298 ** The author disclaims copyright to this source code.  In place of
126299 ** a legal notice, here is a blessing:
126300 **
126301 **    May you do good and not evil.
126302 **    May you find forgiveness for yourself and forgive others.
126303 **    May you share freely, never taking more than you give.
126304 **
126305 ******************************************************************************
126306 **
126307 ** This file is part of the SQLite FTS3 extension module. Specifically,
126308 ** this file contains code to insert, update and delete rows from FTS3
126309 ** tables. It also contains code to merge FTS3 b-tree segments. Some
126310 ** of the sub-routines used to merge segments are also used by the query 
126311 ** code in fts3.c.
126312 */
126313
126314 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126315
126316 /* #include <string.h> */
126317 /* #include <assert.h> */
126318 /* #include <stdlib.h> */
126319
126320
126321 #define FTS_MAX_APPENDABLE_HEIGHT 16
126322
126323 /*
126324 ** When full-text index nodes are loaded from disk, the buffer that they
126325 ** are loaded into has the following number of bytes of padding at the end 
126326 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
126327 ** of 920 bytes is allocated for it.
126328 **
126329 ** This means that if we have a pointer into a buffer containing node data,
126330 ** it is always safe to read up to two varints from it without risking an
126331 ** overread, even if the node data is corrupted.
126332 */
126333 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
126334
126335 /*
126336 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
126337 ** memory incrementally instead of all at once. This can be a big performance
126338 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
126339 ** method before retrieving all query results (as may happen, for example,
126340 ** if a query has a LIMIT clause).
126341 **
126342 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
126343 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
126344 ** The code is written so that the hard lower-limit for each of these values 
126345 ** is 1. Clearly such small values would be inefficient, but can be useful 
126346 ** for testing purposes.
126347 **
126348 ** If this module is built with SQLITE_TEST defined, these constants may
126349 ** be overridden at runtime for testing purposes. File fts3_test.c contains
126350 ** a Tcl interface to read and write the values.
126351 */
126352 #ifdef SQLITE_TEST
126353 int test_fts3_node_chunksize = (4*1024);
126354 int test_fts3_node_chunk_threshold = (4*1024)*4;
126355 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
126356 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
126357 #else
126358 # define FTS3_NODE_CHUNKSIZE (4*1024) 
126359 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
126360 #endif
126361
126362 /*
126363 ** The two values that may be meaningfully bound to the :1 parameter in
126364 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
126365 */
126366 #define FTS_STAT_DOCTOTAL      0
126367 #define FTS_STAT_INCRMERGEHINT 1
126368 #define FTS_STAT_AUTOINCRMERGE 2
126369
126370 /*
126371 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
126372 ** and incremental merge operation that takes place. This is used for 
126373 ** debugging FTS only, it should not usually be turned on in production
126374 ** systems.
126375 */
126376 #ifdef FTS3_LOG_MERGES
126377 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
126378   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
126379 }
126380 #else
126381 #define fts3LogMerge(x, y)
126382 #endif
126383
126384
126385 typedef struct PendingList PendingList;
126386 typedef struct SegmentNode SegmentNode;
126387 typedef struct SegmentWriter SegmentWriter;
126388
126389 /*
126390 ** An instance of the following data structure is used to build doclists
126391 ** incrementally. See function fts3PendingListAppend() for details.
126392 */
126393 struct PendingList {
126394   int nData;
126395   char *aData;
126396   int nSpace;
126397   sqlite3_int64 iLastDocid;
126398   sqlite3_int64 iLastCol;
126399   sqlite3_int64 iLastPos;
126400 };
126401
126402
126403 /*
126404 ** Each cursor has a (possibly empty) linked list of the following objects.
126405 */
126406 struct Fts3DeferredToken {
126407   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
126408   int iCol;                       /* Column token must occur in */
126409   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
126410   PendingList *pList;             /* Doclist is assembled here */
126411 };
126412
126413 /*
126414 ** An instance of this structure is used to iterate through the terms on
126415 ** a contiguous set of segment b-tree leaf nodes. Although the details of
126416 ** this structure are only manipulated by code in this file, opaque handles
126417 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
126418 ** terms when querying the full-text index. See functions:
126419 **
126420 **   sqlite3Fts3SegReaderNew()
126421 **   sqlite3Fts3SegReaderFree()
126422 **   sqlite3Fts3SegReaderIterate()
126423 **
126424 ** Methods used to manipulate Fts3SegReader structures:
126425 **
126426 **   fts3SegReaderNext()
126427 **   fts3SegReaderFirstDocid()
126428 **   fts3SegReaderNextDocid()
126429 */
126430 struct Fts3SegReader {
126431   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
126432   u8 bLookup;                     /* True for a lookup only */
126433   u8 rootOnly;                    /* True for a root-only reader */
126434
126435   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
126436   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
126437   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
126438   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
126439
126440   char *aNode;                    /* Pointer to node data (or NULL) */
126441   int nNode;                      /* Size of buffer at aNode (or 0) */
126442   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
126443   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
126444
126445   Fts3HashElem **ppNextElem;
126446
126447   /* Variables set by fts3SegReaderNext(). These may be read directly
126448   ** by the caller. They are valid from the time SegmentReaderNew() returns
126449   ** until SegmentReaderNext() returns something other than SQLITE_OK
126450   ** (i.e. SQLITE_DONE).
126451   */
126452   int nTerm;                      /* Number of bytes in current term */
126453   char *zTerm;                    /* Pointer to current term */
126454   int nTermAlloc;                 /* Allocated size of zTerm buffer */
126455   char *aDoclist;                 /* Pointer to doclist of current entry */
126456   int nDoclist;                   /* Size of doclist in current entry */
126457
126458   /* The following variables are used by fts3SegReaderNextDocid() to iterate 
126459   ** through the current doclist (aDoclist/nDoclist).
126460   */
126461   char *pOffsetList;
126462   int nOffsetList;                /* For descending pending seg-readers only */
126463   sqlite3_int64 iDocid;
126464 };
126465
126466 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
126467 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
126468
126469 /*
126470 ** An instance of this structure is used to create a segment b-tree in the
126471 ** database. The internal details of this type are only accessed by the
126472 ** following functions:
126473 **
126474 **   fts3SegWriterAdd()
126475 **   fts3SegWriterFlush()
126476 **   fts3SegWriterFree()
126477 */
126478 struct SegmentWriter {
126479   SegmentNode *pTree;             /* Pointer to interior tree structure */
126480   sqlite3_int64 iFirst;           /* First slot in %_segments written */
126481   sqlite3_int64 iFree;            /* Next free slot in %_segments */
126482   char *zTerm;                    /* Pointer to previous term buffer */
126483   int nTerm;                      /* Number of bytes in zTerm */
126484   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
126485   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
126486   int nSize;                      /* Size of allocation at aData */
126487   int nData;                      /* Bytes of data in aData */
126488   char *aData;                    /* Pointer to block from malloc() */
126489 };
126490
126491 /*
126492 ** Type SegmentNode is used by the following three functions to create
126493 ** the interior part of the segment b+-tree structures (everything except
126494 ** the leaf nodes). These functions and type are only ever used by code
126495 ** within the fts3SegWriterXXX() family of functions described above.
126496 **
126497 **   fts3NodeAddTerm()
126498 **   fts3NodeWrite()
126499 **   fts3NodeFree()
126500 **
126501 ** When a b+tree is written to the database (either as a result of a merge
126502 ** or the pending-terms table being flushed), leaves are written into the 
126503 ** database file as soon as they are completely populated. The interior of
126504 ** the tree is assembled in memory and written out only once all leaves have
126505 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
126506 ** very large, meaning that the interior of the tree consumes relatively 
126507 ** little memory.
126508 */
126509 struct SegmentNode {
126510   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
126511   SegmentNode *pRight;            /* Pointer to right-sibling */
126512   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
126513   int nEntry;                     /* Number of terms written to node so far */
126514   char *zTerm;                    /* Pointer to previous term buffer */
126515   int nTerm;                      /* Number of bytes in zTerm */
126516   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
126517   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
126518   int nData;                      /* Bytes of valid data so far */
126519   char *aData;                    /* Node data */
126520 };
126521
126522 /*
126523 ** Valid values for the second argument to fts3SqlStmt().
126524 */
126525 #define SQL_DELETE_CONTENT             0
126526 #define SQL_IS_EMPTY                   1
126527 #define SQL_DELETE_ALL_CONTENT         2 
126528 #define SQL_DELETE_ALL_SEGMENTS        3
126529 #define SQL_DELETE_ALL_SEGDIR          4
126530 #define SQL_DELETE_ALL_DOCSIZE         5
126531 #define SQL_DELETE_ALL_STAT            6
126532 #define SQL_SELECT_CONTENT_BY_ROWID    7
126533 #define SQL_NEXT_SEGMENT_INDEX         8
126534 #define SQL_INSERT_SEGMENTS            9
126535 #define SQL_NEXT_SEGMENTS_ID          10
126536 #define SQL_INSERT_SEGDIR             11
126537 #define SQL_SELECT_LEVEL              12
126538 #define SQL_SELECT_LEVEL_RANGE        13
126539 #define SQL_SELECT_LEVEL_COUNT        14
126540 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
126541 #define SQL_DELETE_SEGDIR_LEVEL       16
126542 #define SQL_DELETE_SEGMENTS_RANGE     17
126543 #define SQL_CONTENT_INSERT            18
126544 #define SQL_DELETE_DOCSIZE            19
126545 #define SQL_REPLACE_DOCSIZE           20
126546 #define SQL_SELECT_DOCSIZE            21
126547 #define SQL_SELECT_STAT               22
126548 #define SQL_REPLACE_STAT              23
126549
126550 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
126551 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
126552 #define SQL_DELETE_SEGDIR_RANGE       26
126553 #define SQL_SELECT_ALL_LANGID         27
126554 #define SQL_FIND_MERGE_LEVEL          28
126555 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
126556 #define SQL_DELETE_SEGDIR_ENTRY       30
126557 #define SQL_SHIFT_SEGDIR_ENTRY        31
126558 #define SQL_SELECT_SEGDIR             32
126559 #define SQL_CHOMP_SEGDIR              33
126560 #define SQL_SEGMENT_IS_APPENDABLE     34
126561 #define SQL_SELECT_INDEXES            35
126562 #define SQL_SELECT_MXLEVEL            36
126563
126564 /*
126565 ** This function is used to obtain an SQLite prepared statement handle
126566 ** for the statement identified by the second argument. If successful,
126567 ** *pp is set to the requested statement handle and SQLITE_OK returned.
126568 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
126569 **
126570 ** If argument apVal is not NULL, then it must point to an array with
126571 ** at least as many entries as the requested statement has bound 
126572 ** parameters. The values are bound to the statements parameters before
126573 ** returning.
126574 */
126575 static int fts3SqlStmt(
126576   Fts3Table *p,                   /* Virtual table handle */
126577   int eStmt,                      /* One of the SQL_XXX constants above */
126578   sqlite3_stmt **pp,              /* OUT: Statement handle */
126579   sqlite3_value **apVal           /* Values to bind to statement */
126580 ){
126581   const char *azSql[] = {
126582 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
126583 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
126584 /* 2  */  "DELETE FROM %Q.'%q_content'",
126585 /* 3  */  "DELETE FROM %Q.'%q_segments'",
126586 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
126587 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
126588 /* 6  */  "DELETE FROM %Q.'%q_stat'",
126589 /* 7  */  "SELECT %s WHERE rowid=?",
126590 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
126591 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
126592 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
126593 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
126594
126595           /* Return segments in order from oldest to newest.*/ 
126596 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
126597             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
126598 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
126599             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
126600             "ORDER BY level DESC, idx ASC",
126601
126602 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
126603 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
126604
126605 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
126606 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
126607 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
126608 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
126609 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
126610 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
126611 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
126612 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
126613 /* 24 */  "",
126614 /* 25 */  "",
126615
126616 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
126617 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
126618
126619 /* This statement is used to determine which level to read the input from
126620 ** when performing an incremental merge. It returns the absolute level number
126621 ** of the oldest level in the db that contains at least ? segments. Or,
126622 ** if no level in the FTS index contains more than ? segments, the statement
126623 ** returns zero rows.  */
126624 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
126625          "  ORDER BY (level %% 1024) ASC LIMIT 1",
126626
126627 /* Estimate the upper limit on the number of leaf nodes in a new segment
126628 ** created by merging the oldest :2 segments from absolute level :1. See 
126629 ** function sqlite3Fts3Incrmerge() for details.  */
126630 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
126631          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
126632
126633 /* SQL_DELETE_SEGDIR_ENTRY
126634 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
126635 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
126636
126637 /* SQL_SHIFT_SEGDIR_ENTRY
126638 **   Modify the idx value for the segment with idx=:3 on absolute level :2
126639 **   to :1.  */
126640 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
126641
126642 /* SQL_SELECT_SEGDIR
126643 **   Read a single entry from the %_segdir table. The entry from absolute 
126644 **   level :1 with index value :2.  */
126645 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
126646             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
126647
126648 /* SQL_CHOMP_SEGDIR
126649 **   Update the start_block (:1) and root (:2) fields of the %_segdir
126650 **   entry located on absolute level :3 with index :4.  */
126651 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
126652             "WHERE level = ? AND idx = ?",
126653
126654 /* SQL_SEGMENT_IS_APPENDABLE
126655 **   Return a single row if the segment with end_block=? is appendable. Or
126656 **   no rows otherwise.  */
126657 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
126658
126659 /* SQL_SELECT_INDEXES
126660 **   Return the list of valid segment indexes for absolute level ?  */
126661 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
126662
126663 /* SQL_SELECT_MXLEVEL
126664 **   Return the largest relative level in the FTS index or indexes.  */
126665 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
126666   };
126667   int rc = SQLITE_OK;
126668   sqlite3_stmt *pStmt;
126669
126670   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
126671   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
126672   
126673   pStmt = p->aStmt[eStmt];
126674   if( !pStmt ){
126675     char *zSql;
126676     if( eStmt==SQL_CONTENT_INSERT ){
126677       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
126678     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
126679       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
126680     }else{
126681       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
126682     }
126683     if( !zSql ){
126684       rc = SQLITE_NOMEM;
126685     }else{
126686       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
126687       sqlite3_free(zSql);
126688       assert( rc==SQLITE_OK || pStmt==0 );
126689       p->aStmt[eStmt] = pStmt;
126690     }
126691   }
126692   if( apVal ){
126693     int i;
126694     int nParam = sqlite3_bind_parameter_count(pStmt);
126695     for(i=0; rc==SQLITE_OK && i<nParam; i++){
126696       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
126697     }
126698   }
126699   *pp = pStmt;
126700   return rc;
126701 }
126702
126703
126704 static int fts3SelectDocsize(
126705   Fts3Table *pTab,                /* FTS3 table handle */
126706   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
126707   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
126708 ){
126709   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
126710   int rc;                         /* Return code */
126711
126712   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
126713   if( rc==SQLITE_OK ){
126714     sqlite3_bind_int64(pStmt, 1, iDocid);
126715     rc = sqlite3_step(pStmt);
126716     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
126717       rc = sqlite3_reset(pStmt);
126718       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
126719       pStmt = 0;
126720     }else{
126721       rc = SQLITE_OK;
126722     }
126723   }
126724
126725   *ppStmt = pStmt;
126726   return rc;
126727 }
126728
126729 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
126730   Fts3Table *pTab,                /* Fts3 table handle */
126731   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
126732 ){
126733   sqlite3_stmt *pStmt = 0;
126734   int rc;
126735   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
126736   if( rc==SQLITE_OK ){
126737     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
126738     if( sqlite3_step(pStmt)!=SQLITE_ROW
126739      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
126740     ){
126741       rc = sqlite3_reset(pStmt);
126742       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
126743       pStmt = 0;
126744     }
126745   }
126746   *ppStmt = pStmt;
126747   return rc;
126748 }
126749
126750 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
126751   Fts3Table *pTab,                /* Fts3 table handle */
126752   sqlite3_int64 iDocid,           /* Docid to read size data for */
126753   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
126754 ){
126755   return fts3SelectDocsize(pTab, iDocid, ppStmt);
126756 }
126757
126758 /*
126759 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
126760 ** array apVal[] to the SQL statement identified by eStmt, the statement
126761 ** is executed.
126762 **
126763 ** Returns SQLITE_OK if the statement is successfully executed, or an
126764 ** SQLite error code otherwise.
126765 */
126766 static void fts3SqlExec(
126767   int *pRC,                /* Result code */
126768   Fts3Table *p,            /* The FTS3 table */
126769   int eStmt,               /* Index of statement to evaluate */
126770   sqlite3_value **apVal    /* Parameters to bind */
126771 ){
126772   sqlite3_stmt *pStmt;
126773   int rc;
126774   if( *pRC ) return;
126775   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
126776   if( rc==SQLITE_OK ){
126777     sqlite3_step(pStmt);
126778     rc = sqlite3_reset(pStmt);
126779   }
126780   *pRC = rc;
126781 }
126782
126783
126784 /*
126785 ** This function ensures that the caller has obtained a shared-cache
126786 ** table-lock on the %_content table. This is required before reading
126787 ** data from the fts3 table. If this lock is not acquired first, then
126788 ** the caller may end up holding read-locks on the %_segments and %_segdir
126789 ** tables, but no read-lock on the %_content table. If this happens 
126790 ** a second connection will be able to write to the fts3 table, but
126791 ** attempting to commit those writes might return SQLITE_LOCKED or
126792 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
126793 ** write-locks on the %_segments and %_segdir ** tables). 
126794 **
126795 ** We try to avoid this because if FTS3 returns any error when committing
126796 ** a transaction, the whole transaction will be rolled back. And this is
126797 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
126798 ** still happen if the user reads data directly from the %_segments or
126799 ** %_segdir tables instead of going through FTS3 though.
126800 **
126801 ** This reasoning does not apply to a content=xxx table.
126802 */
126803 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
126804   int rc;                         /* Return code */
126805   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
126806
126807   if( p->zContentTbl==0 ){
126808     rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
126809     if( rc==SQLITE_OK ){
126810       sqlite3_bind_null(pStmt, 1);
126811       sqlite3_step(pStmt);
126812       rc = sqlite3_reset(pStmt);
126813     }
126814   }else{
126815     rc = SQLITE_OK;
126816   }
126817
126818   return rc;
126819 }
126820
126821 /*
126822 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
126823 ** Within each language id, a separate index is maintained to store the
126824 ** document terms, and each configured prefix size (configured the FTS 
126825 ** "prefix=" option). And each index consists of multiple levels ("relative
126826 ** levels").
126827 **
126828 ** All three of these values (the language id, the specific index and the
126829 ** level within the index) are encoded in 64-bit integer values stored
126830 ** in the %_segdir table on disk. This function is used to convert three
126831 ** separate component values into the single 64-bit integer value that
126832 ** can be used to query the %_segdir table.
126833 **
126834 ** Specifically, each language-id/index combination is allocated 1024 
126835 ** 64-bit integer level values ("absolute levels"). The main terms index
126836 ** for language-id 0 is allocate values 0-1023. The first prefix index
126837 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
126838 ** Language 1 indexes are allocated immediately following language 0.
126839 **
126840 ** So, for a system with nPrefix prefix indexes configured, the block of
126841 ** absolute levels that corresponds to language-id iLangid and index 
126842 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
126843 */
126844 static sqlite3_int64 getAbsoluteLevel(
126845   Fts3Table *p,                   /* FTS3 table handle */
126846   int iLangid,                    /* Language id */
126847   int iIndex,                     /* Index in p->aIndex[] */
126848   int iLevel                      /* Level of segments */
126849 ){
126850   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
126851   assert( iLangid>=0 );
126852   assert( p->nIndex>0 );
126853   assert( iIndex>=0 && iIndex<p->nIndex );
126854
126855   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
126856   return iBase + iLevel;
126857 }
126858
126859 /*
126860 ** Set *ppStmt to a statement handle that may be used to iterate through
126861 ** all rows in the %_segdir table, from oldest to newest. If successful,
126862 ** return SQLITE_OK. If an error occurs while preparing the statement, 
126863 ** return an SQLite error code.
126864 **
126865 ** There is only ever one instance of this SQL statement compiled for
126866 ** each FTS3 table.
126867 **
126868 ** The statement returns the following columns from the %_segdir table:
126869 **
126870 **   0: idx
126871 **   1: start_block
126872 **   2: leaves_end_block
126873 **   3: end_block
126874 **   4: root
126875 */
126876 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
126877   Fts3Table *p,                   /* FTS3 table */
126878   int iLangid,                    /* Language being queried */
126879   int iIndex,                     /* Index for p->aIndex[] */
126880   int iLevel,                     /* Level to select (relative level) */
126881   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
126882 ){
126883   int rc;
126884   sqlite3_stmt *pStmt = 0;
126885
126886   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
126887   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
126888   assert( iIndex>=0 && iIndex<p->nIndex );
126889
126890   if( iLevel<0 ){
126891     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
126892     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
126893     if( rc==SQLITE_OK ){ 
126894       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
126895       sqlite3_bind_int64(pStmt, 2, 
126896           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
126897       );
126898     }
126899   }else{
126900     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
126901     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
126902     if( rc==SQLITE_OK ){ 
126903       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
126904     }
126905   }
126906   *ppStmt = pStmt;
126907   return rc;
126908 }
126909
126910
126911 /*
126912 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
126913 ** if successful, or an SQLite error code otherwise.
126914 **
126915 ** This function also serves to allocate the PendingList structure itself.
126916 ** For example, to create a new PendingList structure containing two
126917 ** varints:
126918 **
126919 **   PendingList *p = 0;
126920 **   fts3PendingListAppendVarint(&p, 1);
126921 **   fts3PendingListAppendVarint(&p, 2);
126922 */
126923 static int fts3PendingListAppendVarint(
126924   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
126925   sqlite3_int64 i                 /* Value to append to data */
126926 ){
126927   PendingList *p = *pp;
126928
126929   /* Allocate or grow the PendingList as required. */
126930   if( !p ){
126931     p = sqlite3_malloc(sizeof(*p) + 100);
126932     if( !p ){
126933       return SQLITE_NOMEM;
126934     }
126935     p->nSpace = 100;
126936     p->aData = (char *)&p[1];
126937     p->nData = 0;
126938   }
126939   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
126940     int nNew = p->nSpace * 2;
126941     p = sqlite3_realloc(p, sizeof(*p) + nNew);
126942     if( !p ){
126943       sqlite3_free(*pp);
126944       *pp = 0;
126945       return SQLITE_NOMEM;
126946     }
126947     p->nSpace = nNew;
126948     p->aData = (char *)&p[1];
126949   }
126950
126951   /* Append the new serialized varint to the end of the list. */
126952   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
126953   p->aData[p->nData] = '\0';
126954   *pp = p;
126955   return SQLITE_OK;
126956 }
126957
126958 /*
126959 ** Add a docid/column/position entry to a PendingList structure. Non-zero
126960 ** is returned if the structure is sqlite3_realloced as part of adding
126961 ** the entry. Otherwise, zero.
126962 **
126963 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
126964 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
126965 ** it is set to SQLITE_OK.
126966 */
126967 static int fts3PendingListAppend(
126968   PendingList **pp,               /* IN/OUT: PendingList structure */
126969   sqlite3_int64 iDocid,           /* Docid for entry to add */
126970   sqlite3_int64 iCol,             /* Column for entry to add */
126971   sqlite3_int64 iPos,             /* Position of term for entry to add */
126972   int *pRc                        /* OUT: Return code */
126973 ){
126974   PendingList *p = *pp;
126975   int rc = SQLITE_OK;
126976
126977   assert( !p || p->iLastDocid<=iDocid );
126978
126979   if( !p || p->iLastDocid!=iDocid ){
126980     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
126981     if( p ){
126982       assert( p->nData<p->nSpace );
126983       assert( p->aData[p->nData]==0 );
126984       p->nData++;
126985     }
126986     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
126987       goto pendinglistappend_out;
126988     }
126989     p->iLastCol = -1;
126990     p->iLastPos = 0;
126991     p->iLastDocid = iDocid;
126992   }
126993   if( iCol>0 && p->iLastCol!=iCol ){
126994     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
126995      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
126996     ){
126997       goto pendinglistappend_out;
126998     }
126999     p->iLastCol = iCol;
127000     p->iLastPos = 0;
127001   }
127002   if( iCol>=0 ){
127003     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
127004     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
127005     if( rc==SQLITE_OK ){
127006       p->iLastPos = iPos;
127007     }
127008   }
127009
127010  pendinglistappend_out:
127011   *pRc = rc;
127012   if( p!=*pp ){
127013     *pp = p;
127014     return 1;
127015   }
127016   return 0;
127017 }
127018
127019 /*
127020 ** Free a PendingList object allocated by fts3PendingListAppend().
127021 */
127022 static void fts3PendingListDelete(PendingList *pList){
127023   sqlite3_free(pList);
127024 }
127025
127026 /*
127027 ** Add an entry to one of the pending-terms hash tables.
127028 */
127029 static int fts3PendingTermsAddOne(
127030   Fts3Table *p,
127031   int iCol,
127032   int iPos,
127033   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
127034   const char *zToken,
127035   int nToken
127036 ){
127037   PendingList *pList;
127038   int rc = SQLITE_OK;
127039
127040   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
127041   if( pList ){
127042     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
127043   }
127044   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
127045     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
127046       /* Malloc failed while inserting the new entry. This can only 
127047       ** happen if there was no previous entry for this token.
127048       */
127049       assert( 0==fts3HashFind(pHash, zToken, nToken) );
127050       sqlite3_free(pList);
127051       rc = SQLITE_NOMEM;
127052     }
127053   }
127054   if( rc==SQLITE_OK ){
127055     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
127056   }
127057   return rc;
127058 }
127059
127060 /*
127061 ** Tokenize the nul-terminated string zText and add all tokens to the
127062 ** pending-terms hash-table. The docid used is that currently stored in
127063 ** p->iPrevDocid, and the column is specified by argument iCol.
127064 **
127065 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
127066 */
127067 static int fts3PendingTermsAdd(
127068   Fts3Table *p,                   /* Table into which text will be inserted */
127069   int iLangid,                    /* Language id to use */
127070   const char *zText,              /* Text of document to be inserted */
127071   int iCol,                       /* Column into which text is being inserted */
127072   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
127073 ){
127074   int rc;
127075   int iStart = 0;
127076   int iEnd = 0;
127077   int iPos = 0;
127078   int nWord = 0;
127079
127080   char const *zToken;
127081   int nToken = 0;
127082
127083   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
127084   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
127085   sqlite3_tokenizer_cursor *pCsr;
127086   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
127087       const char**,int*,int*,int*,int*);
127088
127089   assert( pTokenizer && pModule );
127090
127091   /* If the user has inserted a NULL value, this function may be called with
127092   ** zText==0. In this case, add zero token entries to the hash table and 
127093   ** return early. */
127094   if( zText==0 ){
127095     *pnWord = 0;
127096     return SQLITE_OK;
127097   }
127098
127099   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
127100   if( rc!=SQLITE_OK ){
127101     return rc;
127102   }
127103
127104   xNext = pModule->xNext;
127105   while( SQLITE_OK==rc
127106       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
127107   ){
127108     int i;
127109     if( iPos>=nWord ) nWord = iPos+1;
127110
127111     /* Positions cannot be negative; we use -1 as a terminator internally.
127112     ** Tokens must have a non-zero length.
127113     */
127114     if( iPos<0 || !zToken || nToken<=0 ){
127115       rc = SQLITE_ERROR;
127116       break;
127117     }
127118
127119     /* Add the term to the terms index */
127120     rc = fts3PendingTermsAddOne(
127121         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
127122     );
127123     
127124     /* Add the term to each of the prefix indexes that it is not too 
127125     ** short for. */
127126     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
127127       struct Fts3Index *pIndex = &p->aIndex[i];
127128       if( nToken<pIndex->nPrefix ) continue;
127129       rc = fts3PendingTermsAddOne(
127130           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
127131       );
127132     }
127133   }
127134
127135   pModule->xClose(pCsr);
127136   *pnWord += nWord;
127137   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
127138 }
127139
127140 /* 
127141 ** Calling this function indicates that subsequent calls to 
127142 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
127143 ** contents of the document with docid iDocid.
127144 */
127145 static int fts3PendingTermsDocid(
127146   Fts3Table *p,                   /* Full-text table handle */
127147   int iLangid,                    /* Language id of row being written */
127148   sqlite_int64 iDocid             /* Docid of row being written */
127149 ){
127150   assert( iLangid>=0 );
127151
127152   /* TODO(shess) Explore whether partially flushing the buffer on
127153   ** forced-flush would provide better performance.  I suspect that if
127154   ** we ordered the doclists by size and flushed the largest until the
127155   ** buffer was half empty, that would let the less frequent terms
127156   ** generate longer doclists.
127157   */
127158   if( iDocid<=p->iPrevDocid 
127159    || p->iPrevLangid!=iLangid
127160    || p->nPendingData>p->nMaxPendingData 
127161   ){
127162     int rc = sqlite3Fts3PendingTermsFlush(p);
127163     if( rc!=SQLITE_OK ) return rc;
127164   }
127165   p->iPrevDocid = iDocid;
127166   p->iPrevLangid = iLangid;
127167   return SQLITE_OK;
127168 }
127169
127170 /*
127171 ** Discard the contents of the pending-terms hash tables. 
127172 */
127173 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
127174   int i;
127175   for(i=0; i<p->nIndex; i++){
127176     Fts3HashElem *pElem;
127177     Fts3Hash *pHash = &p->aIndex[i].hPending;
127178     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
127179       PendingList *pList = (PendingList *)fts3HashData(pElem);
127180       fts3PendingListDelete(pList);
127181     }
127182     fts3HashClear(pHash);
127183   }
127184   p->nPendingData = 0;
127185 }
127186
127187 /*
127188 ** This function is called by the xUpdate() method as part of an INSERT
127189 ** operation. It adds entries for each term in the new record to the
127190 ** pendingTerms hash table.
127191 **
127192 ** Argument apVal is the same as the similarly named argument passed to
127193 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
127194 */
127195 static int fts3InsertTerms(
127196   Fts3Table *p, 
127197   int iLangid, 
127198   sqlite3_value **apVal, 
127199   u32 *aSz
127200 ){
127201   int i;                          /* Iterator variable */
127202   for(i=2; i<p->nColumn+2; i++){
127203     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
127204     int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
127205     if( rc!=SQLITE_OK ){
127206       return rc;
127207     }
127208     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
127209   }
127210   return SQLITE_OK;
127211 }
127212
127213 /*
127214 ** This function is called by the xUpdate() method for an INSERT operation.
127215 ** The apVal parameter is passed a copy of the apVal argument passed by
127216 ** SQLite to the xUpdate() method. i.e:
127217 **
127218 **   apVal[0]                Not used for INSERT.
127219 **   apVal[1]                rowid
127220 **   apVal[2]                Left-most user-defined column
127221 **   ...
127222 **   apVal[p->nColumn+1]     Right-most user-defined column
127223 **   apVal[p->nColumn+2]     Hidden column with same name as table
127224 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
127225 **   apVal[p->nColumn+4]     Hidden languageid column
127226 */
127227 static int fts3InsertData(
127228   Fts3Table *p,                   /* Full-text table */
127229   sqlite3_value **apVal,          /* Array of values to insert */
127230   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
127231 ){
127232   int rc;                         /* Return code */
127233   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
127234
127235   if( p->zContentTbl ){
127236     sqlite3_value *pRowid = apVal[p->nColumn+3];
127237     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
127238       pRowid = apVal[1];
127239     }
127240     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
127241       return SQLITE_CONSTRAINT;
127242     }
127243     *piDocid = sqlite3_value_int64(pRowid);
127244     return SQLITE_OK;
127245   }
127246
127247   /* Locate the statement handle used to insert data into the %_content
127248   ** table. The SQL for this statement is:
127249   **
127250   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
127251   **
127252   ** The statement features N '?' variables, where N is the number of user
127253   ** defined columns in the FTS3 table, plus one for the docid field.
127254   */
127255   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
127256   if( rc==SQLITE_OK && p->zLanguageid ){
127257     rc = sqlite3_bind_int(
127258         pContentInsert, p->nColumn+2, 
127259         sqlite3_value_int(apVal[p->nColumn+4])
127260     );
127261   }
127262   if( rc!=SQLITE_OK ) return rc;
127263
127264   /* There is a quirk here. The users INSERT statement may have specified
127265   ** a value for the "rowid" field, for the "docid" field, or for both.
127266   ** Which is a problem, since "rowid" and "docid" are aliases for the
127267   ** same value. For example:
127268   **
127269   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
127270   **
127271   ** In FTS3, this is an error. It is an error to specify non-NULL values
127272   ** for both docid and some other rowid alias.
127273   */
127274   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
127275     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
127276      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
127277     ){
127278       /* A rowid/docid conflict. */
127279       return SQLITE_ERROR;
127280     }
127281     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
127282     if( rc!=SQLITE_OK ) return rc;
127283   }
127284
127285   /* Execute the statement to insert the record. Set *piDocid to the 
127286   ** new docid value. 
127287   */
127288   sqlite3_step(pContentInsert);
127289   rc = sqlite3_reset(pContentInsert);
127290
127291   *piDocid = sqlite3_last_insert_rowid(p->db);
127292   return rc;
127293 }
127294
127295
127296
127297 /*
127298 ** Remove all data from the FTS3 table. Clear the hash table containing
127299 ** pending terms.
127300 */
127301 static int fts3DeleteAll(Fts3Table *p, int bContent){
127302   int rc = SQLITE_OK;             /* Return code */
127303
127304   /* Discard the contents of the pending-terms hash table. */
127305   sqlite3Fts3PendingTermsClear(p);
127306
127307   /* Delete everything from the shadow tables. Except, leave %_content as
127308   ** is if bContent is false.  */
127309   assert( p->zContentTbl==0 || bContent==0 );
127310   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
127311   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
127312   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
127313   if( p->bHasDocsize ){
127314     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
127315   }
127316   if( p->bHasStat ){
127317     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
127318   }
127319   return rc;
127320 }
127321
127322 /*
127323 **
127324 */
127325 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
127326   int iLangid = 0;
127327   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
127328   return iLangid;
127329 }
127330
127331 /*
127332 ** The first element in the apVal[] array is assumed to contain the docid
127333 ** (an integer) of a row about to be deleted. Remove all terms from the
127334 ** full-text index.
127335 */
127336 static void fts3DeleteTerms( 
127337   int *pRC,               /* Result code */
127338   Fts3Table *p,           /* The FTS table to delete from */
127339   sqlite3_value *pRowid,  /* The docid to be deleted */
127340   u32 *aSz,               /* Sizes of deleted document written here */
127341   int *pbFound            /* OUT: Set to true if row really does exist */
127342 ){
127343   int rc;
127344   sqlite3_stmt *pSelect;
127345
127346   assert( *pbFound==0 );
127347   if( *pRC ) return;
127348   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
127349   if( rc==SQLITE_OK ){
127350     if( SQLITE_ROW==sqlite3_step(pSelect) ){
127351       int i;
127352       int iLangid = langidFromSelect(p, pSelect);
127353       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
127354       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
127355         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
127356         rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
127357         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
127358       }
127359       if( rc!=SQLITE_OK ){
127360         sqlite3_reset(pSelect);
127361         *pRC = rc;
127362         return;
127363       }
127364       *pbFound = 1;
127365     }
127366     rc = sqlite3_reset(pSelect);
127367   }else{
127368     sqlite3_reset(pSelect);
127369   }
127370   *pRC = rc;
127371 }
127372
127373 /*
127374 ** Forward declaration to account for the circular dependency between
127375 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
127376 */
127377 static int fts3SegmentMerge(Fts3Table *, int, int, int);
127378
127379 /* 
127380 ** This function allocates a new level iLevel index in the segdir table.
127381 ** Usually, indexes are allocated within a level sequentially starting
127382 ** with 0, so the allocated index is one greater than the value returned
127383 ** by:
127384 **
127385 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
127386 **
127387 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
127388 ** level, they are merged into a single level (iLevel+1) segment and the 
127389 ** allocated index is 0.
127390 **
127391 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
127392 ** returned. Otherwise, an SQLite error code is returned.
127393 */
127394 static int fts3AllocateSegdirIdx(
127395   Fts3Table *p, 
127396   int iLangid,                    /* Language id */
127397   int iIndex,                     /* Index for p->aIndex */
127398   int iLevel, 
127399   int *piIdx
127400 ){
127401   int rc;                         /* Return Code */
127402   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
127403   int iNext = 0;                  /* Result of query pNextIdx */
127404
127405   assert( iLangid>=0 );
127406   assert( p->nIndex>=1 );
127407
127408   /* Set variable iNext to the next available segdir index at level iLevel. */
127409   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
127410   if( rc==SQLITE_OK ){
127411     sqlite3_bind_int64(
127412         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
127413     );
127414     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
127415       iNext = sqlite3_column_int(pNextIdx, 0);
127416     }
127417     rc = sqlite3_reset(pNextIdx);
127418   }
127419
127420   if( rc==SQLITE_OK ){
127421     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
127422     ** full, merge all segments in level iLevel into a single iLevel+1
127423     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
127424     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
127425     */
127426     if( iNext>=FTS3_MERGE_COUNT ){
127427       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
127428       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
127429       *piIdx = 0;
127430     }else{
127431       *piIdx = iNext;
127432     }
127433   }
127434
127435   return rc;
127436 }
127437
127438 /*
127439 ** The %_segments table is declared as follows:
127440 **
127441 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
127442 **
127443 ** This function reads data from a single row of the %_segments table. The
127444 ** specific row is identified by the iBlockid parameter. If paBlob is not
127445 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
127446 ** with the contents of the blob stored in the "block" column of the 
127447 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
127448 ** to the size of the blob in bytes before returning.
127449 **
127450 ** If an error occurs, or the table does not contain the specified row,
127451 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
127452 ** paBlob is non-NULL, then it is the responsibility of the caller to
127453 ** eventually free the returned buffer.
127454 **
127455 ** This function may leave an open sqlite3_blob* handle in the
127456 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
127457 ** to this function. The handle may be closed by calling the
127458 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
127459 ** performance improvement, but the blob handle should always be closed
127460 ** before control is returned to the user (to prevent a lock being held
127461 ** on the database file for longer than necessary). Thus, any virtual table
127462 ** method (xFilter etc.) that may directly or indirectly call this function
127463 ** must call sqlite3Fts3SegmentsClose() before returning.
127464 */
127465 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
127466   Fts3Table *p,                   /* FTS3 table handle */
127467   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
127468   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
127469   int *pnBlob,                    /* OUT: Size of blob data */
127470   int *pnLoad                     /* OUT: Bytes actually loaded */
127471 ){
127472   int rc;                         /* Return code */
127473
127474   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
127475   assert( pnBlob );
127476
127477   if( p->pSegments ){
127478     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
127479   }else{
127480     if( 0==p->zSegmentsTbl ){
127481       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
127482       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
127483     }
127484     rc = sqlite3_blob_open(
127485        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
127486     );
127487   }
127488
127489   if( rc==SQLITE_OK ){
127490     int nByte = sqlite3_blob_bytes(p->pSegments);
127491     *pnBlob = nByte;
127492     if( paBlob ){
127493       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
127494       if( !aByte ){
127495         rc = SQLITE_NOMEM;
127496       }else{
127497         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
127498           nByte = FTS3_NODE_CHUNKSIZE;
127499           *pnLoad = nByte;
127500         }
127501         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
127502         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
127503         if( rc!=SQLITE_OK ){
127504           sqlite3_free(aByte);
127505           aByte = 0;
127506         }
127507       }
127508       *paBlob = aByte;
127509     }
127510   }
127511
127512   return rc;
127513 }
127514
127515 /*
127516 ** Close the blob handle at p->pSegments, if it is open. See comments above
127517 ** the sqlite3Fts3ReadBlock() function for details.
127518 */
127519 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
127520   sqlite3_blob_close(p->pSegments);
127521   p->pSegments = 0;
127522 }
127523     
127524 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
127525   int nRead;                      /* Number of bytes to read */
127526   int rc;                         /* Return code */
127527
127528   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
127529   rc = sqlite3_blob_read(
127530       pReader->pBlob, 
127531       &pReader->aNode[pReader->nPopulate],
127532       nRead,
127533       pReader->nPopulate
127534   );
127535
127536   if( rc==SQLITE_OK ){
127537     pReader->nPopulate += nRead;
127538     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
127539     if( pReader->nPopulate==pReader->nNode ){
127540       sqlite3_blob_close(pReader->pBlob);
127541       pReader->pBlob = 0;
127542       pReader->nPopulate = 0;
127543     }
127544   }
127545   return rc;
127546 }
127547
127548 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
127549   int rc = SQLITE_OK;
127550   assert( !pReader->pBlob 
127551        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
127552   );
127553   while( pReader->pBlob && rc==SQLITE_OK 
127554      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
127555   ){
127556     rc = fts3SegReaderIncrRead(pReader);
127557   }
127558   return rc;
127559 }
127560
127561 /*
127562 ** Set an Fts3SegReader cursor to point at EOF.
127563 */
127564 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
127565   if( !fts3SegReaderIsRootOnly(pSeg) ){
127566     sqlite3_free(pSeg->aNode);
127567     sqlite3_blob_close(pSeg->pBlob);
127568     pSeg->pBlob = 0;
127569   }
127570   pSeg->aNode = 0;
127571 }
127572
127573 /*
127574 ** Move the iterator passed as the first argument to the next term in the
127575 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
127576 ** SQLITE_DONE. Otherwise, an SQLite error code.
127577 */
127578 static int fts3SegReaderNext(
127579   Fts3Table *p, 
127580   Fts3SegReader *pReader,
127581   int bIncr
127582 ){
127583   int rc;                         /* Return code of various sub-routines */
127584   char *pNext;                    /* Cursor variable */
127585   int nPrefix;                    /* Number of bytes in term prefix */
127586   int nSuffix;                    /* Number of bytes in term suffix */
127587
127588   if( !pReader->aDoclist ){
127589     pNext = pReader->aNode;
127590   }else{
127591     pNext = &pReader->aDoclist[pReader->nDoclist];
127592   }
127593
127594   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
127595
127596     if( fts3SegReaderIsPending(pReader) ){
127597       Fts3HashElem *pElem = *(pReader->ppNextElem);
127598       if( pElem==0 ){
127599         pReader->aNode = 0;
127600       }else{
127601         PendingList *pList = (PendingList *)fts3HashData(pElem);
127602         pReader->zTerm = (char *)fts3HashKey(pElem);
127603         pReader->nTerm = fts3HashKeysize(pElem);
127604         pReader->nNode = pReader->nDoclist = pList->nData + 1;
127605         pReader->aNode = pReader->aDoclist = pList->aData;
127606         pReader->ppNextElem++;
127607         assert( pReader->aNode );
127608       }
127609       return SQLITE_OK;
127610     }
127611
127612     fts3SegReaderSetEof(pReader);
127613
127614     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
127615     ** blocks have already been traversed.  */
127616     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
127617     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
127618       return SQLITE_OK;
127619     }
127620
127621     rc = sqlite3Fts3ReadBlock(
127622         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
127623         (bIncr ? &pReader->nPopulate : 0)
127624     );
127625     if( rc!=SQLITE_OK ) return rc;
127626     assert( pReader->pBlob==0 );
127627     if( bIncr && pReader->nPopulate<pReader->nNode ){
127628       pReader->pBlob = p->pSegments;
127629       p->pSegments = 0;
127630     }
127631     pNext = pReader->aNode;
127632   }
127633
127634   assert( !fts3SegReaderIsPending(pReader) );
127635
127636   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
127637   if( rc!=SQLITE_OK ) return rc;
127638   
127639   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
127640   ** safe (no risk of overread) even if the node data is corrupted. */
127641   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
127642   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
127643   if( nPrefix<0 || nSuffix<=0 
127644    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
127645   ){
127646     return FTS_CORRUPT_VTAB;
127647   }
127648
127649   if( nPrefix+nSuffix>pReader->nTermAlloc ){
127650     int nNew = (nPrefix+nSuffix)*2;
127651     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
127652     if( !zNew ){
127653       return SQLITE_NOMEM;
127654     }
127655     pReader->zTerm = zNew;
127656     pReader->nTermAlloc = nNew;
127657   }
127658
127659   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
127660   if( rc!=SQLITE_OK ) return rc;
127661
127662   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
127663   pReader->nTerm = nPrefix+nSuffix;
127664   pNext += nSuffix;
127665   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
127666   pReader->aDoclist = pNext;
127667   pReader->pOffsetList = 0;
127668
127669   /* Check that the doclist does not appear to extend past the end of the
127670   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
127671   ** of these statements is untrue, then the data structure is corrupt.
127672   */
127673   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
127674    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
127675   ){
127676     return FTS_CORRUPT_VTAB;
127677   }
127678   return SQLITE_OK;
127679 }
127680
127681 /*
127682 ** Set the SegReader to point to the first docid in the doclist associated
127683 ** with the current term.
127684 */
127685 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
127686   int rc = SQLITE_OK;
127687   assert( pReader->aDoclist );
127688   assert( !pReader->pOffsetList );
127689   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
127690     u8 bEof = 0;
127691     pReader->iDocid = 0;
127692     pReader->nOffsetList = 0;
127693     sqlite3Fts3DoclistPrev(0,
127694         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
127695         &pReader->iDocid, &pReader->nOffsetList, &bEof
127696     );
127697   }else{
127698     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
127699     if( rc==SQLITE_OK ){
127700       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
127701       pReader->pOffsetList = &pReader->aDoclist[n];
127702     }
127703   }
127704   return rc;
127705 }
127706
127707 /*
127708 ** Advance the SegReader to point to the next docid in the doclist
127709 ** associated with the current term.
127710 ** 
127711 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
127712 ** *ppOffsetList is set to point to the first column-offset list
127713 ** in the doclist entry (i.e. immediately past the docid varint).
127714 ** *pnOffsetList is set to the length of the set of column-offset
127715 ** lists, not including the nul-terminator byte. For example:
127716 */
127717 static int fts3SegReaderNextDocid(
127718   Fts3Table *pTab,
127719   Fts3SegReader *pReader,         /* Reader to advance to next docid */
127720   char **ppOffsetList,            /* OUT: Pointer to current position-list */
127721   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
127722 ){
127723   int rc = SQLITE_OK;
127724   char *p = pReader->pOffsetList;
127725   char c = 0;
127726
127727   assert( p );
127728
127729   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
127730     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
127731     ** Pending-terms doclists are always built up in ascending order, so
127732     ** we have to iterate through them backwards here. */
127733     u8 bEof = 0;
127734     if( ppOffsetList ){
127735       *ppOffsetList = pReader->pOffsetList;
127736       *pnOffsetList = pReader->nOffsetList - 1;
127737     }
127738     sqlite3Fts3DoclistPrev(0,
127739         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
127740         &pReader->nOffsetList, &bEof
127741     );
127742     if( bEof ){
127743       pReader->pOffsetList = 0;
127744     }else{
127745       pReader->pOffsetList = p;
127746     }
127747   }else{
127748     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
127749
127750     /* Pointer p currently points at the first byte of an offset list. The
127751     ** following block advances it to point one byte past the end of
127752     ** the same offset list. */
127753     while( 1 ){
127754   
127755       /* The following line of code (and the "p++" below the while() loop) is
127756       ** normally all that is required to move pointer p to the desired 
127757       ** position. The exception is if this node is being loaded from disk
127758       ** incrementally and pointer "p" now points to the first byte passed
127759       ** the populated part of pReader->aNode[].
127760       */
127761       while( *p | c ) c = *p++ & 0x80;
127762       assert( *p==0 );
127763   
127764       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
127765       rc = fts3SegReaderIncrRead(pReader);
127766       if( rc!=SQLITE_OK ) return rc;
127767     }
127768     p++;
127769   
127770     /* If required, populate the output variables with a pointer to and the
127771     ** size of the previous offset-list.
127772     */
127773     if( ppOffsetList ){
127774       *ppOffsetList = pReader->pOffsetList;
127775       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
127776     }
127777
127778     /* List may have been edited in place by fts3EvalNearTrim() */
127779     while( p<pEnd && *p==0 ) p++;
127780   
127781     /* If there are no more entries in the doclist, set pOffsetList to
127782     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
127783     ** Fts3SegReader.pOffsetList to point to the next offset list before
127784     ** returning.
127785     */
127786     if( p>=pEnd ){
127787       pReader->pOffsetList = 0;
127788     }else{
127789       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
127790       if( rc==SQLITE_OK ){
127791         sqlite3_int64 iDelta;
127792         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
127793         if( pTab->bDescIdx ){
127794           pReader->iDocid -= iDelta;
127795         }else{
127796           pReader->iDocid += iDelta;
127797         }
127798       }
127799     }
127800   }
127801
127802   return SQLITE_OK;
127803 }
127804
127805
127806 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
127807   Fts3Cursor *pCsr, 
127808   Fts3MultiSegReader *pMsr,
127809   int *pnOvfl
127810 ){
127811   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
127812   int nOvfl = 0;
127813   int ii;
127814   int rc = SQLITE_OK;
127815   int pgsz = p->nPgsz;
127816
127817   assert( p->bFts4 );
127818   assert( pgsz>0 );
127819
127820   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
127821     Fts3SegReader *pReader = pMsr->apSegment[ii];
127822     if( !fts3SegReaderIsPending(pReader) 
127823      && !fts3SegReaderIsRootOnly(pReader) 
127824     ){
127825       sqlite3_int64 jj;
127826       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
127827         int nBlob;
127828         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
127829         if( rc!=SQLITE_OK ) break;
127830         if( (nBlob+35)>pgsz ){
127831           nOvfl += (nBlob + 34)/pgsz;
127832         }
127833       }
127834     }
127835   }
127836   *pnOvfl = nOvfl;
127837   return rc;
127838 }
127839
127840 /*
127841 ** Free all allocations associated with the iterator passed as the 
127842 ** second argument.
127843 */
127844 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
127845   if( pReader && !fts3SegReaderIsPending(pReader) ){
127846     sqlite3_free(pReader->zTerm);
127847     if( !fts3SegReaderIsRootOnly(pReader) ){
127848       sqlite3_free(pReader->aNode);
127849       sqlite3_blob_close(pReader->pBlob);
127850     }
127851   }
127852   sqlite3_free(pReader);
127853 }
127854
127855 /*
127856 ** Allocate a new SegReader object.
127857 */
127858 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
127859   int iAge,                       /* Segment "age". */
127860   int bLookup,                    /* True for a lookup only */
127861   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
127862   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
127863   sqlite3_int64 iEndBlock,        /* Final block of segment */
127864   const char *zRoot,              /* Buffer containing root node */
127865   int nRoot,                      /* Size of buffer containing root node */
127866   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
127867 ){
127868   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
127869   int nExtra = 0;                 /* Bytes to allocate segment root node */
127870
127871   assert( iStartLeaf<=iEndLeaf );
127872   if( iStartLeaf==0 ){
127873     nExtra = nRoot + FTS3_NODE_PADDING;
127874   }
127875
127876   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
127877   if( !pReader ){
127878     return SQLITE_NOMEM;
127879   }
127880   memset(pReader, 0, sizeof(Fts3SegReader));
127881   pReader->iIdx = iAge;
127882   pReader->bLookup = bLookup!=0;
127883   pReader->iStartBlock = iStartLeaf;
127884   pReader->iLeafEndBlock = iEndLeaf;
127885   pReader->iEndBlock = iEndBlock;
127886
127887   if( nExtra ){
127888     /* The entire segment is stored in the root node. */
127889     pReader->aNode = (char *)&pReader[1];
127890     pReader->rootOnly = 1;
127891     pReader->nNode = nRoot;
127892     memcpy(pReader->aNode, zRoot, nRoot);
127893     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
127894   }else{
127895     pReader->iCurrentBlock = iStartLeaf-1;
127896   }
127897   *ppReader = pReader;
127898   return SQLITE_OK;
127899 }
127900
127901 /*
127902 ** This is a comparison function used as a qsort() callback when sorting
127903 ** an array of pending terms by term. This occurs as part of flushing
127904 ** the contents of the pending-terms hash table to the database.
127905 */
127906 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
127907   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
127908   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
127909   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
127910   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
127911
127912   int n = (n1<n2 ? n1 : n2);
127913   int c = memcmp(z1, z2, n);
127914   if( c==0 ){
127915     c = n1 - n2;
127916   }
127917   return c;
127918 }
127919
127920 /*
127921 ** This function is used to allocate an Fts3SegReader that iterates through
127922 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
127923 **
127924 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
127925 ** through each term in the pending-terms table. Or, if isPrefixIter is
127926 ** non-zero, it iterates through each term and its prefixes. For example, if
127927 ** the pending terms hash table contains the terms "sqlite", "mysql" and
127928 ** "firebird", then the iterator visits the following 'terms' (in the order
127929 ** shown):
127930 **
127931 **   f fi fir fire fireb firebi firebir firebird
127932 **   m my mys mysq mysql
127933 **   s sq sql sqli sqlit sqlite
127934 **
127935 ** Whereas if isPrefixIter is zero, the terms visited are:
127936 **
127937 **   firebird mysql sqlite
127938 */
127939 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
127940   Fts3Table *p,                   /* Virtual table handle */
127941   int iIndex,                     /* Index for p->aIndex */
127942   const char *zTerm,              /* Term to search for */
127943   int nTerm,                      /* Size of buffer zTerm */
127944   int bPrefix,                    /* True for a prefix iterator */
127945   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
127946 ){
127947   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
127948   Fts3HashElem *pE;               /* Iterator variable */
127949   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
127950   int nElem = 0;                  /* Size of array at aElem */
127951   int rc = SQLITE_OK;             /* Return Code */
127952   Fts3Hash *pHash;
127953
127954   pHash = &p->aIndex[iIndex].hPending;
127955   if( bPrefix ){
127956     int nAlloc = 0;               /* Size of allocated array at aElem */
127957
127958     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
127959       char *zKey = (char *)fts3HashKey(pE);
127960       int nKey = fts3HashKeysize(pE);
127961       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
127962         if( nElem==nAlloc ){
127963           Fts3HashElem **aElem2;
127964           nAlloc += 16;
127965           aElem2 = (Fts3HashElem **)sqlite3_realloc(
127966               aElem, nAlloc*sizeof(Fts3HashElem *)
127967           );
127968           if( !aElem2 ){
127969             rc = SQLITE_NOMEM;
127970             nElem = 0;
127971             break;
127972           }
127973           aElem = aElem2;
127974         }
127975
127976         aElem[nElem++] = pE;
127977       }
127978     }
127979
127980     /* If more than one term matches the prefix, sort the Fts3HashElem
127981     ** objects in term order using qsort(). This uses the same comparison
127982     ** callback as is used when flushing terms to disk.
127983     */
127984     if( nElem>1 ){
127985       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
127986     }
127987
127988   }else{
127989     /* The query is a simple term lookup that matches at most one term in
127990     ** the index. All that is required is a straight hash-lookup. 
127991     **
127992     ** Because the stack address of pE may be accessed via the aElem pointer
127993     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
127994     ** within this entire function, not just this "else{...}" block.
127995     */
127996     pE = fts3HashFindElem(pHash, zTerm, nTerm);
127997     if( pE ){
127998       aElem = &pE;
127999       nElem = 1;
128000     }
128001   }
128002
128003   if( nElem>0 ){
128004     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
128005     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
128006     if( !pReader ){
128007       rc = SQLITE_NOMEM;
128008     }else{
128009       memset(pReader, 0, nByte);
128010       pReader->iIdx = 0x7FFFFFFF;
128011       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
128012       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
128013     }
128014   }
128015
128016   if( bPrefix ){
128017     sqlite3_free(aElem);
128018   }
128019   *ppReader = pReader;
128020   return rc;
128021 }
128022
128023 /*
128024 ** Compare the entries pointed to by two Fts3SegReader structures. 
128025 ** Comparison is as follows:
128026 **
128027 **   1) EOF is greater than not EOF.
128028 **
128029 **   2) The current terms (if any) are compared using memcmp(). If one
128030 **      term is a prefix of another, the longer term is considered the
128031 **      larger.
128032 **
128033 **   3) By segment age. An older segment is considered larger.
128034 */
128035 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
128036   int rc;
128037   if( pLhs->aNode && pRhs->aNode ){
128038     int rc2 = pLhs->nTerm - pRhs->nTerm;
128039     if( rc2<0 ){
128040       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
128041     }else{
128042       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
128043     }
128044     if( rc==0 ){
128045       rc = rc2;
128046     }
128047   }else{
128048     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
128049   }
128050   if( rc==0 ){
128051     rc = pRhs->iIdx - pLhs->iIdx;
128052   }
128053   assert( rc!=0 );
128054   return rc;
128055 }
128056
128057 /*
128058 ** A different comparison function for SegReader structures. In this
128059 ** version, it is assumed that each SegReader points to an entry in
128060 ** a doclist for identical terms. Comparison is made as follows:
128061 **
128062 **   1) EOF (end of doclist in this case) is greater than not EOF.
128063 **
128064 **   2) By current docid.
128065 **
128066 **   3) By segment age. An older segment is considered larger.
128067 */
128068 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
128069   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
128070   if( rc==0 ){
128071     if( pLhs->iDocid==pRhs->iDocid ){
128072       rc = pRhs->iIdx - pLhs->iIdx;
128073     }else{
128074       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
128075     }
128076   }
128077   assert( pLhs->aNode && pRhs->aNode );
128078   return rc;
128079 }
128080 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
128081   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
128082   if( rc==0 ){
128083     if( pLhs->iDocid==pRhs->iDocid ){
128084       rc = pRhs->iIdx - pLhs->iIdx;
128085     }else{
128086       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
128087     }
128088   }
128089   assert( pLhs->aNode && pRhs->aNode );
128090   return rc;
128091 }
128092
128093 /*
128094 ** Compare the term that the Fts3SegReader object passed as the first argument
128095 ** points to with the term specified by arguments zTerm and nTerm. 
128096 **
128097 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
128098 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
128099 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
128100 */
128101 static int fts3SegReaderTermCmp(
128102   Fts3SegReader *pSeg,            /* Segment reader object */
128103   const char *zTerm,              /* Term to compare to */
128104   int nTerm                       /* Size of term zTerm in bytes */
128105 ){
128106   int res = 0;
128107   if( pSeg->aNode ){
128108     if( pSeg->nTerm>nTerm ){
128109       res = memcmp(pSeg->zTerm, zTerm, nTerm);
128110     }else{
128111       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
128112     }
128113     if( res==0 ){
128114       res = pSeg->nTerm-nTerm;
128115     }
128116   }
128117   return res;
128118 }
128119
128120 /*
128121 ** Argument apSegment is an array of nSegment elements. It is known that
128122 ** the final (nSegment-nSuspect) members are already in sorted order
128123 ** (according to the comparison function provided). This function shuffles
128124 ** the array around until all entries are in sorted order.
128125 */
128126 static void fts3SegReaderSort(
128127   Fts3SegReader **apSegment,                     /* Array to sort entries of */
128128   int nSegment,                                  /* Size of apSegment array */
128129   int nSuspect,                                  /* Unsorted entry count */
128130   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
128131 ){
128132   int i;                          /* Iterator variable */
128133
128134   assert( nSuspect<=nSegment );
128135
128136   if( nSuspect==nSegment ) nSuspect--;
128137   for(i=nSuspect-1; i>=0; i--){
128138     int j;
128139     for(j=i; j<(nSegment-1); j++){
128140       Fts3SegReader *pTmp;
128141       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
128142       pTmp = apSegment[j+1];
128143       apSegment[j+1] = apSegment[j];
128144       apSegment[j] = pTmp;
128145     }
128146   }
128147
128148 #ifndef NDEBUG
128149   /* Check that the list really is sorted now. */
128150   for(i=0; i<(nSuspect-1); i++){
128151     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
128152   }
128153 #endif
128154 }
128155
128156 /* 
128157 ** Insert a record into the %_segments table.
128158 */
128159 static int fts3WriteSegment(
128160   Fts3Table *p,                   /* Virtual table handle */
128161   sqlite3_int64 iBlock,           /* Block id for new block */
128162   char *z,                        /* Pointer to buffer containing block data */
128163   int n                           /* Size of buffer z in bytes */
128164 ){
128165   sqlite3_stmt *pStmt;
128166   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
128167   if( rc==SQLITE_OK ){
128168     sqlite3_bind_int64(pStmt, 1, iBlock);
128169     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
128170     sqlite3_step(pStmt);
128171     rc = sqlite3_reset(pStmt);
128172   }
128173   return rc;
128174 }
128175
128176 /*
128177 ** Find the largest relative level number in the table. If successful, set
128178 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
128179 ** set *pnMax to zero and return an SQLite error code.
128180 */
128181 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
128182   int rc;
128183   int mxLevel = 0;
128184   sqlite3_stmt *pStmt = 0;
128185
128186   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
128187   if( rc==SQLITE_OK ){
128188     if( SQLITE_ROW==sqlite3_step(pStmt) ){
128189       mxLevel = sqlite3_column_int(pStmt, 0);
128190     }
128191     rc = sqlite3_reset(pStmt);
128192   }
128193   *pnMax = mxLevel;
128194   return rc;
128195 }
128196
128197 /* 
128198 ** Insert a record into the %_segdir table.
128199 */
128200 static int fts3WriteSegdir(
128201   Fts3Table *p,                   /* Virtual table handle */
128202   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
128203   int iIdx,                       /* Value for "idx" field */
128204   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
128205   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
128206   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
128207   char *zRoot,                    /* Blob value for "root" field */
128208   int nRoot                       /* Number of bytes in buffer zRoot */
128209 ){
128210   sqlite3_stmt *pStmt;
128211   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
128212   if( rc==SQLITE_OK ){
128213     sqlite3_bind_int64(pStmt, 1, iLevel);
128214     sqlite3_bind_int(pStmt, 2, iIdx);
128215     sqlite3_bind_int64(pStmt, 3, iStartBlock);
128216     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
128217     sqlite3_bind_int64(pStmt, 5, iEndBlock);
128218     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
128219     sqlite3_step(pStmt);
128220     rc = sqlite3_reset(pStmt);
128221   }
128222   return rc;
128223 }
128224
128225 /*
128226 ** Return the size of the common prefix (if any) shared by zPrev and
128227 ** zNext, in bytes. For example, 
128228 **
128229 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
128230 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
128231 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
128232 */
128233 static int fts3PrefixCompress(
128234   const char *zPrev,              /* Buffer containing previous term */
128235   int nPrev,                      /* Size of buffer zPrev in bytes */
128236   const char *zNext,              /* Buffer containing next term */
128237   int nNext                       /* Size of buffer zNext in bytes */
128238 ){
128239   int n;
128240   UNUSED_PARAMETER(nNext);
128241   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
128242   return n;
128243 }
128244
128245 /*
128246 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
128247 ** (according to memcmp) than the previous term.
128248 */
128249 static int fts3NodeAddTerm(
128250   Fts3Table *p,                   /* Virtual table handle */
128251   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
128252   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
128253   const char *zTerm,              /* Pointer to buffer containing term */
128254   int nTerm                       /* Size of term in bytes */
128255 ){
128256   SegmentNode *pTree = *ppTree;
128257   int rc;
128258   SegmentNode *pNew;
128259
128260   /* First try to append the term to the current node. Return early if 
128261   ** this is possible.
128262   */
128263   if( pTree ){
128264     int nData = pTree->nData;     /* Current size of node in bytes */
128265     int nReq = nData;             /* Required space after adding zTerm */
128266     int nPrefix;                  /* Number of bytes of prefix compression */
128267     int nSuffix;                  /* Suffix length */
128268
128269     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
128270     nSuffix = nTerm-nPrefix;
128271
128272     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
128273     if( nReq<=p->nNodeSize || !pTree->zTerm ){
128274
128275       if( nReq>p->nNodeSize ){
128276         /* An unusual case: this is the first term to be added to the node
128277         ** and the static node buffer (p->nNodeSize bytes) is not large
128278         ** enough. Use a separately malloced buffer instead This wastes
128279         ** p->nNodeSize bytes, but since this scenario only comes about when
128280         ** the database contain two terms that share a prefix of almost 2KB, 
128281         ** this is not expected to be a serious problem. 
128282         */
128283         assert( pTree->aData==(char *)&pTree[1] );
128284         pTree->aData = (char *)sqlite3_malloc(nReq);
128285         if( !pTree->aData ){
128286           return SQLITE_NOMEM;
128287         }
128288       }
128289
128290       if( pTree->zTerm ){
128291         /* There is no prefix-length field for first term in a node */
128292         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
128293       }
128294
128295       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
128296       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
128297       pTree->nData = nData + nSuffix;
128298       pTree->nEntry++;
128299
128300       if( isCopyTerm ){
128301         if( pTree->nMalloc<nTerm ){
128302           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
128303           if( !zNew ){
128304             return SQLITE_NOMEM;
128305           }
128306           pTree->nMalloc = nTerm*2;
128307           pTree->zMalloc = zNew;
128308         }
128309         pTree->zTerm = pTree->zMalloc;
128310         memcpy(pTree->zTerm, zTerm, nTerm);
128311         pTree->nTerm = nTerm;
128312       }else{
128313         pTree->zTerm = (char *)zTerm;
128314         pTree->nTerm = nTerm;
128315       }
128316       return SQLITE_OK;
128317     }
128318   }
128319
128320   /* If control flows to here, it was not possible to append zTerm to the
128321   ** current node. Create a new node (a right-sibling of the current node).
128322   ** If this is the first node in the tree, the term is added to it.
128323   **
128324   ** Otherwise, the term is not added to the new node, it is left empty for
128325   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
128326   ** has no parent, one is created here.
128327   */
128328   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
128329   if( !pNew ){
128330     return SQLITE_NOMEM;
128331   }
128332   memset(pNew, 0, sizeof(SegmentNode));
128333   pNew->nData = 1 + FTS3_VARINT_MAX;
128334   pNew->aData = (char *)&pNew[1];
128335
128336   if( pTree ){
128337     SegmentNode *pParent = pTree->pParent;
128338     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
128339     if( pTree->pParent==0 ){
128340       pTree->pParent = pParent;
128341     }
128342     pTree->pRight = pNew;
128343     pNew->pLeftmost = pTree->pLeftmost;
128344     pNew->pParent = pParent;
128345     pNew->zMalloc = pTree->zMalloc;
128346     pNew->nMalloc = pTree->nMalloc;
128347     pTree->zMalloc = 0;
128348   }else{
128349     pNew->pLeftmost = pNew;
128350     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
128351   }
128352
128353   *ppTree = pNew;
128354   return rc;
128355 }
128356
128357 /*
128358 ** Helper function for fts3NodeWrite().
128359 */
128360 static int fts3TreeFinishNode(
128361   SegmentNode *pTree, 
128362   int iHeight, 
128363   sqlite3_int64 iLeftChild
128364 ){
128365   int nStart;
128366   assert( iHeight>=1 && iHeight<128 );
128367   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
128368   pTree->aData[nStart] = (char)iHeight;
128369   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
128370   return nStart;
128371 }
128372
128373 /*
128374 ** Write the buffer for the segment node pTree and all of its peers to the
128375 ** database. Then call this function recursively to write the parent of 
128376 ** pTree and its peers to the database. 
128377 **
128378 ** Except, if pTree is a root node, do not write it to the database. Instead,
128379 ** set output variables *paRoot and *pnRoot to contain the root node.
128380 **
128381 ** If successful, SQLITE_OK is returned and output variable *piLast is
128382 ** set to the largest blockid written to the database (or zero if no
128383 ** blocks were written to the db). Otherwise, an SQLite error code is 
128384 ** returned.
128385 */
128386 static int fts3NodeWrite(
128387   Fts3Table *p,                   /* Virtual table handle */
128388   SegmentNode *pTree,             /* SegmentNode handle */
128389   int iHeight,                    /* Height of this node in tree */
128390   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
128391   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
128392   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
128393   char **paRoot,                  /* OUT: Data for root node */
128394   int *pnRoot                     /* OUT: Size of root node in bytes */
128395 ){
128396   int rc = SQLITE_OK;
128397
128398   if( !pTree->pParent ){
128399     /* Root node of the tree. */
128400     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
128401     *piLast = iFree-1;
128402     *pnRoot = pTree->nData - nStart;
128403     *paRoot = &pTree->aData[nStart];
128404   }else{
128405     SegmentNode *pIter;
128406     sqlite3_int64 iNextFree = iFree;
128407     sqlite3_int64 iNextLeaf = iLeaf;
128408     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
128409       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
128410       int nWrite = pIter->nData - nStart;
128411   
128412       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
128413       iNextFree++;
128414       iNextLeaf += (pIter->nEntry+1);
128415     }
128416     if( rc==SQLITE_OK ){
128417       assert( iNextLeaf==iFree );
128418       rc = fts3NodeWrite(
128419           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
128420       );
128421     }
128422   }
128423
128424   return rc;
128425 }
128426
128427 /*
128428 ** Free all memory allocations associated with the tree pTree.
128429 */
128430 static void fts3NodeFree(SegmentNode *pTree){
128431   if( pTree ){
128432     SegmentNode *p = pTree->pLeftmost;
128433     fts3NodeFree(p->pParent);
128434     while( p ){
128435       SegmentNode *pRight = p->pRight;
128436       if( p->aData!=(char *)&p[1] ){
128437         sqlite3_free(p->aData);
128438       }
128439       assert( pRight==0 || p->zMalloc==0 );
128440       sqlite3_free(p->zMalloc);
128441       sqlite3_free(p);
128442       p = pRight;
128443     }
128444   }
128445 }
128446
128447 /*
128448 ** Add a term to the segment being constructed by the SegmentWriter object
128449 ** *ppWriter. When adding the first term to a segment, *ppWriter should
128450 ** be passed NULL. This function will allocate a new SegmentWriter object
128451 ** and return it via the input/output variable *ppWriter in this case.
128452 **
128453 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
128454 */
128455 static int fts3SegWriterAdd(
128456   Fts3Table *p,                   /* Virtual table handle */
128457   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
128458   int isCopyTerm,                 /* True if buffer zTerm must be copied */
128459   const char *zTerm,              /* Pointer to buffer containing term */
128460   int nTerm,                      /* Size of term in bytes */
128461   const char *aDoclist,           /* Pointer to buffer containing doclist */
128462   int nDoclist                    /* Size of doclist in bytes */
128463 ){
128464   int nPrefix;                    /* Size of term prefix in bytes */
128465   int nSuffix;                    /* Size of term suffix in bytes */
128466   int nReq;                       /* Number of bytes required on leaf page */
128467   int nData;
128468   SegmentWriter *pWriter = *ppWriter;
128469
128470   if( !pWriter ){
128471     int rc;
128472     sqlite3_stmt *pStmt;
128473
128474     /* Allocate the SegmentWriter structure */
128475     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
128476     if( !pWriter ) return SQLITE_NOMEM;
128477     memset(pWriter, 0, sizeof(SegmentWriter));
128478     *ppWriter = pWriter;
128479
128480     /* Allocate a buffer in which to accumulate data */
128481     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
128482     if( !pWriter->aData ) return SQLITE_NOMEM;
128483     pWriter->nSize = p->nNodeSize;
128484
128485     /* Find the next free blockid in the %_segments table */
128486     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
128487     if( rc!=SQLITE_OK ) return rc;
128488     if( SQLITE_ROW==sqlite3_step(pStmt) ){
128489       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
128490       pWriter->iFirst = pWriter->iFree;
128491     }
128492     rc = sqlite3_reset(pStmt);
128493     if( rc!=SQLITE_OK ) return rc;
128494   }
128495   nData = pWriter->nData;
128496
128497   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
128498   nSuffix = nTerm-nPrefix;
128499
128500   /* Figure out how many bytes are required by this new entry */
128501   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
128502     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
128503     nSuffix +                               /* Term suffix */
128504     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
128505     nDoclist;                               /* Doclist data */
128506
128507   if( nData>0 && nData+nReq>p->nNodeSize ){
128508     int rc;
128509
128510     /* The current leaf node is full. Write it out to the database. */
128511     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
128512     if( rc!=SQLITE_OK ) return rc;
128513     p->nLeafAdd++;
128514
128515     /* Add the current term to the interior node tree. The term added to
128516     ** the interior tree must:
128517     **
128518     **   a) be greater than the largest term on the leaf node just written
128519     **      to the database (still available in pWriter->zTerm), and
128520     **
128521     **   b) be less than or equal to the term about to be added to the new
128522     **      leaf node (zTerm/nTerm).
128523     **
128524     ** In other words, it must be the prefix of zTerm 1 byte longer than
128525     ** the common prefix (if any) of zTerm and pWriter->zTerm.
128526     */
128527     assert( nPrefix<nTerm );
128528     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
128529     if( rc!=SQLITE_OK ) return rc;
128530
128531     nData = 0;
128532     pWriter->nTerm = 0;
128533
128534     nPrefix = 0;
128535     nSuffix = nTerm;
128536     nReq = 1 +                              /* varint containing prefix size */
128537       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
128538       nTerm +                               /* Term suffix */
128539       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
128540       nDoclist;                             /* Doclist data */
128541   }
128542
128543   /* If the buffer currently allocated is too small for this entry, realloc
128544   ** the buffer to make it large enough.
128545   */
128546   if( nReq>pWriter->nSize ){
128547     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
128548     if( !aNew ) return SQLITE_NOMEM;
128549     pWriter->aData = aNew;
128550     pWriter->nSize = nReq;
128551   }
128552   assert( nData+nReq<=pWriter->nSize );
128553
128554   /* Append the prefix-compressed term and doclist to the buffer. */
128555   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
128556   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
128557   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
128558   nData += nSuffix;
128559   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
128560   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
128561   pWriter->nData = nData + nDoclist;
128562
128563   /* Save the current term so that it can be used to prefix-compress the next.
128564   ** If the isCopyTerm parameter is true, then the buffer pointed to by
128565   ** zTerm is transient, so take a copy of the term data. Otherwise, just
128566   ** store a copy of the pointer.
128567   */
128568   if( isCopyTerm ){
128569     if( nTerm>pWriter->nMalloc ){
128570       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
128571       if( !zNew ){
128572         return SQLITE_NOMEM;
128573       }
128574       pWriter->nMalloc = nTerm*2;
128575       pWriter->zMalloc = zNew;
128576       pWriter->zTerm = zNew;
128577     }
128578     assert( pWriter->zTerm==pWriter->zMalloc );
128579     memcpy(pWriter->zTerm, zTerm, nTerm);
128580   }else{
128581     pWriter->zTerm = (char *)zTerm;
128582   }
128583   pWriter->nTerm = nTerm;
128584
128585   return SQLITE_OK;
128586 }
128587
128588 /*
128589 ** Flush all data associated with the SegmentWriter object pWriter to the
128590 ** database. This function must be called after all terms have been added
128591 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
128592 ** returned. Otherwise, an SQLite error code.
128593 */
128594 static int fts3SegWriterFlush(
128595   Fts3Table *p,                   /* Virtual table handle */
128596   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
128597   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
128598   int iIdx                        /* Value for 'idx' column of %_segdir */
128599 ){
128600   int rc;                         /* Return code */
128601   if( pWriter->pTree ){
128602     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
128603     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
128604     char *zRoot = NULL;           /* Pointer to buffer containing root node */
128605     int nRoot = 0;                /* Size of buffer zRoot */
128606
128607     iLastLeaf = pWriter->iFree;
128608     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
128609     if( rc==SQLITE_OK ){
128610       rc = fts3NodeWrite(p, pWriter->pTree, 1,
128611           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
128612     }
128613     if( rc==SQLITE_OK ){
128614       rc = fts3WriteSegdir(
128615           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
128616     }
128617   }else{
128618     /* The entire tree fits on the root node. Write it to the segdir table. */
128619     rc = fts3WriteSegdir(
128620         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
128621   }
128622   p->nLeafAdd++;
128623   return rc;
128624 }
128625
128626 /*
128627 ** Release all memory held by the SegmentWriter object passed as the 
128628 ** first argument.
128629 */
128630 static void fts3SegWriterFree(SegmentWriter *pWriter){
128631   if( pWriter ){
128632     sqlite3_free(pWriter->aData);
128633     sqlite3_free(pWriter->zMalloc);
128634     fts3NodeFree(pWriter->pTree);
128635     sqlite3_free(pWriter);
128636   }
128637 }
128638
128639 /*
128640 ** The first value in the apVal[] array is assumed to contain an integer.
128641 ** This function tests if there exist any documents with docid values that
128642 ** are different from that integer. i.e. if deleting the document with docid
128643 ** pRowid would mean the FTS3 table were empty.
128644 **
128645 ** If successful, *pisEmpty is set to true if the table is empty except for
128646 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
128647 ** error occurs, an SQLite error code is returned.
128648 */
128649 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
128650   sqlite3_stmt *pStmt;
128651   int rc;
128652   if( p->zContentTbl ){
128653     /* If using the content=xxx option, assume the table is never empty */
128654     *pisEmpty = 0;
128655     rc = SQLITE_OK;
128656   }else{
128657     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
128658     if( rc==SQLITE_OK ){
128659       if( SQLITE_ROW==sqlite3_step(pStmt) ){
128660         *pisEmpty = sqlite3_column_int(pStmt, 0);
128661       }
128662       rc = sqlite3_reset(pStmt);
128663     }
128664   }
128665   return rc;
128666 }
128667
128668 /*
128669 ** Set *pnMax to the largest segment level in the database for the index
128670 ** iIndex.
128671 **
128672 ** Segment levels are stored in the 'level' column of the %_segdir table.
128673 **
128674 ** Return SQLITE_OK if successful, or an SQLite error code if not.
128675 */
128676 static int fts3SegmentMaxLevel(
128677   Fts3Table *p, 
128678   int iLangid,
128679   int iIndex, 
128680   sqlite3_int64 *pnMax
128681 ){
128682   sqlite3_stmt *pStmt;
128683   int rc;
128684   assert( iIndex>=0 && iIndex<p->nIndex );
128685
128686   /* Set pStmt to the compiled version of:
128687   **
128688   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
128689   **
128690   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
128691   */
128692   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
128693   if( rc!=SQLITE_OK ) return rc;
128694   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
128695   sqlite3_bind_int64(pStmt, 2, 
128696       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
128697   );
128698   if( SQLITE_ROW==sqlite3_step(pStmt) ){
128699     *pnMax = sqlite3_column_int64(pStmt, 0);
128700   }
128701   return sqlite3_reset(pStmt);
128702 }
128703
128704 /*
128705 ** Delete all entries in the %_segments table associated with the segment
128706 ** opened with seg-reader pSeg. This function does not affect the contents
128707 ** of the %_segdir table.
128708 */
128709 static int fts3DeleteSegment(
128710   Fts3Table *p,                   /* FTS table handle */
128711   Fts3SegReader *pSeg             /* Segment to delete */
128712 ){
128713   int rc = SQLITE_OK;             /* Return code */
128714   if( pSeg->iStartBlock ){
128715     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
128716     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
128717     if( rc==SQLITE_OK ){
128718       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
128719       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
128720       sqlite3_step(pDelete);
128721       rc = sqlite3_reset(pDelete);
128722     }
128723   }
128724   return rc;
128725 }
128726
128727 /*
128728 ** This function is used after merging multiple segments into a single large
128729 ** segment to delete the old, now redundant, segment b-trees. Specifically,
128730 ** it:
128731 ** 
128732 **   1) Deletes all %_segments entries for the segments associated with 
128733 **      each of the SegReader objects in the array passed as the third 
128734 **      argument, and
128735 **
128736 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
128737 **      entries regardless of level if (iLevel<0).
128738 **
128739 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
128740 */
128741 static int fts3DeleteSegdir(
128742   Fts3Table *p,                   /* Virtual table handle */
128743   int iLangid,                    /* Language id */
128744   int iIndex,                     /* Index for p->aIndex */
128745   int iLevel,                     /* Level of %_segdir entries to delete */
128746   Fts3SegReader **apSegment,      /* Array of SegReader objects */
128747   int nReader                     /* Size of array apSegment */
128748 ){
128749   int rc = SQLITE_OK;             /* Return Code */
128750   int i;                          /* Iterator variable */
128751   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
128752
128753   for(i=0; rc==SQLITE_OK && i<nReader; i++){
128754     rc = fts3DeleteSegment(p, apSegment[i]);
128755   }
128756   if( rc!=SQLITE_OK ){
128757     return rc;
128758   }
128759
128760   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
128761   if( iLevel==FTS3_SEGCURSOR_ALL ){
128762     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
128763     if( rc==SQLITE_OK ){
128764       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
128765       sqlite3_bind_int64(pDelete, 2, 
128766           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
128767       );
128768     }
128769   }else{
128770     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
128771     if( rc==SQLITE_OK ){
128772       sqlite3_bind_int64(
128773           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
128774       );
128775     }
128776   }
128777
128778   if( rc==SQLITE_OK ){
128779     sqlite3_step(pDelete);
128780     rc = sqlite3_reset(pDelete);
128781   }
128782
128783   return rc;
128784 }
128785
128786 /*
128787 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
128788 ** a position list that may (or may not) feature multiple columns. This
128789 ** function adjusts the pointer *ppList and the length *pnList so that they
128790 ** identify the subset of the position list that corresponds to column iCol.
128791 **
128792 ** If there are no entries in the input position list for column iCol, then
128793 ** *pnList is set to zero before returning.
128794 **
128795 ** If parameter bZero is non-zero, then any part of the input list following
128796 ** the end of the output list is zeroed before returning.
128797 */
128798 static void fts3ColumnFilter(
128799   int iCol,                       /* Column to filter on */
128800   int bZero,                      /* Zero out anything following *ppList */
128801   char **ppList,                  /* IN/OUT: Pointer to position list */
128802   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
128803 ){
128804   char *pList = *ppList;
128805   int nList = *pnList;
128806   char *pEnd = &pList[nList];
128807   int iCurrent = 0;
128808   char *p = pList;
128809
128810   assert( iCol>=0 );
128811   while( 1 ){
128812     char c = 0;
128813     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
128814   
128815     if( iCol==iCurrent ){
128816       nList = (int)(p - pList);
128817       break;
128818     }
128819
128820     nList -= (int)(p - pList);
128821     pList = p;
128822     if( nList==0 ){
128823       break;
128824     }
128825     p = &pList[1];
128826     p += sqlite3Fts3GetVarint32(p, &iCurrent);
128827   }
128828
128829   if( bZero && &pList[nList]!=pEnd ){
128830     memset(&pList[nList], 0, pEnd - &pList[nList]);
128831   }
128832   *ppList = pList;
128833   *pnList = nList;
128834 }
128835
128836 /*
128837 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
128838 ** existing data). Grow the buffer if required.
128839 **
128840 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
128841 ** trying to resize the buffer, return SQLITE_NOMEM.
128842 */
128843 static int fts3MsrBufferData(
128844   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
128845   char *pList,
128846   int nList
128847 ){
128848   if( nList>pMsr->nBuffer ){
128849     char *pNew;
128850     pMsr->nBuffer = nList*2;
128851     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
128852     if( !pNew ) return SQLITE_NOMEM;
128853     pMsr->aBuffer = pNew;
128854   }
128855
128856   memcpy(pMsr->aBuffer, pList, nList);
128857   return SQLITE_OK;
128858 }
128859
128860 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
128861   Fts3Table *p,                   /* Virtual table handle */
128862   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
128863   sqlite3_int64 *piDocid,         /* OUT: Docid value */
128864   char **paPoslist,               /* OUT: Pointer to position list */
128865   int *pnPoslist                  /* OUT: Size of position list in bytes */
128866 ){
128867   int nMerge = pMsr->nAdvance;
128868   Fts3SegReader **apSegment = pMsr->apSegment;
128869   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
128870     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
128871   );
128872
128873   if( nMerge==0 ){
128874     *paPoslist = 0;
128875     return SQLITE_OK;
128876   }
128877
128878   while( 1 ){
128879     Fts3SegReader *pSeg;
128880     pSeg = pMsr->apSegment[0];
128881
128882     if( pSeg->pOffsetList==0 ){
128883       *paPoslist = 0;
128884       break;
128885     }else{
128886       int rc;
128887       char *pList;
128888       int nList;
128889       int j;
128890       sqlite3_int64 iDocid = apSegment[0]->iDocid;
128891
128892       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
128893       j = 1;
128894       while( rc==SQLITE_OK 
128895         && j<nMerge
128896         && apSegment[j]->pOffsetList
128897         && apSegment[j]->iDocid==iDocid
128898       ){
128899         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
128900         j++;
128901       }
128902       if( rc!=SQLITE_OK ) return rc;
128903       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
128904
128905       if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
128906         rc = fts3MsrBufferData(pMsr, pList, nList+1);
128907         if( rc!=SQLITE_OK ) return rc;
128908         assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
128909         pList = pMsr->aBuffer;
128910       }
128911
128912       if( pMsr->iColFilter>=0 ){
128913         fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
128914       }
128915
128916       if( nList>0 ){
128917         *paPoslist = pList;
128918         *piDocid = iDocid;
128919         *pnPoslist = nList;
128920         break;
128921       }
128922     }
128923   }
128924
128925   return SQLITE_OK;
128926 }
128927
128928 static int fts3SegReaderStart(
128929   Fts3Table *p,                   /* Virtual table handle */
128930   Fts3MultiSegReader *pCsr,       /* Cursor object */
128931   const char *zTerm,              /* Term searched for (or NULL) */
128932   int nTerm                       /* Length of zTerm in bytes */
128933 ){
128934   int i;
128935   int nSeg = pCsr->nSegment;
128936
128937   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
128938   ** for, then advance each segment iterator until it points to a term of
128939   ** equal or greater value than the specified term. This prevents many
128940   ** unnecessary merge/sort operations for the case where single segment
128941   ** b-tree leaf nodes contain more than one term.
128942   */
128943   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
128944     int res = 0;
128945     Fts3SegReader *pSeg = pCsr->apSegment[i];
128946     do {
128947       int rc = fts3SegReaderNext(p, pSeg, 0);
128948       if( rc!=SQLITE_OK ) return rc;
128949     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
128950
128951     if( pSeg->bLookup && res!=0 ){
128952       fts3SegReaderSetEof(pSeg);
128953     }
128954   }
128955   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
128956
128957   return SQLITE_OK;
128958 }
128959
128960 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
128961   Fts3Table *p,                   /* Virtual table handle */
128962   Fts3MultiSegReader *pCsr,       /* Cursor object */
128963   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
128964 ){
128965   pCsr->pFilter = pFilter;
128966   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
128967 }
128968
128969 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
128970   Fts3Table *p,                   /* Virtual table handle */
128971   Fts3MultiSegReader *pCsr,       /* Cursor object */
128972   int iCol,                       /* Column to match on. */
128973   const char *zTerm,              /* Term to iterate through a doclist for */
128974   int nTerm                       /* Number of bytes in zTerm */
128975 ){
128976   int i;
128977   int rc;
128978   int nSegment = pCsr->nSegment;
128979   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
128980     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
128981   );
128982
128983   assert( pCsr->pFilter==0 );
128984   assert( zTerm && nTerm>0 );
128985
128986   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
128987   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
128988   if( rc!=SQLITE_OK ) return rc;
128989
128990   /* Determine how many of the segments actually point to zTerm/nTerm. */
128991   for(i=0; i<nSegment; i++){
128992     Fts3SegReader *pSeg = pCsr->apSegment[i];
128993     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
128994       break;
128995     }
128996   }
128997   pCsr->nAdvance = i;
128998
128999   /* Advance each of the segments to point to the first docid. */
129000   for(i=0; i<pCsr->nAdvance; i++){
129001     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
129002     if( rc!=SQLITE_OK ) return rc;
129003   }
129004   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
129005
129006   assert( iCol<0 || iCol<p->nColumn );
129007   pCsr->iColFilter = iCol;
129008
129009   return SQLITE_OK;
129010 }
129011
129012 /*
129013 ** This function is called on a MultiSegReader that has been started using
129014 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
129015 ** have been made. Calling this function puts the MultiSegReader in such
129016 ** a state that if the next two calls are:
129017 **
129018 **   sqlite3Fts3SegReaderStart()
129019 **   sqlite3Fts3SegReaderStep()
129020 **
129021 ** then the entire doclist for the term is available in 
129022 ** MultiSegReader.aDoclist/nDoclist.
129023 */
129024 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
129025   int i;                          /* Used to iterate through segment-readers */
129026
129027   assert( pCsr->zTerm==0 );
129028   assert( pCsr->nTerm==0 );
129029   assert( pCsr->aDoclist==0 );
129030   assert( pCsr->nDoclist==0 );
129031
129032   pCsr->nAdvance = 0;
129033   pCsr->bRestart = 1;
129034   for(i=0; i<pCsr->nSegment; i++){
129035     pCsr->apSegment[i]->pOffsetList = 0;
129036     pCsr->apSegment[i]->nOffsetList = 0;
129037     pCsr->apSegment[i]->iDocid = 0;
129038   }
129039
129040   return SQLITE_OK;
129041 }
129042
129043
129044 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
129045   Fts3Table *p,                   /* Virtual table handle */
129046   Fts3MultiSegReader *pCsr        /* Cursor object */
129047 ){
129048   int rc = SQLITE_OK;
129049
129050   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
129051   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
129052   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
129053   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
129054   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
129055   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
129056
129057   Fts3SegReader **apSegment = pCsr->apSegment;
129058   int nSegment = pCsr->nSegment;
129059   Fts3SegFilter *pFilter = pCsr->pFilter;
129060   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
129061     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
129062   );
129063
129064   if( pCsr->nSegment==0 ) return SQLITE_OK;
129065
129066   do {
129067     int nMerge;
129068     int i;
129069   
129070     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
129071     ** forward. Then sort the list in order of current term again.  
129072     */
129073     for(i=0; i<pCsr->nAdvance; i++){
129074       Fts3SegReader *pSeg = apSegment[i];
129075       if( pSeg->bLookup ){
129076         fts3SegReaderSetEof(pSeg);
129077       }else{
129078         rc = fts3SegReaderNext(p, pSeg, 0);
129079       }
129080       if( rc!=SQLITE_OK ) return rc;
129081     }
129082     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
129083     pCsr->nAdvance = 0;
129084
129085     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
129086     assert( rc==SQLITE_OK );
129087     if( apSegment[0]->aNode==0 ) break;
129088
129089     pCsr->nTerm = apSegment[0]->nTerm;
129090     pCsr->zTerm = apSegment[0]->zTerm;
129091
129092     /* If this is a prefix-search, and if the term that apSegment[0] points
129093     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
129094     ** required callbacks have been made. In this case exit early.
129095     **
129096     ** Similarly, if this is a search for an exact match, and the first term
129097     ** of segment apSegment[0] is not a match, exit early.
129098     */
129099     if( pFilter->zTerm && !isScan ){
129100       if( pCsr->nTerm<pFilter->nTerm 
129101        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
129102        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
129103       ){
129104         break;
129105       }
129106     }
129107
129108     nMerge = 1;
129109     while( nMerge<nSegment 
129110         && apSegment[nMerge]->aNode
129111         && apSegment[nMerge]->nTerm==pCsr->nTerm 
129112         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
129113     ){
129114       nMerge++;
129115     }
129116
129117     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
129118     if( nMerge==1 
129119      && !isIgnoreEmpty 
129120      && !isFirst 
129121      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
129122     ){
129123       pCsr->nDoclist = apSegment[0]->nDoclist;
129124       if( fts3SegReaderIsPending(apSegment[0]) ){
129125         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
129126         pCsr->aDoclist = pCsr->aBuffer;
129127       }else{
129128         pCsr->aDoclist = apSegment[0]->aDoclist;
129129       }
129130       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
129131     }else{
129132       int nDoclist = 0;           /* Size of doclist */
129133       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
129134
129135       /* The current term of the first nMerge entries in the array
129136       ** of Fts3SegReader objects is the same. The doclists must be merged
129137       ** and a single term returned with the merged doclist.
129138       */
129139       for(i=0; i<nMerge; i++){
129140         fts3SegReaderFirstDocid(p, apSegment[i]);
129141       }
129142       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
129143       while( apSegment[0]->pOffsetList ){
129144         int j;                    /* Number of segments that share a docid */
129145         char *pList;
129146         int nList;
129147         int nByte;
129148         sqlite3_int64 iDocid = apSegment[0]->iDocid;
129149         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
129150         j = 1;
129151         while( j<nMerge
129152             && apSegment[j]->pOffsetList
129153             && apSegment[j]->iDocid==iDocid
129154         ){
129155           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
129156           j++;
129157         }
129158
129159         if( isColFilter ){
129160           fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
129161         }
129162
129163         if( !isIgnoreEmpty || nList>0 ){
129164
129165           /* Calculate the 'docid' delta value to write into the merged 
129166           ** doclist. */
129167           sqlite3_int64 iDelta;
129168           if( p->bDescIdx && nDoclist>0 ){
129169             iDelta = iPrev - iDocid;
129170           }else{
129171             iDelta = iDocid - iPrev;
129172           }
129173           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
129174           assert( nDoclist>0 || iDelta==iDocid );
129175
129176           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
129177           if( nDoclist+nByte>pCsr->nBuffer ){
129178             char *aNew;
129179             pCsr->nBuffer = (nDoclist+nByte)*2;
129180             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
129181             if( !aNew ){
129182               return SQLITE_NOMEM;
129183             }
129184             pCsr->aBuffer = aNew;
129185           }
129186
129187           if( isFirst ){
129188             char *a = &pCsr->aBuffer[nDoclist];
129189             int nWrite;
129190            
129191             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
129192             if( nWrite ){
129193               iPrev = iDocid;
129194               nDoclist += nWrite;
129195             }
129196           }else{
129197             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
129198             iPrev = iDocid;
129199             if( isRequirePos ){
129200               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
129201               nDoclist += nList;
129202               pCsr->aBuffer[nDoclist++] = '\0';
129203             }
129204           }
129205         }
129206
129207         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
129208       }
129209       if( nDoclist>0 ){
129210         pCsr->aDoclist = pCsr->aBuffer;
129211         pCsr->nDoclist = nDoclist;
129212         rc = SQLITE_ROW;
129213       }
129214     }
129215     pCsr->nAdvance = nMerge;
129216   }while( rc==SQLITE_OK );
129217
129218   return rc;
129219 }
129220
129221
129222 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
129223   Fts3MultiSegReader *pCsr       /* Cursor object */
129224 ){
129225   if( pCsr ){
129226     int i;
129227     for(i=0; i<pCsr->nSegment; i++){
129228       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
129229     }
129230     sqlite3_free(pCsr->apSegment);
129231     sqlite3_free(pCsr->aBuffer);
129232
129233     pCsr->nSegment = 0;
129234     pCsr->apSegment = 0;
129235     pCsr->aBuffer = 0;
129236   }
129237 }
129238
129239 /*
129240 ** Merge all level iLevel segments in the database into a single 
129241 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
129242 ** single segment with a level equal to the numerically largest level 
129243 ** currently present in the database.
129244 **
129245 ** If this function is called with iLevel<0, but there is only one
129246 ** segment in the database, SQLITE_DONE is returned immediately. 
129247 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
129248 ** an SQLite error code is returned.
129249 */
129250 static int fts3SegmentMerge(
129251   Fts3Table *p, 
129252   int iLangid,                    /* Language id to merge */
129253   int iIndex,                     /* Index in p->aIndex[] to merge */
129254   int iLevel                      /* Level to merge */
129255 ){
129256   int rc;                         /* Return code */
129257   int iIdx = 0;                   /* Index of new segment */
129258   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
129259   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
129260   Fts3SegFilter filter;           /* Segment term filter condition */
129261   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
129262   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
129263
129264   assert( iLevel==FTS3_SEGCURSOR_ALL
129265        || iLevel==FTS3_SEGCURSOR_PENDING
129266        || iLevel>=0
129267   );
129268   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
129269   assert( iIndex>=0 && iIndex<p->nIndex );
129270
129271   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
129272   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
129273
129274   if( iLevel==FTS3_SEGCURSOR_ALL ){
129275     /* This call is to merge all segments in the database to a single
129276     ** segment. The level of the new segment is equal to the numerically
129277     ** greatest segment level currently present in the database for this
129278     ** index. The idx of the new segment is always 0.  */
129279     if( csr.nSegment==1 ){
129280       rc = SQLITE_DONE;
129281       goto finished;
129282     }
129283     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
129284     bIgnoreEmpty = 1;
129285
129286   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
129287     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
129288     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
129289   }else{
129290     /* This call is to merge all segments at level iLevel. find the next
129291     ** available segment index at level iLevel+1. The call to
129292     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
129293     ** a single iLevel+2 segment if necessary.  */
129294     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
129295     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
129296   }
129297   if( rc!=SQLITE_OK ) goto finished;
129298   assert( csr.nSegment>0 );
129299   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
129300   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
129301
129302   memset(&filter, 0, sizeof(Fts3SegFilter));
129303   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
129304   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
129305
129306   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
129307   while( SQLITE_OK==rc ){
129308     rc = sqlite3Fts3SegReaderStep(p, &csr);
129309     if( rc!=SQLITE_ROW ) break;
129310     rc = fts3SegWriterAdd(p, &pWriter, 1, 
129311         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
129312   }
129313   if( rc!=SQLITE_OK ) goto finished;
129314   assert( pWriter );
129315
129316   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
129317     rc = fts3DeleteSegdir(
129318         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
129319     );
129320     if( rc!=SQLITE_OK ) goto finished;
129321   }
129322   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
129323
129324  finished:
129325   fts3SegWriterFree(pWriter);
129326   sqlite3Fts3SegReaderFinish(&csr);
129327   return rc;
129328 }
129329
129330
129331 /* 
129332 ** Flush the contents of pendingTerms to level 0 segments.
129333 */
129334 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
129335   int rc = SQLITE_OK;
129336   int i;
129337         
129338   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
129339     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
129340     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
129341   }
129342   sqlite3Fts3PendingTermsClear(p);
129343
129344   /* Determine the auto-incr-merge setting if unknown.  If enabled,
129345   ** estimate the number of leaf blocks of content to be written
129346   */
129347   if( rc==SQLITE_OK && p->bHasStat
129348    && p->bAutoincrmerge==0xff && p->nLeafAdd>0
129349   ){
129350     sqlite3_stmt *pStmt = 0;
129351     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
129352     if( rc==SQLITE_OK ){
129353       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
129354       rc = sqlite3_step(pStmt);
129355       p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
129356       rc = sqlite3_reset(pStmt);
129357     }
129358   }
129359   return rc;
129360 }
129361
129362 /*
129363 ** Encode N integers as varints into a blob.
129364 */
129365 static void fts3EncodeIntArray(
129366   int N,             /* The number of integers to encode */
129367   u32 *a,            /* The integer values */
129368   char *zBuf,        /* Write the BLOB here */
129369   int *pNBuf         /* Write number of bytes if zBuf[] used here */
129370 ){
129371   int i, j;
129372   for(i=j=0; i<N; i++){
129373     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
129374   }
129375   *pNBuf = j;
129376 }
129377
129378 /*
129379 ** Decode a blob of varints into N integers
129380 */
129381 static void fts3DecodeIntArray(
129382   int N,             /* The number of integers to decode */
129383   u32 *a,            /* Write the integer values */
129384   const char *zBuf,  /* The BLOB containing the varints */
129385   int nBuf           /* size of the BLOB */
129386 ){
129387   int i, j;
129388   UNUSED_PARAMETER(nBuf);
129389   for(i=j=0; i<N; i++){
129390     sqlite3_int64 x;
129391     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
129392     assert(j<=nBuf);
129393     a[i] = (u32)(x & 0xffffffff);
129394   }
129395 }
129396
129397 /*
129398 ** Insert the sizes (in tokens) for each column of the document
129399 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
129400 ** a blob of varints.
129401 */
129402 static void fts3InsertDocsize(
129403   int *pRC,                       /* Result code */
129404   Fts3Table *p,                   /* Table into which to insert */
129405   u32 *aSz                        /* Sizes of each column, in tokens */
129406 ){
129407   char *pBlob;             /* The BLOB encoding of the document size */
129408   int nBlob;               /* Number of bytes in the BLOB */
129409   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
129410   int rc;                  /* Result code from subfunctions */
129411
129412   if( *pRC ) return;
129413   pBlob = sqlite3_malloc( 10*p->nColumn );
129414   if( pBlob==0 ){
129415     *pRC = SQLITE_NOMEM;
129416     return;
129417   }
129418   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
129419   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
129420   if( rc ){
129421     sqlite3_free(pBlob);
129422     *pRC = rc;
129423     return;
129424   }
129425   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
129426   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
129427   sqlite3_step(pStmt);
129428   *pRC = sqlite3_reset(pStmt);
129429 }
129430
129431 /*
129432 ** Record 0 of the %_stat table contains a blob consisting of N varints,
129433 ** where N is the number of user defined columns in the fts3 table plus
129434 ** two. If nCol is the number of user defined columns, then values of the 
129435 ** varints are set as follows:
129436 **
129437 **   Varint 0:       Total number of rows in the table.
129438 **
129439 **   Varint 1..nCol: For each column, the total number of tokens stored in
129440 **                   the column for all rows of the table.
129441 **
129442 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
129443 **                   columns of all rows of the table.
129444 **
129445 */
129446 static void fts3UpdateDocTotals(
129447   int *pRC,                       /* The result code */
129448   Fts3Table *p,                   /* Table being updated */
129449   u32 *aSzIns,                    /* Size increases */
129450   u32 *aSzDel,                    /* Size decreases */
129451   int nChng                       /* Change in the number of documents */
129452 ){
129453   char *pBlob;             /* Storage for BLOB written into %_stat */
129454   int nBlob;               /* Size of BLOB written into %_stat */
129455   u32 *a;                  /* Array of integers that becomes the BLOB */
129456   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
129457   int i;                   /* Loop counter */
129458   int rc;                  /* Result code from subfunctions */
129459
129460   const int nStat = p->nColumn+2;
129461
129462   if( *pRC ) return;
129463   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
129464   if( a==0 ){
129465     *pRC = SQLITE_NOMEM;
129466     return;
129467   }
129468   pBlob = (char*)&a[nStat];
129469   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
129470   if( rc ){
129471     sqlite3_free(a);
129472     *pRC = rc;
129473     return;
129474   }
129475   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
129476   if( sqlite3_step(pStmt)==SQLITE_ROW ){
129477     fts3DecodeIntArray(nStat, a,
129478          sqlite3_column_blob(pStmt, 0),
129479          sqlite3_column_bytes(pStmt, 0));
129480   }else{
129481     memset(a, 0, sizeof(u32)*(nStat) );
129482   }
129483   rc = sqlite3_reset(pStmt);
129484   if( rc!=SQLITE_OK ){
129485     sqlite3_free(a);
129486     *pRC = rc;
129487     return;
129488   }
129489   if( nChng<0 && a[0]<(u32)(-nChng) ){
129490     a[0] = 0;
129491   }else{
129492     a[0] += nChng;
129493   }
129494   for(i=0; i<p->nColumn+1; i++){
129495     u32 x = a[i+1];
129496     if( x+aSzIns[i] < aSzDel[i] ){
129497       x = 0;
129498     }else{
129499       x = x + aSzIns[i] - aSzDel[i];
129500     }
129501     a[i+1] = x;
129502   }
129503   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
129504   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
129505   if( rc ){
129506     sqlite3_free(a);
129507     *pRC = rc;
129508     return;
129509   }
129510   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
129511   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
129512   sqlite3_step(pStmt);
129513   *pRC = sqlite3_reset(pStmt);
129514   sqlite3_free(a);
129515 }
129516
129517 /*
129518 ** Merge the entire database so that there is one segment for each 
129519 ** iIndex/iLangid combination.
129520 */
129521 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
129522   int bSeenDone = 0;
129523   int rc;
129524   sqlite3_stmt *pAllLangid = 0;
129525
129526   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
129527   if( rc==SQLITE_OK ){
129528     int rc2;
129529     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
129530     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
129531       int i;
129532       int iLangid = sqlite3_column_int(pAllLangid, 0);
129533       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
129534         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
129535         if( rc==SQLITE_DONE ){
129536           bSeenDone = 1;
129537           rc = SQLITE_OK;
129538         }
129539       }
129540     }
129541     rc2 = sqlite3_reset(pAllLangid);
129542     if( rc==SQLITE_OK ) rc = rc2;
129543   }
129544
129545   sqlite3Fts3SegmentsClose(p);
129546   sqlite3Fts3PendingTermsClear(p);
129547
129548   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
129549 }
129550
129551 /*
129552 ** This function is called when the user executes the following statement:
129553 **
129554 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
129555 **
129556 ** The entire FTS index is discarded and rebuilt. If the table is one 
129557 ** created using the content=xxx option, then the new index is based on
129558 ** the current contents of the xxx table. Otherwise, it is rebuilt based
129559 ** on the contents of the %_content table.
129560 */
129561 static int fts3DoRebuild(Fts3Table *p){
129562   int rc;                         /* Return Code */
129563
129564   rc = fts3DeleteAll(p, 0);
129565   if( rc==SQLITE_OK ){
129566     u32 *aSz = 0;
129567     u32 *aSzIns = 0;
129568     u32 *aSzDel = 0;
129569     sqlite3_stmt *pStmt = 0;
129570     int nEntry = 0;
129571
129572     /* Compose and prepare an SQL statement to loop through the content table */
129573     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
129574     if( !zSql ){
129575       rc = SQLITE_NOMEM;
129576     }else{
129577       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
129578       sqlite3_free(zSql);
129579     }
129580
129581     if( rc==SQLITE_OK ){
129582       int nByte = sizeof(u32) * (p->nColumn+1)*3;
129583       aSz = (u32 *)sqlite3_malloc(nByte);
129584       if( aSz==0 ){
129585         rc = SQLITE_NOMEM;
129586       }else{
129587         memset(aSz, 0, nByte);
129588         aSzIns = &aSz[p->nColumn+1];
129589         aSzDel = &aSzIns[p->nColumn+1];
129590       }
129591     }
129592
129593     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
129594       int iCol;
129595       int iLangid = langidFromSelect(p, pStmt);
129596       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
129597       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
129598       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
129599         const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
129600         rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
129601         aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
129602       }
129603       if( p->bHasDocsize ){
129604         fts3InsertDocsize(&rc, p, aSz);
129605       }
129606       if( rc!=SQLITE_OK ){
129607         sqlite3_finalize(pStmt);
129608         pStmt = 0;
129609       }else{
129610         nEntry++;
129611         for(iCol=0; iCol<=p->nColumn; iCol++){
129612           aSzIns[iCol] += aSz[iCol];
129613         }
129614       }
129615     }
129616     if( p->bFts4 ){
129617       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
129618     }
129619     sqlite3_free(aSz);
129620
129621     if( pStmt ){
129622       int rc2 = sqlite3_finalize(pStmt);
129623       if( rc==SQLITE_OK ){
129624         rc = rc2;
129625       }
129626     }
129627   }
129628
129629   return rc;
129630 }
129631
129632
129633 /*
129634 ** This function opens a cursor used to read the input data for an 
129635 ** incremental merge operation. Specifically, it opens a cursor to scan
129636 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute 
129637 ** level iAbsLevel.
129638 */
129639 static int fts3IncrmergeCsr(
129640   Fts3Table *p,                   /* FTS3 table handle */
129641   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
129642   int nSeg,                       /* Number of segments to merge */
129643   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
129644 ){
129645   int rc;                         /* Return Code */
129646   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  
129647   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
129648
129649   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
129650   memset(pCsr, 0, sizeof(*pCsr));
129651   nByte = sizeof(Fts3SegReader *) * nSeg;
129652   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
129653
129654   if( pCsr->apSegment==0 ){
129655     rc = SQLITE_NOMEM;
129656   }else{
129657     memset(pCsr->apSegment, 0, nByte);
129658     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
129659   }
129660   if( rc==SQLITE_OK ){
129661     int i;
129662     int rc2;
129663     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
129664     assert( pCsr->nSegment==0 );
129665     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
129666       rc = sqlite3Fts3SegReaderNew(i, 0,
129667           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
129668           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
129669           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
129670           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
129671           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
129672           &pCsr->apSegment[i]
129673       );
129674       pCsr->nSegment++;
129675     }
129676     rc2 = sqlite3_reset(pStmt);
129677     if( rc==SQLITE_OK ) rc = rc2;
129678   }
129679
129680   return rc;
129681 }
129682
129683 typedef struct IncrmergeWriter IncrmergeWriter;
129684 typedef struct NodeWriter NodeWriter;
129685 typedef struct Blob Blob;
129686 typedef struct NodeReader NodeReader;
129687
129688 /*
129689 ** An instance of the following structure is used as a dynamic buffer
129690 ** to build up nodes or other blobs of data in.
129691 **
129692 ** The function blobGrowBuffer() is used to extend the allocation.
129693 */
129694 struct Blob {
129695   char *a;                        /* Pointer to allocation */
129696   int n;                          /* Number of valid bytes of data in a[] */
129697   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
129698 };
129699
129700 /*
129701 ** This structure is used to build up buffers containing segment b-tree 
129702 ** nodes (blocks).
129703 */
129704 struct NodeWriter {
129705   sqlite3_int64 iBlock;           /* Current block id */
129706   Blob key;                       /* Last key written to the current block */
129707   Blob block;                     /* Current block image */
129708 };
129709
129710 /*
129711 ** An object of this type contains the state required to create or append
129712 ** to an appendable b-tree segment.
129713 */
129714 struct IncrmergeWriter {
129715   int nLeafEst;                   /* Space allocated for leaf blocks */
129716   int nWork;                      /* Number of leaf pages flushed */
129717   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
129718   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
129719   sqlite3_int64 iStart;           /* Block number of first allocated block */
129720   sqlite3_int64 iEnd;             /* Block number of last allocated block */
129721   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
129722 };
129723
129724 /*
129725 ** An object of the following type is used to read data from a single
129726 ** FTS segment node. See the following functions:
129727 **
129728 **     nodeReaderInit()
129729 **     nodeReaderNext()
129730 **     nodeReaderRelease()
129731 */
129732 struct NodeReader {
129733   const char *aNode;
129734   int nNode;
129735   int iOff;                       /* Current offset within aNode[] */
129736
129737   /* Output variables. Containing the current node entry. */
129738   sqlite3_int64 iChild;           /* Pointer to child node */
129739   Blob term;                      /* Current term */
129740   const char *aDoclist;           /* Pointer to doclist */
129741   int nDoclist;                   /* Size of doclist in bytes */
129742 };
129743
129744 /*
129745 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
129746 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
129747 ** bytes in size, extend (realloc) it to be so.
129748 **
129749 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
129750 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
129751 ** to reflect the new size of the pBlob->a[] buffer.
129752 */
129753 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
129754   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
129755     int nAlloc = nMin;
129756     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
129757     if( a ){
129758       pBlob->nAlloc = nAlloc;
129759       pBlob->a = a;
129760     }else{
129761       *pRc = SQLITE_NOMEM;
129762     }
129763   }
129764 }
129765
129766 /*
129767 ** Attempt to advance the node-reader object passed as the first argument to
129768 ** the next entry on the node. 
129769 **
129770 ** Return an error code if an error occurs (SQLITE_NOMEM is possible). 
129771 ** Otherwise return SQLITE_OK. If there is no next entry on the node
129772 ** (e.g. because the current entry is the last) set NodeReader->aNode to
129773 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output 
129774 ** variables for the new entry.
129775 */
129776 static int nodeReaderNext(NodeReader *p){
129777   int bFirst = (p->term.n==0);    /* True for first term on the node */
129778   int nPrefix = 0;                /* Bytes to copy from previous term */
129779   int nSuffix = 0;                /* Bytes to append to the prefix */
129780   int rc = SQLITE_OK;             /* Return code */
129781
129782   assert( p->aNode );
129783   if( p->iChild && bFirst==0 ) p->iChild++;
129784   if( p->iOff>=p->nNode ){
129785     /* EOF */
129786     p->aNode = 0;
129787   }else{
129788     if( bFirst==0 ){
129789       p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
129790     }
129791     p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
129792
129793     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
129794     if( rc==SQLITE_OK ){
129795       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
129796       p->term.n = nPrefix+nSuffix;
129797       p->iOff += nSuffix;
129798       if( p->iChild==0 ){
129799         p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
129800         p->aDoclist = &p->aNode[p->iOff];
129801         p->iOff += p->nDoclist;
129802       }
129803     }
129804   }
129805
129806   assert( p->iOff<=p->nNode );
129807
129808   return rc;
129809 }
129810
129811 /*
129812 ** Release all dynamic resources held by node-reader object *p.
129813 */
129814 static void nodeReaderRelease(NodeReader *p){
129815   sqlite3_free(p->term.a);
129816 }
129817
129818 /*
129819 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
129820 **
129821 ** If successful, SQLITE_OK is returned and the NodeReader object set to 
129822 ** point to the first entry on the node (if any). Otherwise, an SQLite
129823 ** error code is returned.
129824 */
129825 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
129826   memset(p, 0, sizeof(NodeReader));
129827   p->aNode = aNode;
129828   p->nNode = nNode;
129829
129830   /* Figure out if this is a leaf or an internal node. */
129831   if( p->aNode[0] ){
129832     /* An internal node. */
129833     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
129834   }else{
129835     p->iOff = 1;
129836   }
129837
129838   return nodeReaderNext(p);
129839 }
129840
129841 /*
129842 ** This function is called while writing an FTS segment each time a leaf o
129843 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
129844 ** to be greater than the largest key on the node just written, but smaller
129845 ** than or equal to the first key that will be written to the next leaf
129846 ** node.
129847 **
129848 ** The block id of the leaf node just written to disk may be found in
129849 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
129850 */
129851 static int fts3IncrmergePush(
129852   Fts3Table *p,                   /* Fts3 table handle */
129853   IncrmergeWriter *pWriter,       /* Writer object */
129854   const char *zTerm,              /* Term to write to internal node */
129855   int nTerm                       /* Bytes at zTerm */
129856 ){
129857   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
129858   int iLayer;
129859
129860   assert( nTerm>0 );
129861   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
129862     sqlite3_int64 iNextPtr = 0;
129863     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
129864     int rc = SQLITE_OK;
129865     int nPrefix;
129866     int nSuffix;
129867     int nSpace;
129868
129869     /* Figure out how much space the key will consume if it is written to
129870     ** the current node of layer iLayer. Due to the prefix compression, 
129871     ** the space required changes depending on which node the key is to
129872     ** be added to.  */
129873     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
129874     nSuffix = nTerm - nPrefix;
129875     nSpace  = sqlite3Fts3VarintLen(nPrefix);
129876     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
129877
129878     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ 
129879       /* If the current node of layer iLayer contains zero keys, or if adding
129880       ** the key to it will not cause it to grow to larger than nNodeSize 
129881       ** bytes in size, write the key here.  */
129882
129883       Blob *pBlk = &pNode->block;
129884       if( pBlk->n==0 ){
129885         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
129886         if( rc==SQLITE_OK ){
129887           pBlk->a[0] = (char)iLayer;
129888           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
129889         }
129890       }
129891       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
129892       blobGrowBuffer(&pNode->key, nTerm, &rc);
129893
129894       if( rc==SQLITE_OK ){
129895         if( pNode->key.n ){
129896           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
129897         }
129898         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
129899         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
129900         pBlk->n += nSuffix;
129901
129902         memcpy(pNode->key.a, zTerm, nTerm);
129903         pNode->key.n = nTerm;
129904       }
129905     }else{
129906       /* Otherwise, flush the current node of layer iLayer to disk.
129907       ** Then allocate a new, empty sibling node. The key will be written
129908       ** into the parent of this node. */
129909       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
129910
129911       assert( pNode->block.nAlloc>=p->nNodeSize );
129912       pNode->block.a[0] = (char)iLayer;
129913       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
129914
129915       iNextPtr = pNode->iBlock;
129916       pNode->iBlock++;
129917       pNode->key.n = 0;
129918     }
129919
129920     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
129921     iPtr = iNextPtr;
129922   }
129923
129924   assert( 0 );
129925   return 0;
129926 }
129927
129928 /*
129929 ** Append a term and (optionally) doclist to the FTS segment node currently
129930 ** stored in blob *pNode. The node need not contain any terms, but the
129931 ** header must be written before this function is called.
129932 **
129933 ** A node header is a single 0x00 byte for a leaf node, or a height varint
129934 ** followed by the left-hand-child varint for an internal node.
129935 **
129936 ** The term to be appended is passed via arguments zTerm/nTerm. For a 
129937 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
129938 ** node, both aDoclist and nDoclist must be passed 0.
129939 **
129940 ** If the size of the value in blob pPrev is zero, then this is the first
129941 ** term written to the node. Otherwise, pPrev contains a copy of the 
129942 ** previous term. Before this function returns, it is updated to contain a
129943 ** copy of zTerm/nTerm.
129944 **
129945 ** It is assumed that the buffer associated with pNode is already large
129946 ** enough to accommodate the new entry. The buffer associated with pPrev
129947 ** is extended by this function if requrired.
129948 **
129949 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
129950 ** returned. Otherwise, SQLITE_OK.
129951 */
129952 static int fts3AppendToNode(
129953   Blob *pNode,                    /* Current node image to append to */
129954   Blob *pPrev,                    /* Buffer containing previous term written */
129955   const char *zTerm,              /* New term to write */
129956   int nTerm,                      /* Size of zTerm in bytes */
129957   const char *aDoclist,           /* Doclist (or NULL) to write */
129958   int nDoclist                    /* Size of aDoclist in bytes */ 
129959 ){
129960   int rc = SQLITE_OK;             /* Return code */
129961   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
129962   int nPrefix;                    /* Size of term prefix in bytes */
129963   int nSuffix;                    /* Size of term suffix in bytes */
129964
129965   /* Node must have already been started. There must be a doclist for a
129966   ** leaf node, and there must not be a doclist for an internal node.  */
129967   assert( pNode->n>0 );
129968   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
129969
129970   blobGrowBuffer(pPrev, nTerm, &rc);
129971   if( rc!=SQLITE_OK ) return rc;
129972
129973   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
129974   nSuffix = nTerm - nPrefix;
129975   memcpy(pPrev->a, zTerm, nTerm);
129976   pPrev->n = nTerm;
129977
129978   if( bFirst==0 ){
129979     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
129980   }
129981   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
129982   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
129983   pNode->n += nSuffix;
129984
129985   if( aDoclist ){
129986     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
129987     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
129988     pNode->n += nDoclist;
129989   }
129990
129991   assert( pNode->n<=pNode->nAlloc );
129992
129993   return SQLITE_OK;
129994 }
129995
129996 /*
129997 ** Append the current term and doclist pointed to by cursor pCsr to the
129998 ** appendable b-tree segment opened for writing by pWriter.
129999 **
130000 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
130001 */
130002 static int fts3IncrmergeAppend(
130003   Fts3Table *p,                   /* Fts3 table handle */
130004   IncrmergeWriter *pWriter,       /* Writer object */
130005   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
130006 ){
130007   const char *zTerm = pCsr->zTerm;
130008   int nTerm = pCsr->nTerm;
130009   const char *aDoclist = pCsr->aDoclist;
130010   int nDoclist = pCsr->nDoclist;
130011   int rc = SQLITE_OK;           /* Return code */
130012   int nSpace;                   /* Total space in bytes required on leaf */
130013   int nPrefix;                  /* Size of prefix shared with previous term */
130014   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
130015   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
130016
130017   pLeaf = &pWriter->aNodeWriter[0];
130018   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
130019   nSuffix = nTerm - nPrefix;
130020
130021   nSpace  = sqlite3Fts3VarintLen(nPrefix);
130022   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
130023   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
130024
130025   /* If the current block is not empty, and if adding this term/doclist
130026   ** to the current block would make it larger than Fts3Table.nNodeSize
130027   ** bytes, write this block out to the database. */
130028   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
130029     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
130030     pWriter->nWork++;
130031
130032     /* Add the current term to the parent node. The term added to the 
130033     ** parent must:
130034     **
130035     **   a) be greater than the largest term on the leaf node just written
130036     **      to the database (still available in pLeaf->key), and
130037     **
130038     **   b) be less than or equal to the term about to be added to the new
130039     **      leaf node (zTerm/nTerm).
130040     **
130041     ** In other words, it must be the prefix of zTerm 1 byte longer than
130042     ** the common prefix (if any) of zTerm and pWriter->zTerm.
130043     */
130044     if( rc==SQLITE_OK ){
130045       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
130046     }
130047
130048     /* Advance to the next output block */
130049     pLeaf->iBlock++;
130050     pLeaf->key.n = 0;
130051     pLeaf->block.n = 0;
130052
130053     nSuffix = nTerm;
130054     nSpace  = 1;
130055     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
130056     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
130057   }
130058
130059   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
130060
130061   if( rc==SQLITE_OK ){
130062     if( pLeaf->block.n==0 ){
130063       pLeaf->block.n = 1;
130064       pLeaf->block.a[0] = '\0';
130065     }
130066     rc = fts3AppendToNode(
130067         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
130068     );
130069   }
130070
130071   return rc;
130072 }
130073
130074 /*
130075 ** This function is called to release all dynamic resources held by the
130076 ** merge-writer object pWriter, and if no error has occurred, to flush
130077 ** all outstanding node buffers held by pWriter to disk.
130078 **
130079 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
130080 ** is made to write any data to disk. Instead, this function serves only
130081 ** to release outstanding resources.
130082 **
130083 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
130084 ** flushing buffers to disk, *pRc is set to an SQLite error code before
130085 ** returning.
130086 */
130087 static void fts3IncrmergeRelease(
130088   Fts3Table *p,                   /* FTS3 table handle */
130089   IncrmergeWriter *pWriter,       /* Merge-writer object */
130090   int *pRc                        /* IN/OUT: Error code */
130091 ){
130092   int i;                          /* Used to iterate through non-root layers */
130093   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
130094   NodeWriter *pRoot;              /* NodeWriter for root node */
130095   int rc = *pRc;                  /* Error code */
130096
130097   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment 
130098   ** root node. If the segment fits entirely on a single leaf node, iRoot
130099   ** will be set to 0. If the root node is the parent of the leaves, iRoot
130100   ** will be 1. And so on.  */
130101   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
130102     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
130103     if( pNode->block.n>0 ) break;
130104     assert( *pRc || pNode->block.nAlloc==0 );
130105     assert( *pRc || pNode->key.nAlloc==0 );
130106     sqlite3_free(pNode->block.a);
130107     sqlite3_free(pNode->key.a);
130108   }
130109
130110   /* Empty output segment. This is a no-op. */
130111   if( iRoot<0 ) return;
130112
130113   /* The entire output segment fits on a single node. Normally, this means
130114   ** the node would be stored as a blob in the "root" column of the %_segdir
130115   ** table. However, this is not permitted in this case. The problem is that 
130116   ** space has already been reserved in the %_segments table, and so the 
130117   ** start_block and end_block fields of the %_segdir table must be populated. 
130118   ** And, by design or by accident, released versions of FTS cannot handle 
130119   ** segments that fit entirely on the root node with start_block!=0.
130120   **
130121   ** Instead, create a synthetic root node that contains nothing but a 
130122   ** pointer to the single content node. So that the segment consists of a
130123   ** single leaf and a single interior (root) node.
130124   **
130125   ** Todo: Better might be to defer allocating space in the %_segments 
130126   ** table until we are sure it is needed.
130127   */
130128   if( iRoot==0 ){
130129     Blob *pBlock = &pWriter->aNodeWriter[1].block;
130130     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
130131     if( rc==SQLITE_OK ){
130132       pBlock->a[0] = 0x01;
130133       pBlock->n = 1 + sqlite3Fts3PutVarint(
130134           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
130135       );
130136     }
130137     iRoot = 1;
130138   }
130139   pRoot = &pWriter->aNodeWriter[iRoot];
130140
130141   /* Flush all currently outstanding nodes to disk. */
130142   for(i=0; i<iRoot; i++){
130143     NodeWriter *pNode = &pWriter->aNodeWriter[i];
130144     if( pNode->block.n>0 && rc==SQLITE_OK ){
130145       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
130146     }
130147     sqlite3_free(pNode->block.a);
130148     sqlite3_free(pNode->key.a);
130149   }
130150
130151   /* Write the %_segdir record. */
130152   if( rc==SQLITE_OK ){
130153     rc = fts3WriteSegdir(p, 
130154         pWriter->iAbsLevel+1,               /* level */
130155         pWriter->iIdx,                      /* idx */
130156         pWriter->iStart,                    /* start_block */
130157         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
130158         pWriter->iEnd,                      /* end_block */
130159         pRoot->block.a, pRoot->block.n      /* root */
130160     );
130161   }
130162   sqlite3_free(pRoot->block.a);
130163   sqlite3_free(pRoot->key.a);
130164
130165   *pRc = rc;
130166 }
130167
130168 /*
130169 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
130170 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
130171 ** the other, it is considered to be smaller than the other.
130172 **
130173 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
130174 ** if it is greater.
130175 */
130176 static int fts3TermCmp(
130177   const char *zLhs, int nLhs,     /* LHS of comparison */
130178   const char *zRhs, int nRhs      /* RHS of comparison */
130179 ){
130180   int nCmp = MIN(nLhs, nRhs);
130181   int res;
130182
130183   res = memcmp(zLhs, zRhs, nCmp);
130184   if( res==0 ) res = nLhs - nRhs;
130185
130186   return res;
130187 }
130188
130189
130190 /*
130191 ** Query to see if the entry in the %_segments table with blockid iEnd is 
130192 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
130193 ** returning. Otherwise, set *pbRes to 0. 
130194 **
130195 ** Or, if an error occurs while querying the database, return an SQLite 
130196 ** error code. The final value of *pbRes is undefined in this case.
130197 **
130198 ** This is used to test if a segment is an "appendable" segment. If it
130199 ** is, then a NULL entry has been inserted into the %_segments table
130200 ** with blockid %_segdir.end_block.
130201 */
130202 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
130203   int bRes = 0;                   /* Result to set *pbRes to */
130204   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
130205   int rc;                         /* Return code */
130206
130207   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
130208   if( rc==SQLITE_OK ){
130209     sqlite3_bind_int64(pCheck, 1, iEnd);
130210     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
130211     rc = sqlite3_reset(pCheck);
130212   }
130213   
130214   *pbRes = bRes;
130215   return rc;
130216 }
130217
130218 /*
130219 ** This function is called when initializing an incremental-merge operation.
130220 ** It checks if the existing segment with index value iIdx at absolute level 
130221 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
130222 ** merge-writer object *pWriter is initialized to write to it.
130223 **
130224 ** An existing segment can be appended to by an incremental merge if:
130225 **
130226 **   * It was initially created as an appendable segment (with all required
130227 **     space pre-allocated), and
130228 **
130229 **   * The first key read from the input (arguments zKey and nKey) is 
130230 **     greater than the largest key currently stored in the potential
130231 **     output segment.
130232 */
130233 static int fts3IncrmergeLoad(
130234   Fts3Table *p,                   /* Fts3 table handle */
130235   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
130236   int iIdx,                       /* Index of candidate output segment */
130237   const char *zKey,               /* First key to write */
130238   int nKey,                       /* Number of bytes in nKey */
130239   IncrmergeWriter *pWriter        /* Populate this object */
130240 ){
130241   int rc;                         /* Return code */
130242   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
130243
130244   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
130245   if( rc==SQLITE_OK ){
130246     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
130247     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
130248     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
130249     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
130250     int nRoot = 0;                /* Size of aRoot[] in bytes */
130251     int rc2;                      /* Return code from sqlite3_reset() */
130252     int bAppendable = 0;          /* Set to true if segment is appendable */
130253
130254     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
130255     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
130256     sqlite3_bind_int(pSelect, 2, iIdx);
130257     if( sqlite3_step(pSelect)==SQLITE_ROW ){
130258       iStart = sqlite3_column_int64(pSelect, 1);
130259       iLeafEnd = sqlite3_column_int64(pSelect, 2);
130260       iEnd = sqlite3_column_int64(pSelect, 3);
130261       nRoot = sqlite3_column_bytes(pSelect, 4);
130262       aRoot = sqlite3_column_blob(pSelect, 4);
130263     }else{
130264       return sqlite3_reset(pSelect);
130265     }
130266
130267     /* Check for the zero-length marker in the %_segments table */
130268     rc = fts3IsAppendable(p, iEnd, &bAppendable);
130269
130270     /* Check that zKey/nKey is larger than the largest key the candidate */
130271     if( rc==SQLITE_OK && bAppendable ){
130272       char *aLeaf = 0;
130273       int nLeaf = 0;
130274
130275       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
130276       if( rc==SQLITE_OK ){
130277         NodeReader reader;
130278         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
130279             rc==SQLITE_OK && reader.aNode;
130280             rc = nodeReaderNext(&reader)
130281         ){
130282           assert( reader.aNode );
130283         }
130284         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
130285           bAppendable = 0;
130286         }
130287         nodeReaderRelease(&reader);
130288       }
130289       sqlite3_free(aLeaf);
130290     }
130291
130292     if( rc==SQLITE_OK && bAppendable ){
130293       /* It is possible to append to this segment. Set up the IncrmergeWriter
130294       ** object to do so.  */
130295       int i;
130296       int nHeight = (int)aRoot[0];
130297       NodeWriter *pNode;
130298
130299       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
130300       pWriter->iStart = iStart;
130301       pWriter->iEnd = iEnd;
130302       pWriter->iAbsLevel = iAbsLevel;
130303       pWriter->iIdx = iIdx;
130304
130305       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
130306         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
130307       }
130308
130309       pNode = &pWriter->aNodeWriter[nHeight];
130310       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
130311       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
130312       if( rc==SQLITE_OK ){
130313         memcpy(pNode->block.a, aRoot, nRoot);
130314         pNode->block.n = nRoot;
130315       }
130316
130317       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
130318         NodeReader reader;
130319         pNode = &pWriter->aNodeWriter[i];
130320
130321         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
130322         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
130323         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
130324         if( rc==SQLITE_OK ){
130325           memcpy(pNode->key.a, reader.term.a, reader.term.n);
130326           pNode->key.n = reader.term.n;
130327           if( i>0 ){
130328             char *aBlock = 0;
130329             int nBlock = 0;
130330             pNode = &pWriter->aNodeWriter[i-1];
130331             pNode->iBlock = reader.iChild;
130332             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
130333             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
130334             if( rc==SQLITE_OK ){
130335               memcpy(pNode->block.a, aBlock, nBlock);
130336               pNode->block.n = nBlock;
130337             }
130338             sqlite3_free(aBlock);
130339           }
130340         }
130341         nodeReaderRelease(&reader);
130342       }
130343     }
130344
130345     rc2 = sqlite3_reset(pSelect);
130346     if( rc==SQLITE_OK ) rc = rc2;
130347   }
130348
130349   return rc;
130350 }
130351
130352 /*
130353 ** Determine the largest segment index value that exists within absolute
130354 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
130355 ** one before returning SQLITE_OK. Or, if there are no segments at all 
130356 ** within level iAbsLevel, set *piIdx to zero.
130357 **
130358 ** If an error occurs, return an SQLite error code. The final value of
130359 ** *piIdx is undefined in this case.
130360 */
130361 static int fts3IncrmergeOutputIdx( 
130362   Fts3Table *p,                   /* FTS Table handle */
130363   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
130364   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
130365 ){
130366   int rc;
130367   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
130368
130369   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
130370   if( rc==SQLITE_OK ){
130371     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
130372     sqlite3_step(pOutputIdx);
130373     *piIdx = sqlite3_column_int(pOutputIdx, 0);
130374     rc = sqlite3_reset(pOutputIdx);
130375   }
130376
130377   return rc;
130378 }
130379
130380 /* 
130381 ** Allocate an appendable output segment on absolute level iAbsLevel+1
130382 ** with idx value iIdx.
130383 **
130384 ** In the %_segdir table, a segment is defined by the values in three
130385 ** columns:
130386 **
130387 **     start_block
130388 **     leaves_end_block
130389 **     end_block
130390 **
130391 ** When an appendable segment is allocated, it is estimated that the
130392 ** maximum number of leaf blocks that may be required is the sum of the
130393 ** number of leaf blocks consumed by the input segments, plus the number
130394 ** of input segments, multiplied by two. This value is stored in stack 
130395 ** variable nLeafEst.
130396 **
130397 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
130398 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
130399 ** array of leaf nodes starts at the first block allocated. The array
130400 ** of interior nodes that are parents of the leaf nodes start at block
130401 ** (start_block + (1 + end_block - start_block) / 16). And so on.
130402 **
130403 ** In the actual code below, the value "16" is replaced with the 
130404 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
130405 */
130406 static int fts3IncrmergeWriter( 
130407   Fts3Table *p,                   /* Fts3 table handle */
130408   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
130409   int iIdx,                       /* Index of new output segment */
130410   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
130411   IncrmergeWriter *pWriter        /* Populate this object */
130412 ){
130413   int rc;                         /* Return Code */
130414   int i;                          /* Iterator variable */
130415   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
130416   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
130417   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
130418
130419   /* Calculate nLeafEst. */
130420   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
130421   if( rc==SQLITE_OK ){
130422     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
130423     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
130424     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
130425       nLeafEst = sqlite3_column_int(pLeafEst, 0);
130426     }
130427     rc = sqlite3_reset(pLeafEst);
130428   }
130429   if( rc!=SQLITE_OK ) return rc;
130430
130431   /* Calculate the first block to use in the output segment */
130432   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
130433   if( rc==SQLITE_OK ){
130434     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
130435       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
130436       pWriter->iEnd = pWriter->iStart - 1;
130437       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
130438     }
130439     rc = sqlite3_reset(pFirstBlock);
130440   }
130441   if( rc!=SQLITE_OK ) return rc;
130442
130443   /* Insert the marker in the %_segments table to make sure nobody tries
130444   ** to steal the space just allocated. This is also used to identify 
130445   ** appendable segments.  */
130446   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
130447   if( rc!=SQLITE_OK ) return rc;
130448
130449   pWriter->iAbsLevel = iAbsLevel;
130450   pWriter->nLeafEst = nLeafEst;
130451   pWriter->iIdx = iIdx;
130452
130453   /* Set up the array of NodeWriter objects */
130454   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
130455     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
130456   }
130457   return SQLITE_OK;
130458 }
130459
130460 /*
130461 ** Remove an entry from the %_segdir table. This involves running the 
130462 ** following two statements:
130463 **
130464 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
130465 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
130466 **
130467 ** The DELETE statement removes the specific %_segdir level. The UPDATE 
130468 ** statement ensures that the remaining segments have contiguously allocated
130469 ** idx values.
130470 */
130471 static int fts3RemoveSegdirEntry(
130472   Fts3Table *p,                   /* FTS3 table handle */
130473   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
130474   int iIdx                        /* Index of %_segdir entry to delete */
130475 ){
130476   int rc;                         /* Return code */
130477   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
130478
130479   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
130480   if( rc==SQLITE_OK ){
130481     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
130482     sqlite3_bind_int(pDelete, 2, iIdx);
130483     sqlite3_step(pDelete);
130484     rc = sqlite3_reset(pDelete);
130485   }
130486
130487   return rc;
130488 }
130489
130490 /*
130491 ** One or more segments have just been removed from absolute level iAbsLevel.
130492 ** Update the 'idx' values of the remaining segments in the level so that
130493 ** the idx values are a contiguous sequence starting from 0.
130494 */
130495 static int fts3RepackSegdirLevel(
130496   Fts3Table *p,                   /* FTS3 table handle */
130497   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
130498 ){
130499   int rc;                         /* Return code */
130500   int *aIdx = 0;                  /* Array of remaining idx values */
130501   int nIdx = 0;                   /* Valid entries in aIdx[] */
130502   int nAlloc = 0;                 /* Allocated size of aIdx[] */
130503   int i;                          /* Iterator variable */
130504   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
130505   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
130506
130507   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
130508   if( rc==SQLITE_OK ){
130509     int rc2;
130510     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
130511     while( SQLITE_ROW==sqlite3_step(pSelect) ){
130512       if( nIdx>=nAlloc ){
130513         int *aNew;
130514         nAlloc += 16;
130515         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
130516         if( !aNew ){
130517           rc = SQLITE_NOMEM;
130518           break;
130519         }
130520         aIdx = aNew;
130521       }
130522       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
130523     }
130524     rc2 = sqlite3_reset(pSelect);
130525     if( rc==SQLITE_OK ) rc = rc2;
130526   }
130527
130528   if( rc==SQLITE_OK ){
130529     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
130530   }
130531   if( rc==SQLITE_OK ){
130532     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
130533   }
130534
130535   assert( p->bIgnoreSavepoint==0 );
130536   p->bIgnoreSavepoint = 1;
130537   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
130538     if( aIdx[i]!=i ){
130539       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
130540       sqlite3_bind_int(pUpdate, 1, i);
130541       sqlite3_step(pUpdate);
130542       rc = sqlite3_reset(pUpdate);
130543     }
130544   }
130545   p->bIgnoreSavepoint = 0;
130546
130547   sqlite3_free(aIdx);
130548   return rc;
130549 }
130550
130551 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
130552   pNode->a[0] = (char)iHeight;
130553   if( iChild ){
130554     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
130555     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
130556   }else{
130557     assert( pNode->nAlloc>=1 );
130558     pNode->n = 1;
130559   }
130560 }
130561
130562 /*
130563 ** The first two arguments are a pointer to and the size of a segment b-tree
130564 ** node. The node may be a leaf or an internal node.
130565 **
130566 ** This function creates a new node image in blob object *pNew by copying
130567 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
130568 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
130569 */
130570 static int fts3TruncateNode(
130571   const char *aNode,              /* Current node image */
130572   int nNode,                      /* Size of aNode in bytes */
130573   Blob *pNew,                     /* OUT: Write new node image here */
130574   const char *zTerm,              /* Omit all terms smaller than this */
130575   int nTerm,                      /* Size of zTerm in bytes */
130576   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
130577 ){
130578   NodeReader reader;              /* Reader object */
130579   Blob prev = {0, 0, 0};          /* Previous term written to new node */
130580   int rc = SQLITE_OK;             /* Return code */
130581   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
130582
130583   /* Allocate required output space */
130584   blobGrowBuffer(pNew, nNode, &rc);
130585   if( rc!=SQLITE_OK ) return rc;
130586   pNew->n = 0;
130587
130588   /* Populate new node buffer */
130589   for(rc = nodeReaderInit(&reader, aNode, nNode); 
130590       rc==SQLITE_OK && reader.aNode; 
130591       rc = nodeReaderNext(&reader)
130592   ){
130593     if( pNew->n==0 ){
130594       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
130595       if( res<0 || (bLeaf==0 && res==0) ) continue;
130596       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
130597       *piBlock = reader.iChild;
130598     }
130599     rc = fts3AppendToNode(
130600         pNew, &prev, reader.term.a, reader.term.n,
130601         reader.aDoclist, reader.nDoclist
130602     );
130603     if( rc!=SQLITE_OK ) break;
130604   }
130605   if( pNew->n==0 ){
130606     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
130607     *piBlock = reader.iChild;
130608   }
130609   assert( pNew->n<=pNew->nAlloc );
130610
130611   nodeReaderRelease(&reader);
130612   sqlite3_free(prev.a);
130613   return rc;
130614 }
130615
130616 /*
130617 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute 
130618 ** level iAbsLevel. This may involve deleting entries from the %_segments
130619 ** table, and modifying existing entries in both the %_segments and %_segdir
130620 ** tables.
130621 **
130622 ** SQLITE_OK is returned if the segment is updated successfully. Or an
130623 ** SQLite error code otherwise.
130624 */
130625 static int fts3TruncateSegment(
130626   Fts3Table *p,                   /* FTS3 table handle */
130627   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
130628   int iIdx,                       /* Index within level of segment to modify */
130629   const char *zTerm,              /* Remove terms smaller than this */
130630   int nTerm                      /* Number of bytes in buffer zTerm */
130631 ){
130632   int rc = SQLITE_OK;             /* Return code */
130633   Blob root = {0,0,0};            /* New root page image */
130634   Blob block = {0,0,0};           /* Buffer used for any other block */
130635   sqlite3_int64 iBlock = 0;       /* Block id */
130636   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
130637   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
130638   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
130639
130640   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
130641   if( rc==SQLITE_OK ){
130642     int rc2;                      /* sqlite3_reset() return code */
130643     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
130644     sqlite3_bind_int(pFetch, 2, iIdx);
130645     if( SQLITE_ROW==sqlite3_step(pFetch) ){
130646       const char *aRoot = sqlite3_column_blob(pFetch, 4);
130647       int nRoot = sqlite3_column_bytes(pFetch, 4);
130648       iOldStart = sqlite3_column_int64(pFetch, 1);
130649       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
130650     }
130651     rc2 = sqlite3_reset(pFetch);
130652     if( rc==SQLITE_OK ) rc = rc2;
130653   }
130654
130655   while( rc==SQLITE_OK && iBlock ){
130656     char *aBlock = 0;
130657     int nBlock = 0;
130658     iNewStart = iBlock;
130659
130660     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
130661     if( rc==SQLITE_OK ){
130662       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
130663     }
130664     if( rc==SQLITE_OK ){
130665       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
130666     }
130667     sqlite3_free(aBlock);
130668   }
130669
130670   /* Variable iNewStart now contains the first valid leaf node. */
130671   if( rc==SQLITE_OK && iNewStart ){
130672     sqlite3_stmt *pDel = 0;
130673     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
130674     if( rc==SQLITE_OK ){
130675       sqlite3_bind_int64(pDel, 1, iOldStart);
130676       sqlite3_bind_int64(pDel, 2, iNewStart-1);
130677       sqlite3_step(pDel);
130678       rc = sqlite3_reset(pDel);
130679     }
130680   }
130681
130682   if( rc==SQLITE_OK ){
130683     sqlite3_stmt *pChomp = 0;
130684     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
130685     if( rc==SQLITE_OK ){
130686       sqlite3_bind_int64(pChomp, 1, iNewStart);
130687       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
130688       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
130689       sqlite3_bind_int(pChomp, 4, iIdx);
130690       sqlite3_step(pChomp);
130691       rc = sqlite3_reset(pChomp);
130692     }
130693   }
130694
130695   sqlite3_free(root.a);
130696   sqlite3_free(block.a);
130697   return rc;
130698 }
130699
130700 /*
130701 ** This function is called after an incrmental-merge operation has run to
130702 ** merge (or partially merge) two or more segments from absolute level
130703 ** iAbsLevel.
130704 **
130705 ** Each input segment is either removed from the db completely (if all of
130706 ** its data was copied to the output segment by the incrmerge operation)
130707 ** or modified in place so that it no longer contains those entries that
130708 ** have been duplicated in the output segment.
130709 */
130710 static int fts3IncrmergeChomp(
130711   Fts3Table *p,                   /* FTS table handle */
130712   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
130713   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
130714   int *pnRem                      /* Number of segments not deleted */
130715 ){
130716   int i;
130717   int nRem = 0;
130718   int rc = SQLITE_OK;
130719
130720   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
130721     Fts3SegReader *pSeg = 0;
130722     int j;
130723
130724     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
130725     ** somewhere in the pCsr->apSegment[] array.  */
130726     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
130727       pSeg = pCsr->apSegment[j];
130728       if( pSeg->iIdx==i ) break;
130729     }
130730     assert( j<pCsr->nSegment && pSeg->iIdx==i );
130731
130732     if( pSeg->aNode==0 ){
130733       /* Seg-reader is at EOF. Remove the entire input segment. */
130734       rc = fts3DeleteSegment(p, pSeg);
130735       if( rc==SQLITE_OK ){
130736         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
130737       }
130738       *pnRem = 0;
130739     }else{
130740       /* The incremental merge did not copy all the data from this 
130741       ** segment to the upper level. The segment is modified in place
130742       ** so that it contains no keys smaller than zTerm/nTerm. */ 
130743       const char *zTerm = pSeg->zTerm;
130744       int nTerm = pSeg->nTerm;
130745       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
130746       nRem++;
130747     }
130748   }
130749
130750   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
130751     rc = fts3RepackSegdirLevel(p, iAbsLevel);
130752   }
130753
130754   *pnRem = nRem;
130755   return rc;
130756 }
130757
130758 /*
130759 ** Store an incr-merge hint in the database.
130760 */
130761 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
130762   sqlite3_stmt *pReplace = 0;
130763   int rc;                         /* Return code */
130764
130765   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
130766   if( rc==SQLITE_OK ){
130767     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
130768     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
130769     sqlite3_step(pReplace);
130770     rc = sqlite3_reset(pReplace);
130771   }
130772
130773   return rc;
130774 }
130775
130776 /*
130777 ** Load an incr-merge hint from the database. The incr-merge hint, if one 
130778 ** exists, is stored in the rowid==1 row of the %_stat table.
130779 **
130780 ** If successful, populate blob *pHint with the value read from the %_stat
130781 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
130782 ** SQLite error code.
130783 */
130784 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
130785   sqlite3_stmt *pSelect = 0;
130786   int rc;
130787
130788   pHint->n = 0;
130789   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
130790   if( rc==SQLITE_OK ){
130791     int rc2;
130792     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
130793     if( SQLITE_ROW==sqlite3_step(pSelect) ){
130794       const char *aHint = sqlite3_column_blob(pSelect, 0);
130795       int nHint = sqlite3_column_bytes(pSelect, 0);
130796       if( aHint ){
130797         blobGrowBuffer(pHint, nHint, &rc);
130798         if( rc==SQLITE_OK ){
130799           memcpy(pHint->a, aHint, nHint);
130800           pHint->n = nHint;
130801         }
130802       }
130803     }
130804     rc2 = sqlite3_reset(pSelect);
130805     if( rc==SQLITE_OK ) rc = rc2;
130806   }
130807
130808   return rc;
130809 }
130810
130811 /*
130812 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
130813 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
130814 ** consists of two varints, the absolute level number of the input segments 
130815 ** and the number of input segments.
130816 **
130817 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
130818 ** set *pRc to an SQLite error code before returning.
130819 */
130820 static void fts3IncrmergeHintPush(
130821   Blob *pHint,                    /* Hint blob to append to */
130822   i64 iAbsLevel,                  /* First varint to store in hint */
130823   int nInput,                     /* Second varint to store in hint */
130824   int *pRc                        /* IN/OUT: Error code */
130825 ){
130826   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
130827   if( *pRc==SQLITE_OK ){
130828     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
130829     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
130830   }
130831 }
130832
130833 /*
130834 ** Read the last entry (most recently pushed) from the hint blob *pHint
130835 ** and then remove the entry. Write the two values read to *piAbsLevel and 
130836 ** *pnInput before returning.
130837 **
130838 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
130839 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
130840 */
130841 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
130842   const int nHint = pHint->n;
130843   int i;
130844
130845   i = pHint->n-2;
130846   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
130847   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
130848
130849   pHint->n = i;
130850   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
130851   i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
130852   if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
130853
130854   return SQLITE_OK;
130855 }
130856
130857
130858 /*
130859 ** Attempt an incremental merge that writes nMerge leaf blocks.
130860 **
130861 ** Incremental merges happen nMin segments at a time. The two
130862 ** segments to be merged are the nMin oldest segments (the ones with
130863 ** the smallest indexes) in the highest level that contains at least
130864 ** nMin segments. Multiple merges might occur in an attempt to write the 
130865 ** quota of nMerge leaf blocks.
130866 */
130867 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
130868   int rc;                         /* Return code */
130869   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
130870   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
130871   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
130872   IncrmergeWriter *pWriter;       /* Writer object */
130873   int nSeg = 0;                   /* Number of input segments */
130874   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
130875   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
130876   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
130877
130878   /* Allocate space for the cursor, filter and writer objects */
130879   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
130880   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
130881   if( !pWriter ) return SQLITE_NOMEM;
130882   pFilter = (Fts3SegFilter *)&pWriter[1];
130883   pCsr = (Fts3MultiSegReader *)&pFilter[1];
130884
130885   rc = fts3IncrmergeHintLoad(p, &hint);
130886   while( rc==SQLITE_OK && nRem>0 ){
130887     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
130888     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
130889     int bUseHint = 0;             /* True if attempting to append */
130890
130891     /* Search the %_segdir table for the absolute level with the smallest
130892     ** relative level number that contains at least nMin segments, if any.
130893     ** If one is found, set iAbsLevel to the absolute level number and
130894     ** nSeg to nMin. If no level with at least nMin segments can be found, 
130895     ** set nSeg to -1.
130896     */
130897     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
130898     sqlite3_bind_int(pFindLevel, 1, nMin);
130899     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
130900       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
130901       nSeg = nMin;
130902     }else{
130903       nSeg = -1;
130904     }
130905     rc = sqlite3_reset(pFindLevel);
130906
130907     /* If the hint read from the %_stat table is not empty, check if the
130908     ** last entry in it specifies a relative level smaller than or equal
130909     ** to the level identified by the block above (if any). If so, this 
130910     ** iteration of the loop will work on merging at the hinted level.
130911     */
130912     if( rc==SQLITE_OK && hint.n ){
130913       int nHint = hint.n;
130914       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
130915       int nHintSeg = 0;                     /* Hint number of segments */
130916
130917       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
130918       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
130919         iAbsLevel = iHintAbsLevel;
130920         nSeg = nHintSeg;
130921         bUseHint = 1;
130922         bDirtyHint = 1;
130923       }else{
130924         /* This undoes the effect of the HintPop() above - so that no entry
130925         ** is removed from the hint blob.  */
130926         hint.n = nHint;
130927       }
130928     }
130929
130930     /* If nSeg is less that zero, then there is no level with at least
130931     ** nMin segments and no hint in the %_stat table. No work to do.
130932     ** Exit early in this case.  */
130933     if( nSeg<0 ) break;
130934
130935     /* Open a cursor to iterate through the contents of the oldest nSeg 
130936     ** indexes of absolute level iAbsLevel. If this cursor is opened using 
130937     ** the 'hint' parameters, it is possible that there are less than nSeg
130938     ** segments available in level iAbsLevel. In this case, no work is
130939     ** done on iAbsLevel - fall through to the next iteration of the loop 
130940     ** to start work on some other level.  */
130941     memset(pWriter, 0, nAlloc);
130942     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
130943     if( rc==SQLITE_OK ){
130944       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
130945     }
130946     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
130947      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
130948      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
130949     ){
130950       int iIdx = 0;               /* Largest idx in level (iAbsLevel+1) */
130951       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
130952       if( rc==SQLITE_OK ){
130953         if( bUseHint && iIdx>0 ){
130954           const char *zKey = pCsr->zTerm;
130955           int nKey = pCsr->nTerm;
130956           rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
130957         }else{
130958           rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
130959         }
130960       }
130961
130962       if( rc==SQLITE_OK && pWriter->nLeafEst ){
130963         fts3LogMerge(nSeg, iAbsLevel);
130964         do {
130965           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
130966           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
130967           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
130968         }while( rc==SQLITE_ROW );
130969
130970         /* Update or delete the input segments */
130971         if( rc==SQLITE_OK ){
130972           nRem -= (1 + pWriter->nWork);
130973           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
130974           if( nSeg!=0 ){
130975             bDirtyHint = 1;
130976             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
130977           }
130978         }
130979       }
130980
130981       fts3IncrmergeRelease(p, pWriter, &rc);
130982     }
130983
130984     sqlite3Fts3SegReaderFinish(pCsr);
130985   }
130986
130987   /* Write the hint values into the %_stat table for the next incr-merger */
130988   if( bDirtyHint && rc==SQLITE_OK ){
130989     rc = fts3IncrmergeHintStore(p, &hint);
130990   }
130991
130992   sqlite3_free(pWriter);
130993   sqlite3_free(hint.a);
130994   return rc;
130995 }
130996
130997 /*
130998 ** Convert the text beginning at *pz into an integer and return
130999 ** its value.  Advance *pz to point to the first character past
131000 ** the integer.
131001 */
131002 static int fts3Getint(const char **pz){
131003   const char *z = *pz;
131004   int i = 0;
131005   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
131006   *pz = z;
131007   return i;
131008 }
131009
131010 /*
131011 ** Process statements of the form:
131012 **
131013 **    INSERT INTO table(table) VALUES('merge=A,B');
131014 **
131015 ** A and B are integers that decode to be the number of leaf pages
131016 ** written for the merge, and the minimum number of segments on a level
131017 ** before it will be selected for a merge, respectively.
131018 */
131019 static int fts3DoIncrmerge(
131020   Fts3Table *p,                   /* FTS3 table handle */
131021   const char *zParam              /* Nul-terminated string containing "A,B" */
131022 ){
131023   int rc;
131024   int nMin = (FTS3_MERGE_COUNT / 2);
131025   int nMerge = 0;
131026   const char *z = zParam;
131027
131028   /* Read the first integer value */
131029   nMerge = fts3Getint(&z);
131030
131031   /* If the first integer value is followed by a ',',  read the second
131032   ** integer value. */
131033   if( z[0]==',' && z[1]!='\0' ){
131034     z++;
131035     nMin = fts3Getint(&z);
131036   }
131037
131038   if( z[0]!='\0' || nMin<2 ){
131039     rc = SQLITE_ERROR;
131040   }else{
131041     rc = SQLITE_OK;
131042     if( !p->bHasStat ){
131043       assert( p->bFts4==0 );
131044       sqlite3Fts3CreateStatTable(&rc, p);
131045     }
131046     if( rc==SQLITE_OK ){
131047       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
131048     }
131049     sqlite3Fts3SegmentsClose(p);
131050   }
131051   return rc;
131052 }
131053
131054 /*
131055 ** Process statements of the form:
131056 **
131057 **    INSERT INTO table(table) VALUES('automerge=X');
131058 **
131059 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
131060 ** turn it on.  The setting is persistent.
131061 */
131062 static int fts3DoAutoincrmerge(
131063   Fts3Table *p,                   /* FTS3 table handle */
131064   const char *zParam              /* Nul-terminated string containing boolean */
131065 ){
131066   int rc = SQLITE_OK;
131067   sqlite3_stmt *pStmt = 0;
131068   p->bAutoincrmerge = fts3Getint(&zParam)!=0;
131069   if( !p->bHasStat ){
131070     assert( p->bFts4==0 );
131071     sqlite3Fts3CreateStatTable(&rc, p);
131072     if( rc ) return rc;
131073   }
131074   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
131075   if( rc ) return rc;;
131076   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
131077   sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
131078   sqlite3_step(pStmt);
131079   rc = sqlite3_reset(pStmt);
131080   return rc;
131081 }
131082
131083 /*
131084 ** Return a 64-bit checksum for the FTS index entry specified by the
131085 ** arguments to this function.
131086 */
131087 static u64 fts3ChecksumEntry(
131088   const char *zTerm,              /* Pointer to buffer containing term */
131089   int nTerm,                      /* Size of zTerm in bytes */
131090   int iLangid,                    /* Language id for current row */
131091   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
131092   i64 iDocid,                     /* Docid for current row. */
131093   int iCol,                       /* Column number */
131094   int iPos                        /* Position */
131095 ){
131096   int i;
131097   u64 ret = (u64)iDocid;
131098
131099   ret += (ret<<3) + iLangid;
131100   ret += (ret<<3) + iIndex;
131101   ret += (ret<<3) + iCol;
131102   ret += (ret<<3) + iPos;
131103   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
131104
131105   return ret;
131106 }
131107
131108 /*
131109 ** Return a checksum of all entries in the FTS index that correspond to
131110 ** language id iLangid. The checksum is calculated by XORing the checksums
131111 ** of each individual entry (see fts3ChecksumEntry()) together.
131112 **
131113 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
131114 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
131115 ** return value is undefined in this case.
131116 */
131117 static u64 fts3ChecksumIndex(
131118   Fts3Table *p,                   /* FTS3 table handle */
131119   int iLangid,                    /* Language id to return cksum for */
131120   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
131121   int *pRc                        /* OUT: Return code */
131122 ){
131123   Fts3SegFilter filter;
131124   Fts3MultiSegReader csr;
131125   int rc;
131126   u64 cksum = 0;
131127
131128   assert( *pRc==SQLITE_OK );
131129
131130   memset(&filter, 0, sizeof(filter));
131131   memset(&csr, 0, sizeof(csr));
131132   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
131133   filter.flags |= FTS3_SEGMENT_SCAN;
131134
131135   rc = sqlite3Fts3SegReaderCursor(
131136       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
131137   );
131138   if( rc==SQLITE_OK ){
131139     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
131140   }
131141
131142   if( rc==SQLITE_OK ){
131143     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
131144       char *pCsr = csr.aDoclist;
131145       char *pEnd = &pCsr[csr.nDoclist];
131146
131147       i64 iDocid = 0;
131148       i64 iCol = 0;
131149       i64 iPos = 0;
131150
131151       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
131152       while( pCsr<pEnd ){
131153         i64 iVal = 0;
131154         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
131155         if( pCsr<pEnd ){
131156           if( iVal==0 || iVal==1 ){
131157             iCol = 0;
131158             iPos = 0;
131159             if( iVal ){
131160               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
131161             }else{
131162               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
131163               iDocid += iVal;
131164             }
131165           }else{
131166             iPos += (iVal - 2);
131167             cksum = cksum ^ fts3ChecksumEntry(
131168                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
131169                 (int)iCol, (int)iPos
131170             );
131171           }
131172         }
131173       }
131174     }
131175   }
131176   sqlite3Fts3SegReaderFinish(&csr);
131177
131178   *pRc = rc;
131179   return cksum;
131180 }
131181
131182 /*
131183 ** Check if the contents of the FTS index match the current contents of the
131184 ** content table. If no error occurs and the contents do match, set *pbOk
131185 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
131186 ** to false before returning.
131187 **
131188 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error 
131189 ** code. The final value of *pbOk is undefined in this case.
131190 */
131191 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
131192   int rc = SQLITE_OK;             /* Return code */
131193   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
131194   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
131195   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
131196
131197   /* This block calculates the checksum according to the FTS index. */
131198   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
131199   if( rc==SQLITE_OK ){
131200     int rc2;
131201     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
131202     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
131203       int iLangid = sqlite3_column_int(pAllLangid, 0);
131204       int i;
131205       for(i=0; i<p->nIndex; i++){
131206         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
131207       }
131208     }
131209     rc2 = sqlite3_reset(pAllLangid);
131210     if( rc==SQLITE_OK ) rc = rc2;
131211   }
131212
131213   /* This block calculates the checksum according to the %_content table */
131214   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
131215   if( rc==SQLITE_OK ){
131216     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
131217     sqlite3_stmt *pStmt = 0;
131218     char *zSql;
131219    
131220     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
131221     if( !zSql ){
131222       rc = SQLITE_NOMEM;
131223     }else{
131224       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
131225       sqlite3_free(zSql);
131226     }
131227
131228     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
131229       i64 iDocid = sqlite3_column_int64(pStmt, 0);
131230       int iLang = langidFromSelect(p, pStmt);
131231       int iCol;
131232
131233       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
131234         const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
131235         int nText = sqlite3_column_bytes(pStmt, iCol+1);
131236         sqlite3_tokenizer_cursor *pT = 0;
131237
131238         rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
131239         while( rc==SQLITE_OK ){
131240           char const *zToken;       /* Buffer containing token */
131241           int nToken = 0;           /* Number of bytes in token */
131242           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
131243           int iPos = 0;             /* Position of token in zText */
131244
131245           rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
131246           if( rc==SQLITE_OK ){
131247             int i;
131248             cksum2 = cksum2 ^ fts3ChecksumEntry(
131249                 zToken, nToken, iLang, 0, iDocid, iCol, iPos
131250             );
131251             for(i=1; i<p->nIndex; i++){
131252               if( p->aIndex[i].nPrefix<=nToken ){
131253                 cksum2 = cksum2 ^ fts3ChecksumEntry(
131254                   zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
131255                 );
131256               }
131257             }
131258           }
131259         }
131260         if( pT ) pModule->xClose(pT);
131261         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
131262       }
131263     }
131264
131265     sqlite3_finalize(pStmt);
131266   }
131267
131268   *pbOk = (cksum1==cksum2);
131269   return rc;
131270 }
131271
131272 /*
131273 ** Run the integrity-check. If no error occurs and the current contents of
131274 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
131275 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
131276 **
131277 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite 
131278 ** error code.
131279 **
131280 ** The integrity-check works as follows. For each token and indexed token
131281 ** prefix in the document set, a 64-bit checksum is calculated (by code
131282 ** in fts3ChecksumEntry()) based on the following:
131283 **
131284 **     + The index number (0 for the main index, 1 for the first prefix
131285 **       index etc.),
131286 **     + The token (or token prefix) text itself, 
131287 **     + The language-id of the row it appears in,
131288 **     + The docid of the row it appears in,
131289 **     + The column it appears in, and
131290 **     + The tokens position within that column.
131291 **
131292 ** The checksums for all entries in the index are XORed together to create
131293 ** a single checksum for the entire index.
131294 **
131295 ** The integrity-check code calculates the same checksum in two ways:
131296 **
131297 **     1. By scanning the contents of the FTS index, and 
131298 **     2. By scanning and tokenizing the content table.
131299 **
131300 ** If the two checksums are identical, the integrity-check is deemed to have
131301 ** passed.
131302 */
131303 static int fts3DoIntegrityCheck(
131304   Fts3Table *p                    /* FTS3 table handle */
131305 ){
131306   int rc;
131307   int bOk = 0;
131308   rc = fts3IntegrityCheck(p, &bOk);
131309   if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
131310   return rc;
131311 }
131312
131313 /*
131314 ** Handle a 'special' INSERT of the form:
131315 **
131316 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
131317 **
131318 ** Argument pVal contains the result of <expr>. Currently the only 
131319 ** meaningful value to insert is the text 'optimize'.
131320 */
131321 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
131322   int rc;                         /* Return Code */
131323   const char *zVal = (const char *)sqlite3_value_text(pVal);
131324   int nVal = sqlite3_value_bytes(pVal);
131325
131326   if( !zVal ){
131327     return SQLITE_NOMEM;
131328   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
131329     rc = fts3DoOptimize(p, 0);
131330   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
131331     rc = fts3DoRebuild(p);
131332   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
131333     rc = fts3DoIntegrityCheck(p);
131334   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
131335     rc = fts3DoIncrmerge(p, &zVal[6]);
131336   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
131337     rc = fts3DoAutoincrmerge(p, &zVal[10]);
131338 #ifdef SQLITE_TEST
131339   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
131340     p->nNodeSize = atoi(&zVal[9]);
131341     rc = SQLITE_OK;
131342   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
131343     p->nMaxPendingData = atoi(&zVal[11]);
131344     rc = SQLITE_OK;
131345 #endif
131346   }else{
131347     rc = SQLITE_ERROR;
131348   }
131349
131350   return rc;
131351 }
131352
131353 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
131354 /*
131355 ** Delete all cached deferred doclists. Deferred doclists are cached
131356 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
131357 */
131358 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
131359   Fts3DeferredToken *pDef;
131360   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
131361     fts3PendingListDelete(pDef->pList);
131362     pDef->pList = 0;
131363   }
131364 }
131365
131366 /*
131367 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
131368 ** this list using sqlite3Fts3DeferToken().
131369 */
131370 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
131371   Fts3DeferredToken *pDef;
131372   Fts3DeferredToken *pNext;
131373   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
131374     pNext = pDef->pNext;
131375     fts3PendingListDelete(pDef->pList);
131376     sqlite3_free(pDef);
131377   }
131378   pCsr->pDeferred = 0;
131379 }
131380
131381 /*
131382 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
131383 ** based on the row that pCsr currently points to.
131384 **
131385 ** A deferred-doclist is like any other doclist with position information
131386 ** included, except that it only contains entries for a single row of the
131387 ** table, not for all rows.
131388 */
131389 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
131390   int rc = SQLITE_OK;             /* Return code */
131391   if( pCsr->pDeferred ){
131392     int i;                        /* Used to iterate through table columns */
131393     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
131394     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
131395   
131396     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
131397     sqlite3_tokenizer *pT = p->pTokenizer;
131398     sqlite3_tokenizer_module const *pModule = pT->pModule;
131399    
131400     assert( pCsr->isRequireSeek==0 );
131401     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
131402   
131403     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
131404       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
131405       sqlite3_tokenizer_cursor *pTC = 0;
131406   
131407       rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
131408       while( rc==SQLITE_OK ){
131409         char const *zToken;       /* Buffer containing token */
131410         int nToken = 0;           /* Number of bytes in token */
131411         int iDum1 = 0, iDum2 = 0; /* Dummy variables */
131412         int iPos = 0;             /* Position of token in zText */
131413   
131414         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
131415         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
131416           Fts3PhraseToken *pPT = pDef->pToken;
131417           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
131418            && (pPT->bFirst==0 || iPos==0)
131419            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
131420            && (0==memcmp(zToken, pPT->z, pPT->n))
131421           ){
131422             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
131423           }
131424         }
131425       }
131426       if( pTC ) pModule->xClose(pTC);
131427       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
131428     }
131429   
131430     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
131431       if( pDef->pList ){
131432         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
131433       }
131434     }
131435   }
131436
131437   return rc;
131438 }
131439
131440 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
131441   Fts3DeferredToken *p, 
131442   char **ppData, 
131443   int *pnData
131444 ){
131445   char *pRet;
131446   int nSkip;
131447   sqlite3_int64 dummy;
131448
131449   *ppData = 0;
131450   *pnData = 0;
131451
131452   if( p->pList==0 ){
131453     return SQLITE_OK;
131454   }
131455
131456   pRet = (char *)sqlite3_malloc(p->pList->nData);
131457   if( !pRet ) return SQLITE_NOMEM;
131458
131459   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
131460   *pnData = p->pList->nData - nSkip;
131461   *ppData = pRet;
131462   
131463   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
131464   return SQLITE_OK;
131465 }
131466
131467 /*
131468 ** Add an entry for token pToken to the pCsr->pDeferred list.
131469 */
131470 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
131471   Fts3Cursor *pCsr,               /* Fts3 table cursor */
131472   Fts3PhraseToken *pToken,        /* Token to defer */
131473   int iCol                        /* Column that token must appear in (or -1) */
131474 ){
131475   Fts3DeferredToken *pDeferred;
131476   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
131477   if( !pDeferred ){
131478     return SQLITE_NOMEM;
131479   }
131480   memset(pDeferred, 0, sizeof(*pDeferred));
131481   pDeferred->pToken = pToken;
131482   pDeferred->pNext = pCsr->pDeferred; 
131483   pDeferred->iCol = iCol;
131484   pCsr->pDeferred = pDeferred;
131485
131486   assert( pToken->pDeferred==0 );
131487   pToken->pDeferred = pDeferred;
131488
131489   return SQLITE_OK;
131490 }
131491 #endif
131492
131493 /*
131494 ** SQLite value pRowid contains the rowid of a row that may or may not be
131495 ** present in the FTS3 table. If it is, delete it and adjust the contents
131496 ** of subsiduary data structures accordingly.
131497 */
131498 static int fts3DeleteByRowid(
131499   Fts3Table *p, 
131500   sqlite3_value *pRowid, 
131501   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
131502   u32 *aSzDel
131503 ){
131504   int rc = SQLITE_OK;             /* Return code */
131505   int bFound = 0;                 /* True if *pRowid really is in the table */
131506
131507   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
131508   if( bFound && rc==SQLITE_OK ){
131509     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
131510     rc = fts3IsEmpty(p, pRowid, &isEmpty);
131511     if( rc==SQLITE_OK ){
131512       if( isEmpty ){
131513         /* Deleting this row means the whole table is empty. In this case
131514         ** delete the contents of all three tables and throw away any
131515         ** data in the pendingTerms hash table.  */
131516         rc = fts3DeleteAll(p, 1);
131517         *pnChng = 0;
131518         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
131519       }else{
131520         *pnChng = *pnChng - 1;
131521         if( p->zContentTbl==0 ){
131522           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
131523         }
131524         if( p->bHasDocsize ){
131525           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
131526         }
131527       }
131528     }
131529   }
131530
131531   return rc;
131532 }
131533
131534 /*
131535 ** This function does the work for the xUpdate method of FTS3 virtual
131536 ** tables. The schema of the virtual table being:
131537 **
131538 **     CREATE TABLE <table name>( 
131539 **       <user columns>,
131540 **       <table name> HIDDEN, 
131541 **       docid HIDDEN, 
131542 **       <langid> HIDDEN
131543 **     );
131544 **
131545 ** 
131546 */
131547 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
131548   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
131549   int nArg,                       /* Size of argument array */
131550   sqlite3_value **apVal,          /* Array of arguments */
131551   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
131552 ){
131553   Fts3Table *p = (Fts3Table *)pVtab;
131554   int rc = SQLITE_OK;             /* Return Code */
131555   int isRemove = 0;               /* True for an UPDATE or DELETE */
131556   u32 *aSzIns = 0;                /* Sizes of inserted documents */
131557   u32 *aSzDel = 0;                /* Sizes of deleted documents */
131558   int nChng = 0;                  /* Net change in number of documents */
131559   int bInsertDone = 0;
131560
131561   assert( p->pSegments==0 );
131562   assert( 
131563       nArg==1                     /* DELETE operations */
131564    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
131565   );
131566
131567   /* Check for a "special" INSERT operation. One of the form:
131568   **
131569   **   INSERT INTO xyz(xyz) VALUES('command');
131570   */
131571   if( nArg>1 
131572    && sqlite3_value_type(apVal[0])==SQLITE_NULL 
131573    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL 
131574   ){
131575     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
131576     goto update_out;
131577   }
131578
131579   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
131580     rc = SQLITE_CONSTRAINT;
131581     goto update_out;
131582   }
131583
131584   /* Allocate space to hold the change in document sizes */
131585   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
131586   if( aSzDel==0 ){
131587     rc = SQLITE_NOMEM;
131588     goto update_out;
131589   }
131590   aSzIns = &aSzDel[p->nColumn+1];
131591   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
131592
131593   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
131594   ** value, then this operation requires constraint handling.
131595   **
131596   ** If the on-conflict mode is REPLACE, this means that the existing row
131597   ** should be deleted from the database before inserting the new row. Or,
131598   ** if the on-conflict mode is other than REPLACE, then this method must
131599   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
131600   ** modify the database file.
131601   */
131602   if( nArg>1 && p->zContentTbl==0 ){
131603     /* Find the value object that holds the new rowid value. */
131604     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
131605     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
131606       pNewRowid = apVal[1];
131607     }
131608
131609     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( 
131610         sqlite3_value_type(apVal[0])==SQLITE_NULL
131611      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
131612     )){
131613       /* The new rowid is not NULL (in this case the rowid will be
131614       ** automatically assigned and there is no chance of a conflict), and 
131615       ** the statement is either an INSERT or an UPDATE that modifies the
131616       ** rowid column. So if the conflict mode is REPLACE, then delete any
131617       ** existing row with rowid=pNewRowid. 
131618       **
131619       ** Or, if the conflict mode is not REPLACE, insert the new record into 
131620       ** the %_content table. If we hit the duplicate rowid constraint (or any
131621       ** other error) while doing so, return immediately.
131622       **
131623       ** This branch may also run if pNewRowid contains a value that cannot
131624       ** be losslessly converted to an integer. In this case, the eventual 
131625       ** call to fts3InsertData() (either just below or further on in this
131626       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is 
131627       ** invoked, it will delete zero rows (since no row will have
131628       ** docid=$pNewRowid if $pNewRowid is not an integer value).
131629       */
131630       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
131631         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
131632       }else{
131633         rc = fts3InsertData(p, apVal, pRowid);
131634         bInsertDone = 1;
131635       }
131636     }
131637   }
131638   if( rc!=SQLITE_OK ){
131639     goto update_out;
131640   }
131641
131642   /* If this is a DELETE or UPDATE operation, remove the old record. */
131643   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
131644     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
131645     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
131646     isRemove = 1;
131647   }
131648   
131649   /* If this is an INSERT or UPDATE operation, insert the new record. */
131650   if( nArg>1 && rc==SQLITE_OK ){
131651     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
131652     if( bInsertDone==0 ){
131653       rc = fts3InsertData(p, apVal, pRowid);
131654       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
131655         rc = FTS_CORRUPT_VTAB;
131656       }
131657     }
131658     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
131659       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
131660     }
131661     if( rc==SQLITE_OK ){
131662       assert( p->iPrevDocid==*pRowid );
131663       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
131664     }
131665     if( p->bHasDocsize ){
131666       fts3InsertDocsize(&rc, p, aSzIns);
131667     }
131668     nChng++;
131669   }
131670
131671   if( p->bFts4 ){
131672     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
131673   }
131674
131675  update_out:
131676   sqlite3_free(aSzDel);
131677   sqlite3Fts3SegmentsClose(p);
131678   return rc;
131679 }
131680
131681 /* 
131682 ** Flush any data in the pending-terms hash table to disk. If successful,
131683 ** merge all segments in the database (including the new segment, if 
131684 ** there was any data to flush) into a single segment. 
131685 */
131686 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
131687   int rc;
131688   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
131689   if( rc==SQLITE_OK ){
131690     rc = fts3DoOptimize(p, 1);
131691     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
131692       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
131693       if( rc2!=SQLITE_OK ) rc = rc2;
131694     }else{
131695       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
131696       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
131697     }
131698   }
131699   sqlite3Fts3SegmentsClose(p);
131700   return rc;
131701 }
131702
131703 #endif
131704
131705 /************** End of fts3_write.c ******************************************/
131706 /************** Begin file fts3_snippet.c ************************************/
131707 /*
131708 ** 2009 Oct 23
131709 **
131710 ** The author disclaims copyright to this source code.  In place of
131711 ** a legal notice, here is a blessing:
131712 **
131713 **    May you do good and not evil.
131714 **    May you find forgiveness for yourself and forgive others.
131715 **    May you share freely, never taking more than you give.
131716 **
131717 ******************************************************************************
131718 */
131719
131720 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
131721
131722 /* #include <string.h> */
131723 /* #include <assert.h> */
131724
131725 /*
131726 ** Characters that may appear in the second argument to matchinfo().
131727 */
131728 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
131729 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
131730 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
131731 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
131732 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
131733 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
131734 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
131735
131736 /*
131737 ** The default value for the second argument to matchinfo(). 
131738 */
131739 #define FTS3_MATCHINFO_DEFAULT   "pcx"
131740
131741
131742 /*
131743 ** Used as an fts3ExprIterate() context when loading phrase doclists to
131744 ** Fts3Expr.aDoclist[]/nDoclist.
131745 */
131746 typedef struct LoadDoclistCtx LoadDoclistCtx;
131747 struct LoadDoclistCtx {
131748   Fts3Cursor *pCsr;               /* FTS3 Cursor */
131749   int nPhrase;                    /* Number of phrases seen so far */
131750   int nToken;                     /* Number of tokens seen so far */
131751 };
131752
131753 /*
131754 ** The following types are used as part of the implementation of the 
131755 ** fts3BestSnippet() routine.
131756 */
131757 typedef struct SnippetIter SnippetIter;
131758 typedef struct SnippetPhrase SnippetPhrase;
131759 typedef struct SnippetFragment SnippetFragment;
131760
131761 struct SnippetIter {
131762   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
131763   int iCol;                       /* Extract snippet from this column */
131764   int nSnippet;                   /* Requested snippet length (in tokens) */
131765   int nPhrase;                    /* Number of phrases in query */
131766   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
131767   int iCurrent;                   /* First token of current snippet */
131768 };
131769
131770 struct SnippetPhrase {
131771   int nToken;                     /* Number of tokens in phrase */
131772   char *pList;                    /* Pointer to start of phrase position list */
131773   int iHead;                      /* Next value in position list */
131774   char *pHead;                    /* Position list data following iHead */
131775   int iTail;                      /* Next value in trailing position list */
131776   char *pTail;                    /* Position list data following iTail */
131777 };
131778
131779 struct SnippetFragment {
131780   int iCol;                       /* Column snippet is extracted from */
131781   int iPos;                       /* Index of first token in snippet */
131782   u64 covered;                    /* Mask of query phrases covered */
131783   u64 hlmask;                     /* Mask of snippet terms to highlight */
131784 };
131785
131786 /*
131787 ** This type is used as an fts3ExprIterate() context object while 
131788 ** accumulating the data returned by the matchinfo() function.
131789 */
131790 typedef struct MatchInfo MatchInfo;
131791 struct MatchInfo {
131792   Fts3Cursor *pCursor;            /* FTS3 Cursor */
131793   int nCol;                       /* Number of columns in table */
131794   int nPhrase;                    /* Number of matchable phrases in query */
131795   sqlite3_int64 nDoc;             /* Number of docs in database */
131796   u32 *aMatchinfo;                /* Pre-allocated buffer */
131797 };
131798
131799
131800
131801 /*
131802 ** The snippet() and offsets() functions both return text values. An instance
131803 ** of the following structure is used to accumulate those values while the
131804 ** functions are running. See fts3StringAppend() for details.
131805 */
131806 typedef struct StrBuffer StrBuffer;
131807 struct StrBuffer {
131808   char *z;                        /* Pointer to buffer containing string */
131809   int n;                          /* Length of z in bytes (excl. nul-term) */
131810   int nAlloc;                     /* Allocated size of buffer z in bytes */
131811 };
131812
131813
131814 /*
131815 ** This function is used to help iterate through a position-list. A position
131816 ** list is a list of unique integers, sorted from smallest to largest. Each
131817 ** element of the list is represented by an FTS3 varint that takes the value
131818 ** of the difference between the current element and the previous one plus
131819 ** two. For example, to store the position-list:
131820 **
131821 **     4 9 113
131822 **
131823 ** the three varints:
131824 **
131825 **     6 7 106
131826 **
131827 ** are encoded.
131828 **
131829 ** When this function is called, *pp points to the start of an element of
131830 ** the list. *piPos contains the value of the previous entry in the list.
131831 ** After it returns, *piPos contains the value of the next element of the
131832 ** list and *pp is advanced to the following varint.
131833 */
131834 static void fts3GetDeltaPosition(char **pp, int *piPos){
131835   int iVal;
131836   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
131837   *piPos += (iVal-2);
131838 }
131839
131840 /*
131841 ** Helper function for fts3ExprIterate() (see below).
131842 */
131843 static int fts3ExprIterate2(
131844   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
131845   int *piPhrase,                  /* Pointer to phrase counter */
131846   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
131847   void *pCtx                      /* Second argument to pass to callback */
131848 ){
131849   int rc;                         /* Return code */
131850   int eType = pExpr->eType;       /* Type of expression node pExpr */
131851
131852   if( eType!=FTSQUERY_PHRASE ){
131853     assert( pExpr->pLeft && pExpr->pRight );
131854     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
131855     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
131856       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
131857     }
131858   }else{
131859     rc = x(pExpr, *piPhrase, pCtx);
131860     (*piPhrase)++;
131861   }
131862   return rc;
131863 }
131864
131865 /*
131866 ** Iterate through all phrase nodes in an FTS3 query, except those that
131867 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
131868 ** For each phrase node found, the supplied callback function is invoked.
131869 **
131870 ** If the callback function returns anything other than SQLITE_OK, 
131871 ** the iteration is abandoned and the error code returned immediately.
131872 ** Otherwise, SQLITE_OK is returned after a callback has been made for
131873 ** all eligible phrase nodes.
131874 */
131875 static int fts3ExprIterate(
131876   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
131877   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
131878   void *pCtx                      /* Second argument to pass to callback */
131879 ){
131880   int iPhrase = 0;                /* Variable used as the phrase counter */
131881   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
131882 }
131883
131884 /*
131885 ** This is an fts3ExprIterate() callback used while loading the doclists
131886 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
131887 ** fts3ExprLoadDoclists().
131888 */
131889 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
131890   int rc = SQLITE_OK;
131891   Fts3Phrase *pPhrase = pExpr->pPhrase;
131892   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
131893
131894   UNUSED_PARAMETER(iPhrase);
131895
131896   p->nPhrase++;
131897   p->nToken += pPhrase->nToken;
131898
131899   return rc;
131900 }
131901
131902 /*
131903 ** Load the doclists for each phrase in the query associated with FTS3 cursor
131904 ** pCsr. 
131905 **
131906 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
131907 ** phrases in the expression (all phrases except those directly or 
131908 ** indirectly descended from the right-hand-side of a NOT operator). If 
131909 ** pnToken is not NULL, then it is set to the number of tokens in all
131910 ** matchable phrases of the expression.
131911 */
131912 static int fts3ExprLoadDoclists(
131913   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
131914   int *pnPhrase,                  /* OUT: Number of phrases in query */
131915   int *pnToken                    /* OUT: Number of tokens in query */
131916 ){
131917   int rc;                         /* Return Code */
131918   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
131919   sCtx.pCsr = pCsr;
131920   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
131921   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
131922   if( pnToken ) *pnToken = sCtx.nToken;
131923   return rc;
131924 }
131925
131926 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
131927   (*(int *)ctx)++;
131928   UNUSED_PARAMETER(pExpr);
131929   UNUSED_PARAMETER(iPhrase);
131930   return SQLITE_OK;
131931 }
131932 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
131933   int nPhrase = 0;
131934   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
131935   return nPhrase;
131936 }
131937
131938 /*
131939 ** Advance the position list iterator specified by the first two 
131940 ** arguments so that it points to the first element with a value greater
131941 ** than or equal to parameter iNext.
131942 */
131943 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
131944   char *pIter = *ppIter;
131945   if( pIter ){
131946     int iIter = *piIter;
131947
131948     while( iIter<iNext ){
131949       if( 0==(*pIter & 0xFE) ){
131950         iIter = -1;
131951         pIter = 0;
131952         break;
131953       }
131954       fts3GetDeltaPosition(&pIter, &iIter);
131955     }
131956
131957     *piIter = iIter;
131958     *ppIter = pIter;
131959   }
131960 }
131961
131962 /*
131963 ** Advance the snippet iterator to the next candidate snippet.
131964 */
131965 static int fts3SnippetNextCandidate(SnippetIter *pIter){
131966   int i;                          /* Loop counter */
131967
131968   if( pIter->iCurrent<0 ){
131969     /* The SnippetIter object has just been initialized. The first snippet
131970     ** candidate always starts at offset 0 (even if this candidate has a
131971     ** score of 0.0).
131972     */
131973     pIter->iCurrent = 0;
131974
131975     /* Advance the 'head' iterator of each phrase to the first offset that
131976     ** is greater than or equal to (iNext+nSnippet).
131977     */
131978     for(i=0; i<pIter->nPhrase; i++){
131979       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
131980       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
131981     }
131982   }else{
131983     int iStart;
131984     int iEnd = 0x7FFFFFFF;
131985
131986     for(i=0; i<pIter->nPhrase; i++){
131987       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
131988       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
131989         iEnd = pPhrase->iHead;
131990       }
131991     }
131992     if( iEnd==0x7FFFFFFF ){
131993       return 1;
131994     }
131995
131996     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
131997     for(i=0; i<pIter->nPhrase; i++){
131998       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
131999       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
132000       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
132001     }
132002   }
132003
132004   return 0;
132005 }
132006
132007 /*
132008 ** Retrieve information about the current candidate snippet of snippet 
132009 ** iterator pIter.
132010 */
132011 static void fts3SnippetDetails(
132012   SnippetIter *pIter,             /* Snippet iterator */
132013   u64 mCovered,                   /* Bitmask of phrases already covered */
132014   int *piToken,                   /* OUT: First token of proposed snippet */
132015   int *piScore,                   /* OUT: "Score" for this snippet */
132016   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
132017   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
132018 ){
132019   int iStart = pIter->iCurrent;   /* First token of snippet */
132020   int iScore = 0;                 /* Score of this snippet */
132021   int i;                          /* Loop counter */
132022   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
132023   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
132024
132025   for(i=0; i<pIter->nPhrase; i++){
132026     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
132027     if( pPhrase->pTail ){
132028       char *pCsr = pPhrase->pTail;
132029       int iCsr = pPhrase->iTail;
132030
132031       while( iCsr<(iStart+pIter->nSnippet) ){
132032         int j;
132033         u64 mPhrase = (u64)1 << i;
132034         u64 mPos = (u64)1 << (iCsr - iStart);
132035         assert( iCsr>=iStart );
132036         if( (mCover|mCovered)&mPhrase ){
132037           iScore++;
132038         }else{
132039           iScore += 1000;
132040         }
132041         mCover |= mPhrase;
132042
132043         for(j=0; j<pPhrase->nToken; j++){
132044           mHighlight |= (mPos>>j);
132045         }
132046
132047         if( 0==(*pCsr & 0x0FE) ) break;
132048         fts3GetDeltaPosition(&pCsr, &iCsr);
132049       }
132050     }
132051   }
132052
132053   /* Set the output variables before returning. */
132054   *piToken = iStart;
132055   *piScore = iScore;
132056   *pmCover = mCover;
132057   *pmHighlight = mHighlight;
132058 }
132059
132060 /*
132061 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
132062 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
132063 */
132064 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
132065   SnippetIter *p = (SnippetIter *)ctx;
132066   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
132067   char *pCsr;
132068   int rc;
132069
132070   pPhrase->nToken = pExpr->pPhrase->nToken;
132071   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
132072   assert( rc==SQLITE_OK || pCsr==0 );
132073   if( pCsr ){
132074     int iFirst = 0;
132075     pPhrase->pList = pCsr;
132076     fts3GetDeltaPosition(&pCsr, &iFirst);
132077     assert( iFirst>=0 );
132078     pPhrase->pHead = pCsr;
132079     pPhrase->pTail = pCsr;
132080     pPhrase->iHead = iFirst;
132081     pPhrase->iTail = iFirst;
132082   }else{
132083     assert( rc!=SQLITE_OK || (
132084        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 
132085     ));
132086   }
132087
132088   return rc;
132089 }
132090
132091 /*
132092 ** Select the fragment of text consisting of nFragment contiguous tokens 
132093 ** from column iCol that represent the "best" snippet. The best snippet
132094 ** is the snippet with the highest score, where scores are calculated
132095 ** by adding:
132096 **
132097 **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
132098 **
132099 **   (b) +1000 points for the first occurrence of each matchable phrase in 
132100 **       the snippet for which the corresponding mCovered bit is not set.
132101 **
132102 ** The selected snippet parameters are stored in structure *pFragment before
132103 ** returning. The score of the selected snippet is stored in *piScore
132104 ** before returning.
132105 */
132106 static int fts3BestSnippet(
132107   int nSnippet,                   /* Desired snippet length */
132108   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
132109   int iCol,                       /* Index of column to create snippet from */
132110   u64 mCovered,                   /* Mask of phrases already covered */
132111   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
132112   SnippetFragment *pFragment,     /* OUT: Best snippet found */
132113   int *piScore                    /* OUT: Score of snippet pFragment */
132114 ){
132115   int rc;                         /* Return Code */
132116   int nList;                      /* Number of phrases in expression */
132117   SnippetIter sIter;              /* Iterates through snippet candidates */
132118   int nByte;                      /* Number of bytes of space to allocate */
132119   int iBestScore = -1;            /* Best snippet score found so far */
132120   int i;                          /* Loop counter */
132121
132122   memset(&sIter, 0, sizeof(sIter));
132123
132124   /* Iterate through the phrases in the expression to count them. The same
132125   ** callback makes sure the doclists are loaded for each phrase.
132126   */
132127   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
132128   if( rc!=SQLITE_OK ){
132129     return rc;
132130   }
132131
132132   /* Now that it is known how many phrases there are, allocate and zero
132133   ** the required space using malloc().
132134   */
132135   nByte = sizeof(SnippetPhrase) * nList;
132136   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
132137   if( !sIter.aPhrase ){
132138     return SQLITE_NOMEM;
132139   }
132140   memset(sIter.aPhrase, 0, nByte);
132141
132142   /* Initialize the contents of the SnippetIter object. Then iterate through
132143   ** the set of phrases in the expression to populate the aPhrase[] array.
132144   */
132145   sIter.pCsr = pCsr;
132146   sIter.iCol = iCol;
132147   sIter.nSnippet = nSnippet;
132148   sIter.nPhrase = nList;
132149   sIter.iCurrent = -1;
132150   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
132151
132152   /* Set the *pmSeen output variable. */
132153   for(i=0; i<nList; i++){
132154     if( sIter.aPhrase[i].pHead ){
132155       *pmSeen |= (u64)1 << i;
132156     }
132157   }
132158
132159   /* Loop through all candidate snippets. Store the best snippet in 
132160   ** *pFragment. Store its associated 'score' in iBestScore.
132161   */
132162   pFragment->iCol = iCol;
132163   while( !fts3SnippetNextCandidate(&sIter) ){
132164     int iPos;
132165     int iScore;
132166     u64 mCover;
132167     u64 mHighlight;
132168     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
132169     assert( iScore>=0 );
132170     if( iScore>iBestScore ){
132171       pFragment->iPos = iPos;
132172       pFragment->hlmask = mHighlight;
132173       pFragment->covered = mCover;
132174       iBestScore = iScore;
132175     }
132176   }
132177
132178   sqlite3_free(sIter.aPhrase);
132179   *piScore = iBestScore;
132180   return SQLITE_OK;
132181 }
132182
132183
132184 /*
132185 ** Append a string to the string-buffer passed as the first argument.
132186 **
132187 ** If nAppend is negative, then the length of the string zAppend is
132188 ** determined using strlen().
132189 */
132190 static int fts3StringAppend(
132191   StrBuffer *pStr,                /* Buffer to append to */
132192   const char *zAppend,            /* Pointer to data to append to buffer */
132193   int nAppend                     /* Size of zAppend in bytes (or -1) */
132194 ){
132195   if( nAppend<0 ){
132196     nAppend = (int)strlen(zAppend);
132197   }
132198
132199   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
132200   ** to grow the buffer until so that it is big enough to accomadate the
132201   ** appended data.
132202   */
132203   if( pStr->n+nAppend+1>=pStr->nAlloc ){
132204     int nAlloc = pStr->nAlloc+nAppend+100;
132205     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
132206     if( !zNew ){
132207       return SQLITE_NOMEM;
132208     }
132209     pStr->z = zNew;
132210     pStr->nAlloc = nAlloc;
132211   }
132212
132213   /* Append the data to the string buffer. */
132214   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
132215   pStr->n += nAppend;
132216   pStr->z[pStr->n] = '\0';
132217
132218   return SQLITE_OK;
132219 }
132220
132221 /*
132222 ** The fts3BestSnippet() function often selects snippets that end with a
132223 ** query term. That is, the final term of the snippet is always a term
132224 ** that requires highlighting. For example, if 'X' is a highlighted term
132225 ** and '.' is a non-highlighted term, BestSnippet() may select:
132226 **
132227 **     ........X.....X
132228 **
132229 ** This function "shifts" the beginning of the snippet forward in the 
132230 ** document so that there are approximately the same number of 
132231 ** non-highlighted terms to the right of the final highlighted term as there
132232 ** are to the left of the first highlighted term. For example, to this:
132233 **
132234 **     ....X.....X....
132235 **
132236 ** This is done as part of extracting the snippet text, not when selecting
132237 ** the snippet. Snippet selection is done based on doclists only, so there
132238 ** is no way for fts3BestSnippet() to know whether or not the document 
132239 ** actually contains terms that follow the final highlighted term. 
132240 */
132241 static int fts3SnippetShift(
132242   Fts3Table *pTab,                /* FTS3 table snippet comes from */
132243   int iLangid,                    /* Language id to use in tokenizing */
132244   int nSnippet,                   /* Number of tokens desired for snippet */
132245   const char *zDoc,               /* Document text to extract snippet from */
132246   int nDoc,                       /* Size of buffer zDoc in bytes */
132247   int *piPos,                     /* IN/OUT: First token of snippet */
132248   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
132249 ){
132250   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
132251
132252   if( hlmask ){
132253     int nLeft;                    /* Tokens to the left of first highlight */
132254     int nRight;                   /* Tokens to the right of last highlight */
132255     int nDesired;                 /* Ideal number of tokens to shift forward */
132256
132257     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
132258     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
132259     nDesired = (nLeft-nRight)/2;
132260
132261     /* Ideally, the start of the snippet should be pushed forward in the
132262     ** document nDesired tokens. This block checks if there are actually
132263     ** nDesired tokens to the right of the snippet. If so, *piPos and
132264     ** *pHlMask are updated to shift the snippet nDesired tokens to the
132265     ** right. Otherwise, the snippet is shifted by the number of tokens
132266     ** available.
132267     */
132268     if( nDesired>0 ){
132269       int nShift;                 /* Number of tokens to shift snippet by */
132270       int iCurrent = 0;           /* Token counter */
132271       int rc;                     /* Return Code */
132272       sqlite3_tokenizer_module *pMod;
132273       sqlite3_tokenizer_cursor *pC;
132274       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
132275
132276       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
132277       ** or more tokens in zDoc/nDoc.
132278       */
132279       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
132280       if( rc!=SQLITE_OK ){
132281         return rc;
132282       }
132283       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
132284         const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
132285         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
132286       }
132287       pMod->xClose(pC);
132288       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
132289
132290       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
132291       assert( nShift<=nDesired );
132292       if( nShift>0 ){
132293         *piPos += nShift;
132294         *pHlmask = hlmask >> nShift;
132295       }
132296     }
132297   }
132298   return SQLITE_OK;
132299 }
132300
132301 /*
132302 ** Extract the snippet text for fragment pFragment from cursor pCsr and
132303 ** append it to string buffer pOut.
132304 */
132305 static int fts3SnippetText(
132306   Fts3Cursor *pCsr,               /* FTS3 Cursor */
132307   SnippetFragment *pFragment,     /* Snippet to extract */
132308   int iFragment,                  /* Fragment number */
132309   int isLast,                     /* True for final fragment in snippet */
132310   int nSnippet,                   /* Number of tokens in extracted snippet */
132311   const char *zOpen,              /* String inserted before highlighted term */
132312   const char *zClose,             /* String inserted after highlighted term */
132313   const char *zEllipsis,          /* String inserted between snippets */
132314   StrBuffer *pOut                 /* Write output here */
132315 ){
132316   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132317   int rc;                         /* Return code */
132318   const char *zDoc;               /* Document text to extract snippet from */
132319   int nDoc;                       /* Size of zDoc in bytes */
132320   int iCurrent = 0;               /* Current token number of document */
132321   int iEnd = 0;                   /* Byte offset of end of current token */
132322   int isShiftDone = 0;            /* True after snippet is shifted */
132323   int iPos = pFragment->iPos;     /* First token of snippet */
132324   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
132325   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
132326   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
132327   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
132328   
132329   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
132330   if( zDoc==0 ){
132331     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
132332       return SQLITE_NOMEM;
132333     }
132334     return SQLITE_OK;
132335   }
132336   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
132337
132338   /* Open a token cursor on the document. */
132339   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
132340   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
132341   if( rc!=SQLITE_OK ){
132342     return rc;
132343   }
132344
132345   while( rc==SQLITE_OK ){
132346     const char *ZDUMMY;           /* Dummy argument used with tokenizer */
132347     int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
132348     int iBegin = 0;               /* Offset in zDoc of start of token */
132349     int iFin = 0;                 /* Offset in zDoc of end of token */
132350     int isHighlight = 0;          /* True for highlighted terms */
132351
132352     /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
132353     ** in the FTS code the variable that the third argument to xNext points to
132354     ** is initialized to zero before the first (*but not necessarily
132355     ** subsequent*) call to xNext(). This is done for a particular application
132356     ** that needs to know whether or not the tokenizer is being used for
132357     ** snippet generation or for some other purpose.
132358     **
132359     ** Extreme care is required when writing code to depend on this
132360     ** initialization. It is not a documented part of the tokenizer interface.
132361     ** If a tokenizer is used directly by any code outside of FTS, this
132362     ** convention might not be respected.  */
132363     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
132364     if( rc!=SQLITE_OK ){
132365       if( rc==SQLITE_DONE ){
132366         /* Special case - the last token of the snippet is also the last token
132367         ** of the column. Append any punctuation that occurred between the end
132368         ** of the previous token and the end of the document to the output. 
132369         ** Then break out of the loop. */
132370         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
132371       }
132372       break;
132373     }
132374     if( iCurrent<iPos ){ continue; }
132375
132376     if( !isShiftDone ){
132377       int n = nDoc - iBegin;
132378       rc = fts3SnippetShift(
132379           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
132380       );
132381       isShiftDone = 1;
132382
132383       /* Now that the shift has been done, check if the initial "..." are
132384       ** required. They are required if (a) this is not the first fragment,
132385       ** or (b) this fragment does not begin at position 0 of its column. 
132386       */
132387       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
132388         rc = fts3StringAppend(pOut, zEllipsis, -1);
132389       }
132390       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
132391     }
132392
132393     if( iCurrent>=(iPos+nSnippet) ){
132394       if( isLast ){
132395         rc = fts3StringAppend(pOut, zEllipsis, -1);
132396       }
132397       break;
132398     }
132399
132400     /* Set isHighlight to true if this term should be highlighted. */
132401     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
132402
132403     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
132404     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
132405     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
132406     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
132407
132408     iEnd = iFin;
132409   }
132410
132411   pMod->xClose(pC);
132412   return rc;
132413 }
132414
132415
132416 /*
132417 ** This function is used to count the entries in a column-list (a 
132418 ** delta-encoded list of term offsets within a single column of a single 
132419 ** row). When this function is called, *ppCollist should point to the
132420 ** beginning of the first varint in the column-list (the varint that
132421 ** contains the position of the first matching term in the column data).
132422 ** Before returning, *ppCollist is set to point to the first byte after
132423 ** the last varint in the column-list (either the 0x00 signifying the end
132424 ** of the position-list, or the 0x01 that precedes the column number of
132425 ** the next column in the position-list).
132426 **
132427 ** The number of elements in the column-list is returned.
132428 */
132429 static int fts3ColumnlistCount(char **ppCollist){
132430   char *pEnd = *ppCollist;
132431   char c = 0;
132432   int nEntry = 0;
132433
132434   /* A column-list is terminated by either a 0x01 or 0x00. */
132435   while( 0xFE & (*pEnd | c) ){
132436     c = *pEnd++ & 0x80;
132437     if( !c ) nEntry++;
132438   }
132439
132440   *ppCollist = pEnd;
132441   return nEntry;
132442 }
132443
132444 /*
132445 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
132446 ** for a single query. 
132447 **
132448 ** fts3ExprIterate() callback to load the 'global' elements of a
132449 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
132450 ** of the matchinfo array that are constant for all rows returned by the 
132451 ** current query.
132452 **
132453 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
132454 ** function populates Matchinfo.aMatchinfo[] as follows:
132455 **
132456 **   for(iCol=0; iCol<nCol; iCol++){
132457 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
132458 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
132459 **   }
132460 **
132461 ** where X is the number of matches for phrase iPhrase is column iCol of all
132462 ** rows of the table. Y is the number of rows for which column iCol contains
132463 ** at least one instance of phrase iPhrase.
132464 **
132465 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
132466 ** Y values are set to nDoc, where nDoc is the number of documents in the 
132467 ** file system. This is done because the full-text index doclist is required
132468 ** to calculate these values properly, and the full-text index doclist is
132469 ** not available for deferred tokens.
132470 */
132471 static int fts3ExprGlobalHitsCb(
132472   Fts3Expr *pExpr,                /* Phrase expression node */
132473   int iPhrase,                    /* Phrase number (numbered from zero) */
132474   void *pCtx                      /* Pointer to MatchInfo structure */
132475 ){
132476   MatchInfo *p = (MatchInfo *)pCtx;
132477   return sqlite3Fts3EvalPhraseStats(
132478       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
132479   );
132480 }
132481
132482 /*
132483 ** fts3ExprIterate() callback used to collect the "local" part of the
132484 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
132485 ** array that are different for each row returned by the query.
132486 */
132487 static int fts3ExprLocalHitsCb(
132488   Fts3Expr *pExpr,                /* Phrase expression node */
132489   int iPhrase,                    /* Phrase number */
132490   void *pCtx                      /* Pointer to MatchInfo structure */
132491 ){
132492   int rc = SQLITE_OK;
132493   MatchInfo *p = (MatchInfo *)pCtx;
132494   int iStart = iPhrase * p->nCol * 3;
132495   int i;
132496
132497   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
132498     char *pCsr;
132499     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
132500     if( pCsr ){
132501       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
132502     }else{
132503       p->aMatchinfo[iStart+i*3] = 0;
132504     }
132505   }
132506
132507   return rc;
132508 }
132509
132510 static int fts3MatchinfoCheck(
132511   Fts3Table *pTab, 
132512   char cArg,
132513   char **pzErr
132514 ){
132515   if( (cArg==FTS3_MATCHINFO_NPHRASE)
132516    || (cArg==FTS3_MATCHINFO_NCOL)
132517    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
132518    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
132519    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
132520    || (cArg==FTS3_MATCHINFO_LCS)
132521    || (cArg==FTS3_MATCHINFO_HITS)
132522   ){
132523     return SQLITE_OK;
132524   }
132525   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
132526   return SQLITE_ERROR;
132527 }
132528
132529 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
132530   int nVal;                       /* Number of integers output by cArg */
132531
132532   switch( cArg ){
132533     case FTS3_MATCHINFO_NDOC:
132534     case FTS3_MATCHINFO_NPHRASE: 
132535     case FTS3_MATCHINFO_NCOL: 
132536       nVal = 1;
132537       break;
132538
132539     case FTS3_MATCHINFO_AVGLENGTH:
132540     case FTS3_MATCHINFO_LENGTH:
132541     case FTS3_MATCHINFO_LCS:
132542       nVal = pInfo->nCol;
132543       break;
132544
132545     default:
132546       assert( cArg==FTS3_MATCHINFO_HITS );
132547       nVal = pInfo->nCol * pInfo->nPhrase * 3;
132548       break;
132549   }
132550
132551   return nVal;
132552 }
132553
132554 static int fts3MatchinfoSelectDoctotal(
132555   Fts3Table *pTab,
132556   sqlite3_stmt **ppStmt,
132557   sqlite3_int64 *pnDoc,
132558   const char **paLen
132559 ){
132560   sqlite3_stmt *pStmt;
132561   const char *a;
132562   sqlite3_int64 nDoc;
132563
132564   if( !*ppStmt ){
132565     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
132566     if( rc!=SQLITE_OK ) return rc;
132567   }
132568   pStmt = *ppStmt;
132569   assert( sqlite3_data_count(pStmt)==1 );
132570
132571   a = sqlite3_column_blob(pStmt, 0);
132572   a += sqlite3Fts3GetVarint(a, &nDoc);
132573   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
132574   *pnDoc = (u32)nDoc;
132575
132576   if( paLen ) *paLen = a;
132577   return SQLITE_OK;
132578 }
132579
132580 /*
132581 ** An instance of the following structure is used to store state while 
132582 ** iterating through a multi-column position-list corresponding to the
132583 ** hits for a single phrase on a single row in order to calculate the
132584 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
132585 */
132586 typedef struct LcsIterator LcsIterator;
132587 struct LcsIterator {
132588   Fts3Expr *pExpr;                /* Pointer to phrase expression */
132589   int iPosOffset;                 /* Tokens count up to end of this phrase */
132590   char *pRead;                    /* Cursor used to iterate through aDoclist */
132591   int iPos;                       /* Current position */
132592 };
132593
132594 /* 
132595 ** If LcsIterator.iCol is set to the following value, the iterator has
132596 ** finished iterating through all offsets for all columns.
132597 */
132598 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
132599
132600 static int fts3MatchinfoLcsCb(
132601   Fts3Expr *pExpr,                /* Phrase expression node */
132602   int iPhrase,                    /* Phrase number (numbered from zero) */
132603   void *pCtx                      /* Pointer to MatchInfo structure */
132604 ){
132605   LcsIterator *aIter = (LcsIterator *)pCtx;
132606   aIter[iPhrase].pExpr = pExpr;
132607   return SQLITE_OK;
132608 }
132609
132610 /*
132611 ** Advance the iterator passed as an argument to the next position. Return
132612 ** 1 if the iterator is at EOF or if it now points to the start of the
132613 ** position list for the next column.
132614 */
132615 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
132616   char *pRead = pIter->pRead;
132617   sqlite3_int64 iRead;
132618   int rc = 0;
132619
132620   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
132621   if( iRead==0 || iRead==1 ){
132622     pRead = 0;
132623     rc = 1;
132624   }else{
132625     pIter->iPos += (int)(iRead-2);
132626   }
132627
132628   pIter->pRead = pRead;
132629   return rc;
132630 }
132631   
132632 /*
132633 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
132634 **
132635 ** If the call is successful, the longest-common-substring lengths for each
132636 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
132637 ** array before returning. SQLITE_OK is returned in this case.
132638 **
132639 ** Otherwise, if an error occurs, an SQLite error code is returned and the
132640 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
132641 ** undefined.
132642 */
132643 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
132644   LcsIterator *aIter;
132645   int i;
132646   int iCol;
132647   int nToken = 0;
132648
132649   /* Allocate and populate the array of LcsIterator objects. The array
132650   ** contains one element for each matchable phrase in the query.
132651   **/
132652   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
132653   if( !aIter ) return SQLITE_NOMEM;
132654   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
132655   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
132656
132657   for(i=0; i<pInfo->nPhrase; i++){
132658     LcsIterator *pIter = &aIter[i];
132659     nToken -= pIter->pExpr->pPhrase->nToken;
132660     pIter->iPosOffset = nToken;
132661   }
132662
132663   for(iCol=0; iCol<pInfo->nCol; iCol++){
132664     int nLcs = 0;                 /* LCS value for this column */
132665     int nLive = 0;                /* Number of iterators in aIter not at EOF */
132666
132667     for(i=0; i<pInfo->nPhrase; i++){
132668       int rc;
132669       LcsIterator *pIt = &aIter[i];
132670       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
132671       if( rc!=SQLITE_OK ) return rc;
132672       if( pIt->pRead ){
132673         pIt->iPos = pIt->iPosOffset;
132674         fts3LcsIteratorAdvance(&aIter[i]);
132675         nLive++;
132676       }
132677     }
132678
132679     while( nLive>0 ){
132680       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
132681       int nThisLcs = 0;           /* LCS for the current iterator positions */
132682
132683       for(i=0; i<pInfo->nPhrase; i++){
132684         LcsIterator *pIter = &aIter[i];
132685         if( pIter->pRead==0 ){
132686           /* This iterator is already at EOF for this column. */
132687           nThisLcs = 0;
132688         }else{
132689           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
132690             pAdv = pIter;
132691           }
132692           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
132693             nThisLcs++;
132694           }else{
132695             nThisLcs = 1;
132696           }
132697           if( nThisLcs>nLcs ) nLcs = nThisLcs;
132698         }
132699       }
132700       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
132701     }
132702
132703     pInfo->aMatchinfo[iCol] = nLcs;
132704   }
132705
132706   sqlite3_free(aIter);
132707   return SQLITE_OK;
132708 }
132709
132710 /*
132711 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
132712 ** be returned by the matchinfo() function. Argument zArg contains the 
132713 ** format string passed as the second argument to matchinfo (or the
132714 ** default value "pcx" if no second argument was specified). The format
132715 ** string has already been validated and the pInfo->aMatchinfo[] array
132716 ** is guaranteed to be large enough for the output.
132717 **
132718 ** If bGlobal is true, then populate all fields of the matchinfo() output.
132719 ** If it is false, then assume that those fields that do not change between
132720 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
132721 ** have already been populated.
132722 **
132723 ** Return SQLITE_OK if successful, or an SQLite error code if an error 
132724 ** occurs. If a value other than SQLITE_OK is returned, the state the
132725 ** pInfo->aMatchinfo[] buffer is left in is undefined.
132726 */
132727 static int fts3MatchinfoValues(
132728   Fts3Cursor *pCsr,               /* FTS3 cursor object */
132729   int bGlobal,                    /* True to grab the global stats */
132730   MatchInfo *pInfo,               /* Matchinfo context object */
132731   const char *zArg                /* Matchinfo format string */
132732 ){
132733   int rc = SQLITE_OK;
132734   int i;
132735   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132736   sqlite3_stmt *pSelect = 0;
132737
132738   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
132739
132740     switch( zArg[i] ){
132741       case FTS3_MATCHINFO_NPHRASE:
132742         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
132743         break;
132744
132745       case FTS3_MATCHINFO_NCOL:
132746         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
132747         break;
132748         
132749       case FTS3_MATCHINFO_NDOC:
132750         if( bGlobal ){
132751           sqlite3_int64 nDoc = 0;
132752           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
132753           pInfo->aMatchinfo[0] = (u32)nDoc;
132754         }
132755         break;
132756
132757       case FTS3_MATCHINFO_AVGLENGTH: 
132758         if( bGlobal ){
132759           sqlite3_int64 nDoc;     /* Number of rows in table */
132760           const char *a;          /* Aggregate column length array */
132761
132762           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
132763           if( rc==SQLITE_OK ){
132764             int iCol;
132765             for(iCol=0; iCol<pInfo->nCol; iCol++){
132766               u32 iVal;
132767               sqlite3_int64 nToken;
132768               a += sqlite3Fts3GetVarint(a, &nToken);
132769               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
132770               pInfo->aMatchinfo[iCol] = iVal;
132771             }
132772           }
132773         }
132774         break;
132775
132776       case FTS3_MATCHINFO_LENGTH: {
132777         sqlite3_stmt *pSelectDocsize = 0;
132778         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
132779         if( rc==SQLITE_OK ){
132780           int iCol;
132781           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
132782           for(iCol=0; iCol<pInfo->nCol; iCol++){
132783             sqlite3_int64 nToken;
132784             a += sqlite3Fts3GetVarint(a, &nToken);
132785             pInfo->aMatchinfo[iCol] = (u32)nToken;
132786           }
132787         }
132788         sqlite3_reset(pSelectDocsize);
132789         break;
132790       }
132791
132792       case FTS3_MATCHINFO_LCS:
132793         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
132794         if( rc==SQLITE_OK ){
132795           rc = fts3MatchinfoLcs(pCsr, pInfo);
132796         }
132797         break;
132798
132799       default: {
132800         Fts3Expr *pExpr;
132801         assert( zArg[i]==FTS3_MATCHINFO_HITS );
132802         pExpr = pCsr->pExpr;
132803         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
132804         if( rc!=SQLITE_OK ) break;
132805         if( bGlobal ){
132806           if( pCsr->pDeferred ){
132807             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
132808             if( rc!=SQLITE_OK ) break;
132809           }
132810           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
132811           if( rc!=SQLITE_OK ) break;
132812         }
132813         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
132814         break;
132815       }
132816     }
132817
132818     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
132819   }
132820
132821   sqlite3_reset(pSelect);
132822   return rc;
132823 }
132824
132825
132826 /*
132827 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
132828 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
132829 */
132830 static int fts3GetMatchinfo(
132831   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
132832   const char *zArg                /* Second argument to matchinfo() function */
132833 ){
132834   MatchInfo sInfo;
132835   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132836   int rc = SQLITE_OK;
132837   int bGlobal = 0;                /* Collect 'global' stats as well as local */
132838
132839   memset(&sInfo, 0, sizeof(MatchInfo));
132840   sInfo.pCursor = pCsr;
132841   sInfo.nCol = pTab->nColumn;
132842
132843   /* If there is cached matchinfo() data, but the format string for the 
132844   ** cache does not match the format string for this request, discard 
132845   ** the cached data. */
132846   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
132847     assert( pCsr->aMatchinfo );
132848     sqlite3_free(pCsr->aMatchinfo);
132849     pCsr->zMatchinfo = 0;
132850     pCsr->aMatchinfo = 0;
132851   }
132852
132853   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
132854   ** matchinfo function has been called for this query. In this case 
132855   ** allocate the array used to accumulate the matchinfo data and
132856   ** initialize those elements that are constant for every row.
132857   */
132858   if( pCsr->aMatchinfo==0 ){
132859     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
132860     int nArg;                     /* Bytes in zArg */
132861     int i;                        /* Used to iterate through zArg */
132862
132863     /* Determine the number of phrases in the query */
132864     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
132865     sInfo.nPhrase = pCsr->nPhrase;
132866
132867     /* Determine the number of integers in the buffer returned by this call. */
132868     for(i=0; zArg[i]; i++){
132869       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
132870     }
132871
132872     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
132873     nArg = (int)strlen(zArg);
132874     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
132875     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
132876
132877     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
132878     pCsr->nMatchinfo = nMatchinfo;
132879     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
132880     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
132881     pCsr->isMatchinfoNeeded = 1;
132882     bGlobal = 1;
132883   }
132884
132885   sInfo.aMatchinfo = pCsr->aMatchinfo;
132886   sInfo.nPhrase = pCsr->nPhrase;
132887   if( pCsr->isMatchinfoNeeded ){
132888     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
132889     pCsr->isMatchinfoNeeded = 0;
132890   }
132891
132892   return rc;
132893 }
132894
132895 /*
132896 ** Implementation of snippet() function.
132897 */
132898 SQLITE_PRIVATE void sqlite3Fts3Snippet(
132899   sqlite3_context *pCtx,          /* SQLite function call context */
132900   Fts3Cursor *pCsr,               /* Cursor object */
132901   const char *zStart,             /* Snippet start text - "<b>" */
132902   const char *zEnd,               /* Snippet end text - "</b>" */
132903   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
132904   int iCol,                       /* Extract snippet from this column */
132905   int nToken                      /* Approximate number of tokens in snippet */
132906 ){
132907   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132908   int rc = SQLITE_OK;
132909   int i;
132910   StrBuffer res = {0, 0, 0};
132911
132912   /* The returned text includes up to four fragments of text extracted from
132913   ** the data in the current row. The first iteration of the for(...) loop
132914   ** below attempts to locate a single fragment of text nToken tokens in 
132915   ** size that contains at least one instance of all phrases in the query
132916   ** expression that appear in the current row. If such a fragment of text
132917   ** cannot be found, the second iteration of the loop attempts to locate
132918   ** a pair of fragments, and so on.
132919   */
132920   int nSnippet = 0;               /* Number of fragments in this snippet */
132921   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
132922   int nFToken = -1;               /* Number of tokens in each fragment */
132923
132924   if( !pCsr->pExpr ){
132925     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
132926     return;
132927   }
132928
132929   for(nSnippet=1; 1; nSnippet++){
132930
132931     int iSnip;                    /* Loop counter 0..nSnippet-1 */
132932     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
132933     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
132934
132935     if( nToken>=0 ){
132936       nFToken = (nToken+nSnippet-1) / nSnippet;
132937     }else{
132938       nFToken = -1 * nToken;
132939     }
132940
132941     for(iSnip=0; iSnip<nSnippet; iSnip++){
132942       int iBestScore = -1;        /* Best score of columns checked so far */
132943       int iRead;                  /* Used to iterate through columns */
132944       SnippetFragment *pFragment = &aSnippet[iSnip];
132945
132946       memset(pFragment, 0, sizeof(*pFragment));
132947
132948       /* Loop through all columns of the table being considered for snippets.
132949       ** If the iCol argument to this function was negative, this means all
132950       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
132951       */
132952       for(iRead=0; iRead<pTab->nColumn; iRead++){
132953         SnippetFragment sF = {0, 0, 0, 0};
132954         int iS;
132955         if( iCol>=0 && iRead!=iCol ) continue;
132956
132957         /* Find the best snippet of nFToken tokens in column iRead. */
132958         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
132959         if( rc!=SQLITE_OK ){
132960           goto snippet_out;
132961         }
132962         if( iS>iBestScore ){
132963           *pFragment = sF;
132964           iBestScore = iS;
132965         }
132966       }
132967
132968       mCovered |= pFragment->covered;
132969     }
132970
132971     /* If all query phrases seen by fts3BestSnippet() are present in at least
132972     ** one of the nSnippet snippet fragments, break out of the loop.
132973     */
132974     assert( (mCovered&mSeen)==mCovered );
132975     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
132976   }
132977
132978   assert( nFToken>0 );
132979
132980   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
132981     rc = fts3SnippetText(pCsr, &aSnippet[i], 
132982         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
132983     );
132984   }
132985
132986  snippet_out:
132987   sqlite3Fts3SegmentsClose(pTab);
132988   if( rc!=SQLITE_OK ){
132989     sqlite3_result_error_code(pCtx, rc);
132990     sqlite3_free(res.z);
132991   }else{
132992     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
132993   }
132994 }
132995
132996
132997 typedef struct TermOffset TermOffset;
132998 typedef struct TermOffsetCtx TermOffsetCtx;
132999
133000 struct TermOffset {
133001   char *pList;                    /* Position-list */
133002   int iPos;                       /* Position just read from pList */
133003   int iOff;                       /* Offset of this term from read positions */
133004 };
133005
133006 struct TermOffsetCtx {
133007   Fts3Cursor *pCsr;
133008   int iCol;                       /* Column of table to populate aTerm for */
133009   int iTerm;
133010   sqlite3_int64 iDocid;
133011   TermOffset *aTerm;
133012 };
133013
133014 /*
133015 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
133016 */
133017 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
133018   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
133019   int nTerm;                      /* Number of tokens in phrase */
133020   int iTerm;                      /* For looping through nTerm phrase terms */
133021   char *pList;                    /* Pointer to position list for phrase */
133022   int iPos = 0;                   /* First position in position-list */
133023   int rc;
133024
133025   UNUSED_PARAMETER(iPhrase);
133026   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
133027   nTerm = pExpr->pPhrase->nToken;
133028   if( pList ){
133029     fts3GetDeltaPosition(&pList, &iPos);
133030     assert( iPos>=0 );
133031   }
133032
133033   for(iTerm=0; iTerm<nTerm; iTerm++){
133034     TermOffset *pT = &p->aTerm[p->iTerm++];
133035     pT->iOff = nTerm-iTerm-1;
133036     pT->pList = pList;
133037     pT->iPos = iPos;
133038   }
133039
133040   return rc;
133041 }
133042
133043 /*
133044 ** Implementation of offsets() function.
133045 */
133046 SQLITE_PRIVATE void sqlite3Fts3Offsets(
133047   sqlite3_context *pCtx,          /* SQLite function call context */
133048   Fts3Cursor *pCsr                /* Cursor object */
133049 ){
133050   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133051   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
133052   int rc;                         /* Return Code */
133053   int nToken;                     /* Number of tokens in query */
133054   int iCol;                       /* Column currently being processed */
133055   StrBuffer res = {0, 0, 0};      /* Result string */
133056   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
133057
133058   if( !pCsr->pExpr ){
133059     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
133060     return;
133061   }
133062
133063   memset(&sCtx, 0, sizeof(sCtx));
133064   assert( pCsr->isRequireSeek==0 );
133065
133066   /* Count the number of terms in the query */
133067   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
133068   if( rc!=SQLITE_OK ) goto offsets_out;
133069
133070   /* Allocate the array of TermOffset iterators. */
133071   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
133072   if( 0==sCtx.aTerm ){
133073     rc = SQLITE_NOMEM;
133074     goto offsets_out;
133075   }
133076   sCtx.iDocid = pCsr->iPrevId;
133077   sCtx.pCsr = pCsr;
133078
133079   /* Loop through the table columns, appending offset information to 
133080   ** string-buffer res for each column.
133081   */
133082   for(iCol=0; iCol<pTab->nColumn; iCol++){
133083     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
133084     const char *ZDUMMY;           /* Dummy argument used with xNext() */
133085     int NDUMMY = 0;               /* Dummy argument used with xNext() */
133086     int iStart = 0;
133087     int iEnd = 0;
133088     int iCurrent = 0;
133089     const char *zDoc;
133090     int nDoc;
133091
133092     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
133093     ** no way that this operation can fail, so the return code from
133094     ** fts3ExprIterate() can be discarded.
133095     */
133096     sCtx.iCol = iCol;
133097     sCtx.iTerm = 0;
133098     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
133099
133100     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
133101     ** in column iCol, jump immediately to the next iteration of the loop.
133102     ** If an OOM occurs while retrieving the data (this can happen if SQLite
133103     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
133104     ** to the caller. 
133105     */
133106     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
133107     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
133108     if( zDoc==0 ){
133109       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
133110         continue;
133111       }
133112       rc = SQLITE_NOMEM;
133113       goto offsets_out;
133114     }
133115
133116     /* Initialize a tokenizer iterator to iterate through column iCol. */
133117     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
133118         zDoc, nDoc, &pC
133119     );
133120     if( rc!=SQLITE_OK ) goto offsets_out;
133121
133122     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
133123     while( rc==SQLITE_OK ){
133124       int i;                      /* Used to loop through terms */
133125       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
133126       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
133127
133128       for(i=0; i<nToken; i++){
133129         TermOffset *pT = &sCtx.aTerm[i];
133130         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
133131           iMinPos = pT->iPos-pT->iOff;
133132           pTerm = pT;
133133         }
133134       }
133135
133136       if( !pTerm ){
133137         /* All offsets for this column have been gathered. */
133138         rc = SQLITE_DONE;
133139       }else{
133140         assert( iCurrent<=iMinPos );
133141         if( 0==(0xFE&*pTerm->pList) ){
133142           pTerm->pList = 0;
133143         }else{
133144           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
133145         }
133146         while( rc==SQLITE_OK && iCurrent<iMinPos ){
133147           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
133148         }
133149         if( rc==SQLITE_OK ){
133150           char aBuffer[64];
133151           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
133152               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
133153           );
133154           rc = fts3StringAppend(&res, aBuffer, -1);
133155         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
133156           rc = FTS_CORRUPT_VTAB;
133157         }
133158       }
133159     }
133160     if( rc==SQLITE_DONE ){
133161       rc = SQLITE_OK;
133162     }
133163
133164     pMod->xClose(pC);
133165     if( rc!=SQLITE_OK ) goto offsets_out;
133166   }
133167
133168  offsets_out:
133169   sqlite3_free(sCtx.aTerm);
133170   assert( rc!=SQLITE_DONE );
133171   sqlite3Fts3SegmentsClose(pTab);
133172   if( rc!=SQLITE_OK ){
133173     sqlite3_result_error_code(pCtx,  rc);
133174     sqlite3_free(res.z);
133175   }else{
133176     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
133177   }
133178   return;
133179 }
133180
133181 /*
133182 ** Implementation of matchinfo() function.
133183 */
133184 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
133185   sqlite3_context *pContext,      /* Function call context */
133186   Fts3Cursor *pCsr,               /* FTS3 table cursor */
133187   const char *zArg                /* Second arg to matchinfo() function */
133188 ){
133189   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133190   int rc;
133191   int i;
133192   const char *zFormat;
133193
133194   if( zArg ){
133195     for(i=0; zArg[i]; i++){
133196       char *zErr = 0;
133197       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
133198         sqlite3_result_error(pContext, zErr, -1);
133199         sqlite3_free(zErr);
133200         return;
133201       }
133202     }
133203     zFormat = zArg;
133204   }else{
133205     zFormat = FTS3_MATCHINFO_DEFAULT;
133206   }
133207
133208   if( !pCsr->pExpr ){
133209     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
133210     return;
133211   }
133212
133213   /* Retrieve matchinfo() data. */
133214   rc = fts3GetMatchinfo(pCsr, zFormat);
133215   sqlite3Fts3SegmentsClose(pTab);
133216
133217   if( rc!=SQLITE_OK ){
133218     sqlite3_result_error_code(pContext, rc);
133219   }else{
133220     int n = pCsr->nMatchinfo * sizeof(u32);
133221     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
133222   }
133223 }
133224
133225 #endif
133226
133227 /************** End of fts3_snippet.c ****************************************/
133228 /************** Begin file fts3_unicode.c ************************************/
133229 /*
133230 ** 2012 May 24
133231 **
133232 ** The author disclaims copyright to this source code.  In place of
133233 ** a legal notice, here is a blessing:
133234 **
133235 **    May you do good and not evil.
133236 **    May you find forgiveness for yourself and forgive others.
133237 **    May you share freely, never taking more than you give.
133238 **
133239 ******************************************************************************
133240 **
133241 ** Implementation of the "unicode" full-text-search tokenizer.
133242 */
133243
133244 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
133245
133246 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
133247
133248 /* #include <assert.h> */
133249 /* #include <stdlib.h> */
133250 /* #include <stdio.h> */
133251 /* #include <string.h> */
133252
133253
133254 /*
133255 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
133256 ** from the sqlite3 source file utf.c. If this file is compiled as part
133257 ** of the amalgamation, they are not required.
133258 */
133259 #ifndef SQLITE_AMALGAMATION
133260
133261 static const unsigned char sqlite3Utf8Trans1[] = {
133262   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
133263   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
133264   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
133265   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
133266   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
133267   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
133268   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
133269   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
133270 };
133271
133272 #define READ_UTF8(zIn, zTerm, c)                           \
133273   c = *(zIn++);                                            \
133274   if( c>=0xc0 ){                                           \
133275     c = sqlite3Utf8Trans1[c-0xc0];                         \
133276     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
133277       c = (c<<6) + (0x3f & *(zIn++));                      \
133278     }                                                      \
133279     if( c<0x80                                             \
133280         || (c&0xFFFFF800)==0xD800                          \
133281         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
133282   }
133283
133284 #define WRITE_UTF8(zOut, c) {                          \
133285   if( c<0x00080 ){                                     \
133286     *zOut++ = (u8)(c&0xFF);                            \
133287   }                                                    \
133288   else if( c<0x00800 ){                                \
133289     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
133290     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
133291   }                                                    \
133292   else if( c<0x10000 ){                                \
133293     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
133294     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
133295     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
133296   }else{                                               \
133297     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
133298     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
133299     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
133300     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
133301   }                                                    \
133302 }
133303
133304 #endif /* ifndef SQLITE_AMALGAMATION */
133305
133306 typedef struct unicode_tokenizer unicode_tokenizer;
133307 typedef struct unicode_cursor unicode_cursor;
133308
133309 struct unicode_tokenizer {
133310   sqlite3_tokenizer base;
133311   int bRemoveDiacritic;
133312   int nException;
133313   int *aiException;
133314 };
133315
133316 struct unicode_cursor {
133317   sqlite3_tokenizer_cursor base;
133318   const unsigned char *aInput;    /* Input text being tokenized */
133319   int nInput;                     /* Size of aInput[] in bytes */
133320   int iOff;                       /* Current offset within aInput[] */
133321   int iToken;                     /* Index of next token to be returned */
133322   char *zToken;                   /* storage for current token */
133323   int nAlloc;                     /* space allocated at zToken */
133324 };
133325
133326
133327 /*
133328 ** Destroy a tokenizer allocated by unicodeCreate().
133329 */
133330 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
133331   if( pTokenizer ){
133332     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
133333     sqlite3_free(p->aiException);
133334     sqlite3_free(p);
133335   }
133336   return SQLITE_OK;
133337 }
133338
133339 /*
133340 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
133341 ** statement has specified that the tokenizer for this table shall consider
133342 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
133343 ** token characters (if bAlnum==1).
133344 **
133345 ** For each codepoint in the zIn/nIn string, this function checks if the
133346 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
133347 ** If so, no action is taken. Otherwise, the codepoint is added to the 
133348 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
133349 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
133350 ** codepoints in the aiException[] array.
133351 **
133352 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
133353 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
133354 ** It is not possible to change the behavior of the tokenizer with respect
133355 ** to these codepoints.
133356 */
133357 static int unicodeAddExceptions(
133358   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
133359   int bAlnum,                     /* Replace Isalnum() return value with this */
133360   const char *zIn,                /* Array of characters to make exceptions */
133361   int nIn                         /* Length of z in bytes */
133362 ){
133363   const unsigned char *z = (const unsigned char *)zIn;
133364   const unsigned char *zTerm = &z[nIn];
133365   int iCode;
133366   int nEntry = 0;
133367
133368   assert( bAlnum==0 || bAlnum==1 );
133369
133370   while( z<zTerm ){
133371     READ_UTF8(z, zTerm, iCode);
133372     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
133373     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
133374      && sqlite3FtsUnicodeIsdiacritic(iCode)==0 
133375     ){
133376       nEntry++;
133377     }
133378   }
133379
133380   if( nEntry ){
133381     int *aNew;                    /* New aiException[] array */
133382     int nNew;                     /* Number of valid entries in array aNew[] */
133383
133384     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
133385     if( aNew==0 ) return SQLITE_NOMEM;
133386     nNew = p->nException;
133387
133388     z = (const unsigned char *)zIn;
133389     while( z<zTerm ){
133390       READ_UTF8(z, zTerm, iCode);
133391       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
133392        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
133393       ){
133394         int i, j;
133395         for(i=0; i<nNew && aNew[i]<iCode; i++);
133396         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
133397         aNew[i] = iCode;
133398         nNew++;
133399       }
133400     }
133401     p->aiException = aNew;
133402     p->nException = nNew;
133403   }
133404
133405   return SQLITE_OK;
133406 }
133407
133408 /*
133409 ** Return true if the p->aiException[] array contains the value iCode.
133410 */
133411 static int unicodeIsException(unicode_tokenizer *p, int iCode){
133412   if( p->nException>0 ){
133413     int *a = p->aiException;
133414     int iLo = 0;
133415     int iHi = p->nException-1;
133416
133417     while( iHi>=iLo ){
133418       int iTest = (iHi + iLo) / 2;
133419       if( iCode==a[iTest] ){
133420         return 1;
133421       }else if( iCode>a[iTest] ){
133422         iLo = iTest+1;
133423       }else{
133424         iHi = iTest-1;
133425       }
133426     }
133427   }
133428
133429   return 0;
133430 }
133431
133432 /*
133433 ** Return true if, for the purposes of tokenization, codepoint iCode is
133434 ** considered a token character (not a separator).
133435 */
133436 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
133437   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
133438   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
133439 }
133440
133441 /*
133442 ** Create a new tokenizer instance.
133443 */
133444 static int unicodeCreate(
133445   int nArg,                       /* Size of array argv[] */
133446   const char * const *azArg,      /* Tokenizer creation arguments */
133447   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
133448 ){
133449   unicode_tokenizer *pNew;        /* New tokenizer object */
133450   int i;
133451   int rc = SQLITE_OK;
133452
133453   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
133454   if( pNew==NULL ) return SQLITE_NOMEM;
133455   memset(pNew, 0, sizeof(unicode_tokenizer));
133456   pNew->bRemoveDiacritic = 1;
133457
133458   for(i=0; rc==SQLITE_OK && i<nArg; i++){
133459     const char *z = azArg[i];
133460     int n = strlen(z);
133461
133462     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
133463       pNew->bRemoveDiacritic = 1;
133464     }
133465     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
133466       pNew->bRemoveDiacritic = 0;
133467     }
133468     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
133469       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
133470     }
133471     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
133472       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
133473     }
133474     else{
133475       /* Unrecognized argument */
133476       rc  = SQLITE_ERROR;
133477     }
133478   }
133479
133480   if( rc!=SQLITE_OK ){
133481     unicodeDestroy((sqlite3_tokenizer *)pNew);
133482     pNew = 0;
133483   }
133484   *pp = (sqlite3_tokenizer *)pNew;
133485   return rc;
133486 }
133487
133488 /*
133489 ** Prepare to begin tokenizing a particular string.  The input
133490 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
133491 ** used to incrementally tokenize this string is returned in 
133492 ** *ppCursor.
133493 */
133494 static int unicodeOpen(
133495   sqlite3_tokenizer *p,           /* The tokenizer */
133496   const char *aInput,             /* Input string */
133497   int nInput,                     /* Size of string aInput in bytes */
133498   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
133499 ){
133500   unicode_cursor *pCsr;
133501
133502   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
133503   if( pCsr==0 ){
133504     return SQLITE_NOMEM;
133505   }
133506   memset(pCsr, 0, sizeof(unicode_cursor));
133507
133508   pCsr->aInput = (const unsigned char *)aInput;
133509   if( aInput==0 ){
133510     pCsr->nInput = 0;
133511   }else if( nInput<0 ){
133512     pCsr->nInput = (int)strlen(aInput);
133513   }else{
133514     pCsr->nInput = nInput;
133515   }
133516
133517   *pp = &pCsr->base;
133518   UNUSED_PARAMETER(p);
133519   return SQLITE_OK;
133520 }
133521
133522 /*
133523 ** Close a tokenization cursor previously opened by a call to
133524 ** simpleOpen() above.
133525 */
133526 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
133527   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
133528   sqlite3_free(pCsr->zToken);
133529   sqlite3_free(pCsr);
133530   return SQLITE_OK;
133531 }
133532
133533 /*
133534 ** Extract the next token from a tokenization cursor.  The cursor must
133535 ** have been opened by a prior call to simpleOpen().
133536 */
133537 static int unicodeNext(
133538   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
133539   const char **paToken,           /* OUT: Token text */
133540   int *pnToken,                   /* OUT: Number of bytes at *paToken */
133541   int *piStart,                   /* OUT: Starting offset of token */
133542   int *piEnd,                     /* OUT: Ending offset of token */
133543   int *piPos                      /* OUT: Position integer of token */
133544 ){
133545   unicode_cursor *pCsr = (unicode_cursor *)pC;
133546   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
133547   int iCode;
133548   char *zOut;
133549   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
133550   const unsigned char *zStart = z;
133551   const unsigned char *zEnd;
133552   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
133553
133554   /* Scan past any delimiter characters before the start of the next token.
133555   ** Return SQLITE_DONE early if this takes us all the way to the end of 
133556   ** the input.  */
133557   while( z<zTerm ){
133558     READ_UTF8(z, zTerm, iCode);
133559     if( unicodeIsAlnum(p, iCode) ) break;
133560     zStart = z;
133561   }
133562   if( zStart>=zTerm ) return SQLITE_DONE;
133563
133564   zOut = pCsr->zToken;
133565   do {
133566     int iOut;
133567
133568     /* Grow the output buffer if required. */
133569     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
133570       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
133571       if( !zNew ) return SQLITE_NOMEM;
133572       zOut = &zNew[zOut - pCsr->zToken];
133573       pCsr->zToken = zNew;
133574       pCsr->nAlloc += 64;
133575     }
133576
133577     /* Write the folded case of the last character read to the output */
133578     zEnd = z;
133579     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
133580     if( iOut ){
133581       WRITE_UTF8(zOut, iOut);
133582     }
133583
133584     /* If the cursor is not at EOF, read the next character */
133585     if( z>=zTerm ) break;
133586     READ_UTF8(z, zTerm, iCode);
133587   }while( unicodeIsAlnum(p, iCode) 
133588        || sqlite3FtsUnicodeIsdiacritic(iCode)
133589   );
133590
133591   /* Set the output variables and return. */
133592   pCsr->iOff = (z - pCsr->aInput);
133593   *paToken = pCsr->zToken;
133594   *pnToken = zOut - pCsr->zToken;
133595   *piStart = (zStart - pCsr->aInput);
133596   *piEnd = (zEnd - pCsr->aInput);
133597   *piPos = pCsr->iToken++;
133598   return SQLITE_OK;
133599 }
133600
133601 /*
133602 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module 
133603 ** structure for the unicode tokenizer.
133604 */
133605 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
133606   static const sqlite3_tokenizer_module module = {
133607     0,
133608     unicodeCreate,
133609     unicodeDestroy,
133610     unicodeOpen,
133611     unicodeClose,
133612     unicodeNext,
133613     0,
133614   };
133615   *ppModule = &module;
133616 }
133617
133618 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
133619 #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
133620
133621 /************** End of fts3_unicode.c ****************************************/
133622 /************** Begin file fts3_unicode2.c ***********************************/
133623 /*
133624 ** 2012 May 25
133625 **
133626 ** The author disclaims copyright to this source code.  In place of
133627 ** a legal notice, here is a blessing:
133628 **
133629 **    May you do good and not evil.
133630 **    May you find forgiveness for yourself and forgive others.
133631 **    May you share freely, never taking more than you give.
133632 **
133633 ******************************************************************************
133634 */
133635
133636 /*
133637 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
133638 */
133639
133640 #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
133641 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
133642
133643 /* #include <assert.h> */
133644
133645 /*
133646 ** Return true if the argument corresponds to a unicode codepoint
133647 ** classified as either a letter or a number. Otherwise false.
133648 **
133649 ** The results are undefined if the value passed to this function
133650 ** is less than zero.
133651 */
133652 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
133653   /* Each unsigned integer in the following array corresponds to a contiguous
133654   ** range of unicode codepoints that are not either letters or numbers (i.e.
133655   ** codepoints for which this function should return 0).
133656   **
133657   ** The most significant 22 bits in each 32-bit value contain the first 
133658   ** codepoint in the range. The least significant 10 bits are used to store
133659   ** the size of the range (always at least 1). In other words, the value 
133660   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
133661   ** C. It is not possible to represent a range larger than 1023 codepoints 
133662   ** using this format.
133663   */
133664   const static unsigned int aEntry[] = {
133665     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
133666     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
133667     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
133668     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
133669     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
133670     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
133671     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
133672     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
133673     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
133674     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
133675     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
133676     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
133677     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
133678     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
133679     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
133680     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
133681     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
133682     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
133683     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
133684     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
133685     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
133686     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
133687     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
133688     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
133689     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
133690     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
133691     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
133692     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
133693     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
133694     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
133695     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
133696     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
133697     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
133698     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
133699     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
133700     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
133701     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
133702     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
133703     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
133704     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
133705     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
133706     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
133707     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
133708     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
133709     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
133710     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
133711     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
133712     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
133713     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
133714     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
133715     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
133716     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
133717     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
133718     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
133719     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
133720     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
133721     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
133722     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
133723     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
133724     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
133725     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
133726     0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,
133727     0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,
133728     0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
133729     0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
133730     0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,
133731     0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,
133732     0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,
133733     0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,
133734     0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,
133735     0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,
133736     0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,
133737     0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
133738     0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
133739     0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,
133740     0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,
133741     0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,
133742     0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,
133743     0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,
133744     0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,
133745     0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,
133746     0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,
133747     0x43FFF401,
133748   };
133749   static const unsigned int aAscii[4] = {
133750     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
133751   };
133752
133753   if( c<128 ){
133754     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
133755   }else if( c<(1<<22) ){
133756     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
133757     int iRes;
133758     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
133759     int iLo = 0;
133760     while( iHi>=iLo ){
133761       int iTest = (iHi + iLo) / 2;
133762       if( key >= aEntry[iTest] ){
133763         iRes = iTest;
133764         iLo = iTest+1;
133765       }else{
133766         iHi = iTest-1;
133767       }
133768     }
133769     assert( aEntry[0]<key );
133770     assert( key>=aEntry[iRes] );
133771     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
133772   }
133773   return 1;
133774 }
133775
133776
133777 /*
133778 ** If the argument is a codepoint corresponding to a lowercase letter
133779 ** in the ASCII range with a diacritic added, return the codepoint
133780 ** of the ASCII letter only. For example, if passed 235 - "LATIN
133781 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
133782 ** E"). The resuls of passing a codepoint that corresponds to an
133783 ** uppercase letter are undefined.
133784 */
133785 static int remove_diacritic(int c){
133786   unsigned short aDia[] = {
133787         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
133788      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
133789      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
133790      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
133791      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928, 
133792      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234, 
133793      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504, 
133794      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529, 
133795     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 
133796     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 
133797     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 
133798     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 
133799     62924, 63050, 63082, 63274, 63390, 
133800   };
133801   char aChar[] = {
133802     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',  
133803     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',  
133804     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',  
133805     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',  
133806     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0', 
133807     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',  
133808     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',  
133809     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',  
133810     'e',  'i',  'o',  'u',  'y',  
133811   };
133812
133813   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
133814   int iRes = 0;
133815   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
133816   int iLo = 0;
133817   while( iHi>=iLo ){
133818     int iTest = (iHi + iLo) / 2;
133819     if( key >= aDia[iTest] ){
133820       iRes = iTest;
133821       iLo = iTest+1;
133822     }else{
133823       iHi = iTest-1;
133824     }
133825   }
133826   assert( key>=aDia[iRes] );
133827   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
133828 };
133829
133830
133831 /*
133832 ** Return true if the argument interpreted as a unicode codepoint
133833 ** is a diacritical modifier character.
133834 */
133835 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
133836   unsigned int mask0 = 0x08029FDF;
133837   unsigned int mask1 = 0x000361F8;
133838   if( c<768 || c>817 ) return 0;
133839   return (c < 768+32) ?
133840       (mask0 & (1 << (c-768))) :
133841       (mask1 & (1 << (c-768-32)));
133842 }
133843
133844
133845 /*
133846 ** Interpret the argument as a unicode codepoint. If the codepoint
133847 ** is an upper case character that has a lower case equivalent,
133848 ** return the codepoint corresponding to the lower case version.
133849 ** Otherwise, return a copy of the argument.
133850 **
133851 ** The results are undefined if the value passed to this function
133852 ** is less than zero.
133853 */
133854 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
133855   /* Each entry in the following array defines a rule for folding a range
133856   ** of codepoints to lower case. The rule applies to a range of nRange
133857   ** codepoints starting at codepoint iCode.
133858   **
133859   ** If the least significant bit in flags is clear, then the rule applies
133860   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
133861   ** need to be folded). Or, if it is set, then the rule only applies to
133862   ** every second codepoint in the range, starting with codepoint C.
133863   **
133864   ** The 7 most significant bits in flags are an index into the aiOff[]
133865   ** array. If a specific codepoint C does require folding, then its lower
133866   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
133867   **
133868   ** The contents of this array are generated by parsing the CaseFolding.txt
133869   ** file distributed as part of the "Unicode Character Database". See
133870   ** http://www.unicode.org for details.
133871   */
133872   static const struct TableEntry {
133873     unsigned short iCode;
133874     unsigned char flags;
133875     unsigned char nRange;
133876   } aEntry[] = {
133877     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
133878     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
133879     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
133880     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
133881     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
133882     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
133883     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
133884     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
133885     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
133886     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
133887     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
133888     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
133889     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
133890     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
133891     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
133892     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
133893     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
133894     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
133895     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
133896     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
133897     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
133898     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
133899     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
133900     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
133901     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
133902     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
133903     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
133904     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
133905     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
133906     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
133907     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
133908     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
133909     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
133910     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
133911     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
133912     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
133913     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
133914     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
133915     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
133916     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
133917     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
133918     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
133919     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
133920     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
133921     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
133922     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
133923     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
133924     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
133925     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
133926     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
133927     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
133928     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
133929     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
133930     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
133931     {65313, 14, 26},       
133932   };
133933   static const unsigned short aiOff[] = {
133934    1,     2,     8,     15,    16,    26,    28,    32,    
133935    37,    38,    40,    48,    63,    64,    69,    71,    
133936    79,    80,    116,   202,   203,   205,   206,   207,   
133937    209,   210,   211,   213,   214,   217,   218,   219,   
133938    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
133939    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
133940    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
133941    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
133942    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
133943    65514, 65521, 65527, 65528, 65529, 
133944   };
133945
133946   int ret = c;
133947
133948   assert( c>=0 );
133949   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
133950
133951   if( c<128 ){
133952     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
133953   }else if( c<65536 ){
133954     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
133955     int iLo = 0;
133956     int iRes = -1;
133957
133958     while( iHi>=iLo ){
133959       int iTest = (iHi + iLo) / 2;
133960       int cmp = (c - aEntry[iTest].iCode);
133961       if( cmp>=0 ){
133962         iRes = iTest;
133963         iLo = iTest+1;
133964       }else{
133965         iHi = iTest-1;
133966       }
133967     }
133968     assert( iRes<0 || c>=aEntry[iRes].iCode );
133969
133970     if( iRes>=0 ){
133971       const struct TableEntry *p = &aEntry[iRes];
133972       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
133973         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
133974         assert( ret>0 );
133975       }
133976     }
133977
133978     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
133979   }
133980   
133981   else if( c>=66560 && c<66600 ){
133982     ret = c + 40;
133983   }
133984
133985   return ret;
133986 }
133987 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
133988 #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
133989
133990 /************** End of fts3_unicode2.c ***************************************/
133991 /************** Begin file rtree.c *******************************************/
133992 /*
133993 ** 2001 September 15
133994 **
133995 ** The author disclaims copyright to this source code.  In place of
133996 ** a legal notice, here is a blessing:
133997 **
133998 **    May you do good and not evil.
133999 **    May you find forgiveness for yourself and forgive others.
134000 **    May you share freely, never taking more than you give.
134001 **
134002 *************************************************************************
134003 ** This file contains code for implementations of the r-tree and r*-tree
134004 ** algorithms packaged as an SQLite virtual table module.
134005 */
134006
134007 /*
134008 ** Database Format of R-Tree Tables
134009 ** --------------------------------
134010 **
134011 ** The data structure for a single virtual r-tree table is stored in three 
134012 ** native SQLite tables declared as follows. In each case, the '%' character
134013 ** in the table name is replaced with the user-supplied name of the r-tree
134014 ** table.
134015 **
134016 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
134017 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
134018 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
134019 **
134020 ** The data for each node of the r-tree structure is stored in the %_node
134021 ** table. For each node that is not the root node of the r-tree, there is
134022 ** an entry in the %_parent table associating the node with its parent.
134023 ** And for each row of data in the table, there is an entry in the %_rowid
134024 ** table that maps from the entries rowid to the id of the node that it
134025 ** is stored on.
134026 **
134027 ** The root node of an r-tree always exists, even if the r-tree table is
134028 ** empty. The nodeno of the root node is always 1. All other nodes in the
134029 ** table must be the same size as the root node. The content of each node
134030 ** is formatted as follows:
134031 **
134032 **   1. If the node is the root node (node 1), then the first 2 bytes
134033 **      of the node contain the tree depth as a big-endian integer.
134034 **      For non-root nodes, the first 2 bytes are left unused.
134035 **
134036 **   2. The next 2 bytes contain the number of entries currently 
134037 **      stored in the node.
134038 **
134039 **   3. The remainder of the node contains the node entries. Each entry
134040 **      consists of a single 8-byte integer followed by an even number
134041 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
134042 **      of a record. For internal nodes it is the node number of a
134043 **      child page.
134044 */
134045
134046 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
134047
134048 /*
134049 ** This file contains an implementation of a couple of different variants
134050 ** of the r-tree algorithm. See the README file for further details. The 
134051 ** same data-structure is used for all, but the algorithms for insert and
134052 ** delete operations vary. The variants used are selected at compile time 
134053 ** by defining the following symbols:
134054 */
134055
134056 /* Either, both or none of the following may be set to activate 
134057 ** r*tree variant algorithms.
134058 */
134059 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
134060 #define VARIANT_RSTARTREE_REINSERT      1
134061
134062 /* 
134063 ** Exactly one of the following must be set to 1.
134064 */
134065 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
134066 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
134067 #define VARIANT_RSTARTREE_SPLIT         1
134068
134069 #define VARIANT_GUTTMAN_SPLIT \
134070         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
134071
134072 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
134073   #define PickNext QuadraticPickNext
134074   #define PickSeeds QuadraticPickSeeds
134075   #define AssignCells splitNodeGuttman
134076 #endif
134077 #if VARIANT_GUTTMAN_LINEAR_SPLIT
134078   #define PickNext LinearPickNext
134079   #define PickSeeds LinearPickSeeds
134080   #define AssignCells splitNodeGuttman
134081 #endif
134082 #if VARIANT_RSTARTREE_SPLIT
134083   #define AssignCells splitNodeStartree
134084 #endif
134085
134086 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
134087 # define NDEBUG 1
134088 #endif
134089
134090 #ifndef SQLITE_CORE
134091   SQLITE_EXTENSION_INIT1
134092 #else
134093 #endif
134094
134095 /* #include <string.h> */
134096 /* #include <assert.h> */
134097
134098 #ifndef SQLITE_AMALGAMATION
134099 #include "sqlite3rtree.h"
134100 typedef sqlite3_int64 i64;
134101 typedef unsigned char u8;
134102 typedef unsigned int u32;
134103 #endif
134104
134105 /*  The following macro is used to suppress compiler warnings.
134106 */
134107 #ifndef UNUSED_PARAMETER
134108 # define UNUSED_PARAMETER(x) (void)(x)
134109 #endif
134110
134111 typedef struct Rtree Rtree;
134112 typedef struct RtreeCursor RtreeCursor;
134113 typedef struct RtreeNode RtreeNode;
134114 typedef struct RtreeCell RtreeCell;
134115 typedef struct RtreeConstraint RtreeConstraint;
134116 typedef struct RtreeMatchArg RtreeMatchArg;
134117 typedef struct RtreeGeomCallback RtreeGeomCallback;
134118 typedef union RtreeCoord RtreeCoord;
134119
134120 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
134121 #define RTREE_MAX_DIMENSIONS 5
134122
134123 /* Size of hash table Rtree.aHash. This hash table is not expected to
134124 ** ever contain very many entries, so a fixed number of buckets is 
134125 ** used.
134126 */
134127 #define HASHSIZE 128
134128
134129 /* 
134130 ** An rtree virtual-table object.
134131 */
134132 struct Rtree {
134133   sqlite3_vtab base;
134134   sqlite3 *db;                /* Host database connection */
134135   int iNodeSize;              /* Size in bytes of each node in the node table */
134136   int nDim;                   /* Number of dimensions */
134137   int nBytesPerCell;          /* Bytes consumed per cell */
134138   int iDepth;                 /* Current depth of the r-tree structure */
134139   char *zDb;                  /* Name of database containing r-tree table */
134140   char *zName;                /* Name of r-tree table */ 
134141   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
134142   int nBusy;                  /* Current number of users of this structure */
134143
134144   /* List of nodes removed during a CondenseTree operation. List is
134145   ** linked together via the pointer normally used for hash chains -
134146   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
134147   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
134148   */
134149   RtreeNode *pDeleted;
134150   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
134151
134152   /* Statements to read/write/delete a record from xxx_node */
134153   sqlite3_stmt *pReadNode;
134154   sqlite3_stmt *pWriteNode;
134155   sqlite3_stmt *pDeleteNode;
134156
134157   /* Statements to read/write/delete a record from xxx_rowid */
134158   sqlite3_stmt *pReadRowid;
134159   sqlite3_stmt *pWriteRowid;
134160   sqlite3_stmt *pDeleteRowid;
134161
134162   /* Statements to read/write/delete a record from xxx_parent */
134163   sqlite3_stmt *pReadParent;
134164   sqlite3_stmt *pWriteParent;
134165   sqlite3_stmt *pDeleteParent;
134166
134167   int eCoordType;
134168 };
134169
134170 /* Possible values for eCoordType: */
134171 #define RTREE_COORD_REAL32 0
134172 #define RTREE_COORD_INT32  1
134173
134174 /*
134175 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
134176 ** only deal with integer coordinates.  No floating point operations
134177 ** will be done.
134178 */
134179 #ifdef SQLITE_RTREE_INT_ONLY
134180   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
134181   typedef int RtreeValue;                  /* Low accuracy coordinate */
134182 #else
134183   typedef double RtreeDValue;              /* High accuracy coordinate */
134184   typedef float RtreeValue;                /* Low accuracy coordinate */
134185 #endif
134186
134187 /*
134188 ** The minimum number of cells allowed for a node is a third of the 
134189 ** maximum. In Gutman's notation:
134190 **
134191 **     m = M/3
134192 **
134193 ** If an R*-tree "Reinsert" operation is required, the same number of
134194 ** cells are removed from the overfull node and reinserted into the tree.
134195 */
134196 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
134197 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
134198 #define RTREE_MAXCELLS 51
134199
134200 /*
134201 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
134202 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
134203 ** Therefore all non-root nodes must contain at least 3 entries. Since 
134204 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
134205 ** 40 or less.
134206 */
134207 #define RTREE_MAX_DEPTH 40
134208
134209 /* 
134210 ** An rtree cursor object.
134211 */
134212 struct RtreeCursor {
134213   sqlite3_vtab_cursor base;
134214   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
134215   int iCell;                        /* Index of current cell in pNode */
134216   int iStrategy;                    /* Copy of idxNum search parameter */
134217   int nConstraint;                  /* Number of entries in aConstraint */
134218   RtreeConstraint *aConstraint;     /* Search constraints. */
134219 };
134220
134221 union RtreeCoord {
134222   RtreeValue f;
134223   int i;
134224 };
134225
134226 /*
134227 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
134228 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
134229 ** variable pRtree points to the Rtree structure associated with the
134230 ** RtreeCoord.
134231 */
134232 #ifdef SQLITE_RTREE_INT_ONLY
134233 # define DCOORD(coord) ((RtreeDValue)coord.i)
134234 #else
134235 # define DCOORD(coord) (                           \
134236     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
134237       ((double)coord.f) :                           \
134238       ((double)coord.i)                             \
134239   )
134240 #endif
134241
134242 /*
134243 ** A search constraint.
134244 */
134245 struct RtreeConstraint {
134246   int iCoord;                     /* Index of constrained coordinate */
134247   int op;                         /* Constraining operation */
134248   RtreeDValue rValue;             /* Constraint value. */
134249   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
134250   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
134251 };
134252
134253 /* Possible values for RtreeConstraint.op */
134254 #define RTREE_EQ    0x41
134255 #define RTREE_LE    0x42
134256 #define RTREE_LT    0x43
134257 #define RTREE_GE    0x44
134258 #define RTREE_GT    0x45
134259 #define RTREE_MATCH 0x46
134260
134261 /* 
134262 ** An rtree structure node.
134263 */
134264 struct RtreeNode {
134265   RtreeNode *pParent;               /* Parent node */
134266   i64 iNode;
134267   int nRef;
134268   int isDirty;
134269   u8 *zData;
134270   RtreeNode *pNext;                 /* Next node in this hash chain */
134271 };
134272 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
134273
134274 /* 
134275 ** Structure to store a deserialized rtree record.
134276 */
134277 struct RtreeCell {
134278   i64 iRowid;
134279   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
134280 };
134281
134282
134283 /*
134284 ** Value for the first field of every RtreeMatchArg object. The MATCH
134285 ** operator tests that the first field of a blob operand matches this
134286 ** value to avoid operating on invalid blobs (which could cause a segfault).
134287 */
134288 #define RTREE_GEOMETRY_MAGIC 0x891245AB
134289
134290 /*
134291 ** An instance of this structure must be supplied as a blob argument to
134292 ** the right-hand-side of an SQL MATCH operator used to constrain an
134293 ** r-tree query.
134294 */
134295 struct RtreeMatchArg {
134296   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
134297   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
134298   void *pContext;
134299   int nParam;
134300   RtreeDValue aParam[1];
134301 };
134302
134303 /*
134304 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
134305 ** a single instance of the following structure is allocated. It is used
134306 ** as the context for the user-function created by by s_r_g_c(). The object
134307 ** is eventually deleted by the destructor mechanism provided by
134308 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
134309 ** the geometry callback function).
134310 */
134311 struct RtreeGeomCallback {
134312   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
134313   void *pContext;
134314 };
134315
134316 #ifndef MAX
134317 # define MAX(x,y) ((x) < (y) ? (y) : (x))
134318 #endif
134319 #ifndef MIN
134320 # define MIN(x,y) ((x) > (y) ? (y) : (x))
134321 #endif
134322
134323 /*
134324 ** Functions to deserialize a 16 bit integer, 32 bit real number and
134325 ** 64 bit integer. The deserialized value is returned.
134326 */
134327 static int readInt16(u8 *p){
134328   return (p[0]<<8) + p[1];
134329 }
134330 static void readCoord(u8 *p, RtreeCoord *pCoord){
134331   u32 i = (
134332     (((u32)p[0]) << 24) + 
134333     (((u32)p[1]) << 16) + 
134334     (((u32)p[2]) <<  8) + 
134335     (((u32)p[3]) <<  0)
134336   );
134337   *(u32 *)pCoord = i;
134338 }
134339 static i64 readInt64(u8 *p){
134340   return (
134341     (((i64)p[0]) << 56) + 
134342     (((i64)p[1]) << 48) + 
134343     (((i64)p[2]) << 40) + 
134344     (((i64)p[3]) << 32) + 
134345     (((i64)p[4]) << 24) + 
134346     (((i64)p[5]) << 16) + 
134347     (((i64)p[6]) <<  8) + 
134348     (((i64)p[7]) <<  0)
134349   );
134350 }
134351
134352 /*
134353 ** Functions to serialize a 16 bit integer, 32 bit real number and
134354 ** 64 bit integer. The value returned is the number of bytes written
134355 ** to the argument buffer (always 2, 4 and 8 respectively).
134356 */
134357 static int writeInt16(u8 *p, int i){
134358   p[0] = (i>> 8)&0xFF;
134359   p[1] = (i>> 0)&0xFF;
134360   return 2;
134361 }
134362 static int writeCoord(u8 *p, RtreeCoord *pCoord){
134363   u32 i;
134364   assert( sizeof(RtreeCoord)==4 );
134365   assert( sizeof(u32)==4 );
134366   i = *(u32 *)pCoord;
134367   p[0] = (i>>24)&0xFF;
134368   p[1] = (i>>16)&0xFF;
134369   p[2] = (i>> 8)&0xFF;
134370   p[3] = (i>> 0)&0xFF;
134371   return 4;
134372 }
134373 static int writeInt64(u8 *p, i64 i){
134374   p[0] = (i>>56)&0xFF;
134375   p[1] = (i>>48)&0xFF;
134376   p[2] = (i>>40)&0xFF;
134377   p[3] = (i>>32)&0xFF;
134378   p[4] = (i>>24)&0xFF;
134379   p[5] = (i>>16)&0xFF;
134380   p[6] = (i>> 8)&0xFF;
134381   p[7] = (i>> 0)&0xFF;
134382   return 8;
134383 }
134384
134385 /*
134386 ** Increment the reference count of node p.
134387 */
134388 static void nodeReference(RtreeNode *p){
134389   if( p ){
134390     p->nRef++;
134391   }
134392 }
134393
134394 /*
134395 ** Clear the content of node p (set all bytes to 0x00).
134396 */
134397 static void nodeZero(Rtree *pRtree, RtreeNode *p){
134398   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
134399   p->isDirty = 1;
134400 }
134401
134402 /*
134403 ** Given a node number iNode, return the corresponding key to use
134404 ** in the Rtree.aHash table.
134405 */
134406 static int nodeHash(i64 iNode){
134407   return (
134408     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
134409     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
134410   ) % HASHSIZE;
134411 }
134412
134413 /*
134414 ** Search the node hash table for node iNode. If found, return a pointer
134415 ** to it. Otherwise, return 0.
134416 */
134417 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
134418   RtreeNode *p;
134419   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
134420   return p;
134421 }
134422
134423 /*
134424 ** Add node pNode to the node hash table.
134425 */
134426 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
134427   int iHash;
134428   assert( pNode->pNext==0 );
134429   iHash = nodeHash(pNode->iNode);
134430   pNode->pNext = pRtree->aHash[iHash];
134431   pRtree->aHash[iHash] = pNode;
134432 }
134433
134434 /*
134435 ** Remove node pNode from the node hash table.
134436 */
134437 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
134438   RtreeNode **pp;
134439   if( pNode->iNode!=0 ){
134440     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
134441     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
134442     *pp = pNode->pNext;
134443     pNode->pNext = 0;
134444   }
134445 }
134446
134447 /*
134448 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
134449 ** indicating that node has not yet been assigned a node number. It is
134450 ** assigned a node number when nodeWrite() is called to write the
134451 ** node contents out to the database.
134452 */
134453 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
134454   RtreeNode *pNode;
134455   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
134456   if( pNode ){
134457     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
134458     pNode->zData = (u8 *)&pNode[1];
134459     pNode->nRef = 1;
134460     pNode->pParent = pParent;
134461     pNode->isDirty = 1;
134462     nodeReference(pParent);
134463   }
134464   return pNode;
134465 }
134466
134467 /*
134468 ** Obtain a reference to an r-tree node.
134469 */
134470 static int
134471 nodeAcquire(
134472   Rtree *pRtree,             /* R-tree structure */
134473   i64 iNode,                 /* Node number to load */
134474   RtreeNode *pParent,        /* Either the parent node or NULL */
134475   RtreeNode **ppNode         /* OUT: Acquired node */
134476 ){
134477   int rc;
134478   int rc2 = SQLITE_OK;
134479   RtreeNode *pNode;
134480
134481   /* Check if the requested node is already in the hash table. If so,
134482   ** increase its reference count and return it.
134483   */
134484   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
134485     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
134486     if( pParent && !pNode->pParent ){
134487       nodeReference(pParent);
134488       pNode->pParent = pParent;
134489     }
134490     pNode->nRef++;
134491     *ppNode = pNode;
134492     return SQLITE_OK;
134493   }
134494
134495   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
134496   rc = sqlite3_step(pRtree->pReadNode);
134497   if( rc==SQLITE_ROW ){
134498     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
134499     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
134500       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
134501       if( !pNode ){
134502         rc2 = SQLITE_NOMEM;
134503       }else{
134504         pNode->pParent = pParent;
134505         pNode->zData = (u8 *)&pNode[1];
134506         pNode->nRef = 1;
134507         pNode->iNode = iNode;
134508         pNode->isDirty = 0;
134509         pNode->pNext = 0;
134510         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
134511         nodeReference(pParent);
134512       }
134513     }
134514   }
134515   rc = sqlite3_reset(pRtree->pReadNode);
134516   if( rc==SQLITE_OK ) rc = rc2;
134517
134518   /* If the root node was just loaded, set pRtree->iDepth to the height
134519   ** of the r-tree structure. A height of zero means all data is stored on
134520   ** the root node. A height of one means the children of the root node
134521   ** are the leaves, and so on. If the depth as specified on the root node
134522   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
134523   */
134524   if( pNode && iNode==1 ){
134525     pRtree->iDepth = readInt16(pNode->zData);
134526     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
134527       rc = SQLITE_CORRUPT_VTAB;
134528     }
134529   }
134530
134531   /* If no error has occurred so far, check if the "number of entries"
134532   ** field on the node is too large. If so, set the return code to 
134533   ** SQLITE_CORRUPT_VTAB.
134534   */
134535   if( pNode && rc==SQLITE_OK ){
134536     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
134537       rc = SQLITE_CORRUPT_VTAB;
134538     }
134539   }
134540
134541   if( rc==SQLITE_OK ){
134542     if( pNode!=0 ){
134543       nodeHashInsert(pRtree, pNode);
134544     }else{
134545       rc = SQLITE_CORRUPT_VTAB;
134546     }
134547     *ppNode = pNode;
134548   }else{
134549     sqlite3_free(pNode);
134550     *ppNode = 0;
134551   }
134552
134553   return rc;
134554 }
134555
134556 /*
134557 ** Overwrite cell iCell of node pNode with the contents of pCell.
134558 */
134559 static void nodeOverwriteCell(
134560   Rtree *pRtree, 
134561   RtreeNode *pNode,  
134562   RtreeCell *pCell, 
134563   int iCell
134564 ){
134565   int ii;
134566   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
134567   p += writeInt64(p, pCell->iRowid);
134568   for(ii=0; ii<(pRtree->nDim*2); ii++){
134569     p += writeCoord(p, &pCell->aCoord[ii]);
134570   }
134571   pNode->isDirty = 1;
134572 }
134573
134574 /*
134575 ** Remove cell the cell with index iCell from node pNode.
134576 */
134577 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
134578   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
134579   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
134580   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
134581   memmove(pDst, pSrc, nByte);
134582   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
134583   pNode->isDirty = 1;
134584 }
134585
134586 /*
134587 ** Insert the contents of cell pCell into node pNode. If the insert
134588 ** is successful, return SQLITE_OK.
134589 **
134590 ** If there is not enough free space in pNode, return SQLITE_FULL.
134591 */
134592 static int
134593 nodeInsertCell(
134594   Rtree *pRtree, 
134595   RtreeNode *pNode, 
134596   RtreeCell *pCell 
134597 ){
134598   int nCell;                    /* Current number of cells in pNode */
134599   int nMaxCell;                 /* Maximum number of cells for pNode */
134600
134601   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
134602   nCell = NCELL(pNode);
134603
134604   assert( nCell<=nMaxCell );
134605   if( nCell<nMaxCell ){
134606     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
134607     writeInt16(&pNode->zData[2], nCell+1);
134608     pNode->isDirty = 1;
134609   }
134610
134611   return (nCell==nMaxCell);
134612 }
134613
134614 /*
134615 ** If the node is dirty, write it out to the database.
134616 */
134617 static int
134618 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
134619   int rc = SQLITE_OK;
134620   if( pNode->isDirty ){
134621     sqlite3_stmt *p = pRtree->pWriteNode;
134622     if( pNode->iNode ){
134623       sqlite3_bind_int64(p, 1, pNode->iNode);
134624     }else{
134625       sqlite3_bind_null(p, 1);
134626     }
134627     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
134628     sqlite3_step(p);
134629     pNode->isDirty = 0;
134630     rc = sqlite3_reset(p);
134631     if( pNode->iNode==0 && rc==SQLITE_OK ){
134632       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
134633       nodeHashInsert(pRtree, pNode);
134634     }
134635   }
134636   return rc;
134637 }
134638
134639 /*
134640 ** Release a reference to a node. If the node is dirty and the reference
134641 ** count drops to zero, the node data is written to the database.
134642 */
134643 static int
134644 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
134645   int rc = SQLITE_OK;
134646   if( pNode ){
134647     assert( pNode->nRef>0 );
134648     pNode->nRef--;
134649     if( pNode->nRef==0 ){
134650       if( pNode->iNode==1 ){
134651         pRtree->iDepth = -1;
134652       }
134653       if( pNode->pParent ){
134654         rc = nodeRelease(pRtree, pNode->pParent);
134655       }
134656       if( rc==SQLITE_OK ){
134657         rc = nodeWrite(pRtree, pNode);
134658       }
134659       nodeHashDelete(pRtree, pNode);
134660       sqlite3_free(pNode);
134661     }
134662   }
134663   return rc;
134664 }
134665
134666 /*
134667 ** Return the 64-bit integer value associated with cell iCell of
134668 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
134669 ** an internal node, then the 64-bit integer is a child page number.
134670 */
134671 static i64 nodeGetRowid(
134672   Rtree *pRtree, 
134673   RtreeNode *pNode, 
134674   int iCell
134675 ){
134676   assert( iCell<NCELL(pNode) );
134677   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
134678 }
134679
134680 /*
134681 ** Return coordinate iCoord from cell iCell in node pNode.
134682 */
134683 static void nodeGetCoord(
134684   Rtree *pRtree, 
134685   RtreeNode *pNode, 
134686   int iCell,
134687   int iCoord,
134688   RtreeCoord *pCoord           /* Space to write result to */
134689 ){
134690   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
134691 }
134692
134693 /*
134694 ** Deserialize cell iCell of node pNode. Populate the structure pointed
134695 ** to by pCell with the results.
134696 */
134697 static void nodeGetCell(
134698   Rtree *pRtree, 
134699   RtreeNode *pNode, 
134700   int iCell,
134701   RtreeCell *pCell
134702 ){
134703   int ii;
134704   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
134705   for(ii=0; ii<pRtree->nDim*2; ii++){
134706     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
134707   }
134708 }
134709
134710
134711 /* Forward declaration for the function that does the work of
134712 ** the virtual table module xCreate() and xConnect() methods.
134713 */
134714 static int rtreeInit(
134715   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
134716 );
134717
134718 /* 
134719 ** Rtree virtual table module xCreate method.
134720 */
134721 static int rtreeCreate(
134722   sqlite3 *db,
134723   void *pAux,
134724   int argc, const char *const*argv,
134725   sqlite3_vtab **ppVtab,
134726   char **pzErr
134727 ){
134728   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
134729 }
134730
134731 /* 
134732 ** Rtree virtual table module xConnect method.
134733 */
134734 static int rtreeConnect(
134735   sqlite3 *db,
134736   void *pAux,
134737   int argc, const char *const*argv,
134738   sqlite3_vtab **ppVtab,
134739   char **pzErr
134740 ){
134741   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
134742 }
134743
134744 /*
134745 ** Increment the r-tree reference count.
134746 */
134747 static void rtreeReference(Rtree *pRtree){
134748   pRtree->nBusy++;
134749 }
134750
134751 /*
134752 ** Decrement the r-tree reference count. When the reference count reaches
134753 ** zero the structure is deleted.
134754 */
134755 static void rtreeRelease(Rtree *pRtree){
134756   pRtree->nBusy--;
134757   if( pRtree->nBusy==0 ){
134758     sqlite3_finalize(pRtree->pReadNode);
134759     sqlite3_finalize(pRtree->pWriteNode);
134760     sqlite3_finalize(pRtree->pDeleteNode);
134761     sqlite3_finalize(pRtree->pReadRowid);
134762     sqlite3_finalize(pRtree->pWriteRowid);
134763     sqlite3_finalize(pRtree->pDeleteRowid);
134764     sqlite3_finalize(pRtree->pReadParent);
134765     sqlite3_finalize(pRtree->pWriteParent);
134766     sqlite3_finalize(pRtree->pDeleteParent);
134767     sqlite3_free(pRtree);
134768   }
134769 }
134770
134771 /* 
134772 ** Rtree virtual table module xDisconnect method.
134773 */
134774 static int rtreeDisconnect(sqlite3_vtab *pVtab){
134775   rtreeRelease((Rtree *)pVtab);
134776   return SQLITE_OK;
134777 }
134778
134779 /* 
134780 ** Rtree virtual table module xDestroy method.
134781 */
134782 static int rtreeDestroy(sqlite3_vtab *pVtab){
134783   Rtree *pRtree = (Rtree *)pVtab;
134784   int rc;
134785   char *zCreate = sqlite3_mprintf(
134786     "DROP TABLE '%q'.'%q_node';"
134787     "DROP TABLE '%q'.'%q_rowid';"
134788     "DROP TABLE '%q'.'%q_parent';",
134789     pRtree->zDb, pRtree->zName, 
134790     pRtree->zDb, pRtree->zName,
134791     pRtree->zDb, pRtree->zName
134792   );
134793   if( !zCreate ){
134794     rc = SQLITE_NOMEM;
134795   }else{
134796     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
134797     sqlite3_free(zCreate);
134798   }
134799   if( rc==SQLITE_OK ){
134800     rtreeRelease(pRtree);
134801   }
134802
134803   return rc;
134804 }
134805
134806 /* 
134807 ** Rtree virtual table module xOpen method.
134808 */
134809 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
134810   int rc = SQLITE_NOMEM;
134811   RtreeCursor *pCsr;
134812
134813   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
134814   if( pCsr ){
134815     memset(pCsr, 0, sizeof(RtreeCursor));
134816     pCsr->base.pVtab = pVTab;
134817     rc = SQLITE_OK;
134818   }
134819   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
134820
134821   return rc;
134822 }
134823
134824
134825 /*
134826 ** Free the RtreeCursor.aConstraint[] array and its contents.
134827 */
134828 static void freeCursorConstraints(RtreeCursor *pCsr){
134829   if( pCsr->aConstraint ){
134830     int i;                        /* Used to iterate through constraint array */
134831     for(i=0; i<pCsr->nConstraint; i++){
134832       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
134833       if( pGeom ){
134834         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
134835         sqlite3_free(pGeom);
134836       }
134837     }
134838     sqlite3_free(pCsr->aConstraint);
134839     pCsr->aConstraint = 0;
134840   }
134841 }
134842
134843 /* 
134844 ** Rtree virtual table module xClose method.
134845 */
134846 static int rtreeClose(sqlite3_vtab_cursor *cur){
134847   Rtree *pRtree = (Rtree *)(cur->pVtab);
134848   int rc;
134849   RtreeCursor *pCsr = (RtreeCursor *)cur;
134850   freeCursorConstraints(pCsr);
134851   rc = nodeRelease(pRtree, pCsr->pNode);
134852   sqlite3_free(pCsr);
134853   return rc;
134854 }
134855
134856 /*
134857 ** Rtree virtual table module xEof method.
134858 **
134859 ** Return non-zero if the cursor does not currently point to a valid 
134860 ** record (i.e if the scan has finished), or zero otherwise.
134861 */
134862 static int rtreeEof(sqlite3_vtab_cursor *cur){
134863   RtreeCursor *pCsr = (RtreeCursor *)cur;
134864   return (pCsr->pNode==0);
134865 }
134866
134867 /*
134868 ** The r-tree constraint passed as the second argument to this function is
134869 ** guaranteed to be a MATCH constraint.
134870 */
134871 static int testRtreeGeom(
134872   Rtree *pRtree,                  /* R-Tree object */
134873   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
134874   RtreeCell *pCell,               /* Cell to test */
134875   int *pbRes                      /* OUT: Test result */
134876 ){
134877   int i;
134878   RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
134879   int nCoord = pRtree->nDim*2;
134880
134881   assert( pConstraint->op==RTREE_MATCH );
134882   assert( pConstraint->pGeom );
134883
134884   for(i=0; i<nCoord; i++){
134885     aCoord[i] = DCOORD(pCell->aCoord[i]);
134886   }
134887   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
134888 }
134889
134890 /* 
134891 ** Cursor pCursor currently points to a cell in a non-leaf page.
134892 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
134893 ** (excluded) by the constraints in the pCursor->aConstraint[] 
134894 ** array, or false otherwise.
134895 **
134896 ** Return SQLITE_OK if successful or an SQLite error code if an error
134897 ** occurs within a geometry callback.
134898 */
134899 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
134900   RtreeCell cell;
134901   int ii;
134902   int bRes = 0;
134903   int rc = SQLITE_OK;
134904
134905   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
134906   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
134907     RtreeConstraint *p = &pCursor->aConstraint[ii];
134908     RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
134909     RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
134910
134911     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
134912         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
134913     );
134914
134915     switch( p->op ){
134916       case RTREE_LE: case RTREE_LT: 
134917         bRes = p->rValue<cell_min; 
134918         break;
134919
134920       case RTREE_GE: case RTREE_GT: 
134921         bRes = p->rValue>cell_max; 
134922         break;
134923
134924       case RTREE_EQ:
134925         bRes = (p->rValue>cell_max || p->rValue<cell_min);
134926         break;
134927
134928       default: {
134929         assert( p->op==RTREE_MATCH );
134930         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
134931         bRes = !bRes;
134932         break;
134933       }
134934     }
134935   }
134936
134937   *pbEof = bRes;
134938   return rc;
134939 }
134940
134941 /* 
134942 ** Test if the cell that cursor pCursor currently points to
134943 ** would be filtered (excluded) by the constraints in the 
134944 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
134945 ** returning. If the cell is not filtered (excluded) by the constraints,
134946 ** set pbEof to zero.
134947 **
134948 ** Return SQLITE_OK if successful or an SQLite error code if an error
134949 ** occurs within a geometry callback.
134950 **
134951 ** This function assumes that the cell is part of a leaf node.
134952 */
134953 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
134954   RtreeCell cell;
134955   int ii;
134956   *pbEof = 0;
134957
134958   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
134959   for(ii=0; ii<pCursor->nConstraint; ii++){
134960     RtreeConstraint *p = &pCursor->aConstraint[ii];
134961     RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
134962     int res;
134963     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
134964         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
134965     );
134966     switch( p->op ){
134967       case RTREE_LE: res = (coord<=p->rValue); break;
134968       case RTREE_LT: res = (coord<p->rValue);  break;
134969       case RTREE_GE: res = (coord>=p->rValue); break;
134970       case RTREE_GT: res = (coord>p->rValue);  break;
134971       case RTREE_EQ: res = (coord==p->rValue); break;
134972       default: {
134973         int rc;
134974         assert( p->op==RTREE_MATCH );
134975         rc = testRtreeGeom(pRtree, p, &cell, &res);
134976         if( rc!=SQLITE_OK ){
134977           return rc;
134978         }
134979         break;
134980       }
134981     }
134982
134983     if( !res ){
134984       *pbEof = 1;
134985       return SQLITE_OK;
134986     }
134987   }
134988
134989   return SQLITE_OK;
134990 }
134991
134992 /*
134993 ** Cursor pCursor currently points at a node that heads a sub-tree of
134994 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
134995 ** to point to the left-most cell of the sub-tree that matches the 
134996 ** configured constraints.
134997 */
134998 static int descendToCell(
134999   Rtree *pRtree, 
135000   RtreeCursor *pCursor, 
135001   int iHeight,
135002   int *pEof                 /* OUT: Set to true if cannot descend */
135003 ){
135004   int isEof;
135005   int rc;
135006   int ii;
135007   RtreeNode *pChild;
135008   sqlite3_int64 iRowid;
135009
135010   RtreeNode *pSavedNode = pCursor->pNode;
135011   int iSavedCell = pCursor->iCell;
135012
135013   assert( iHeight>=0 );
135014
135015   if( iHeight==0 ){
135016     rc = testRtreeEntry(pRtree, pCursor, &isEof);
135017   }else{
135018     rc = testRtreeCell(pRtree, pCursor, &isEof);
135019   }
135020   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
135021     goto descend_to_cell_out;
135022   }
135023
135024   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
135025   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
135026   if( rc!=SQLITE_OK ){
135027     goto descend_to_cell_out;
135028   }
135029
135030   nodeRelease(pRtree, pCursor->pNode);
135031   pCursor->pNode = pChild;
135032   isEof = 1;
135033   for(ii=0; isEof && ii<NCELL(pChild); ii++){
135034     pCursor->iCell = ii;
135035     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
135036     if( rc!=SQLITE_OK ){
135037       goto descend_to_cell_out;
135038     }
135039   }
135040
135041   if( isEof ){
135042     assert( pCursor->pNode==pChild );
135043     nodeReference(pSavedNode);
135044     nodeRelease(pRtree, pChild);
135045     pCursor->pNode = pSavedNode;
135046     pCursor->iCell = iSavedCell;
135047   }
135048
135049 descend_to_cell_out:
135050   *pEof = isEof;
135051   return rc;
135052 }
135053
135054 /*
135055 ** One of the cells in node pNode is guaranteed to have a 64-bit 
135056 ** integer value equal to iRowid. Return the index of this cell.
135057 */
135058 static int nodeRowidIndex(
135059   Rtree *pRtree, 
135060   RtreeNode *pNode, 
135061   i64 iRowid,
135062   int *piIndex
135063 ){
135064   int ii;
135065   int nCell = NCELL(pNode);
135066   for(ii=0; ii<nCell; ii++){
135067     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
135068       *piIndex = ii;
135069       return SQLITE_OK;
135070     }
135071   }
135072   return SQLITE_CORRUPT_VTAB;
135073 }
135074
135075 /*
135076 ** Return the index of the cell containing a pointer to node pNode
135077 ** in its parent. If pNode is the root node, return -1.
135078 */
135079 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
135080   RtreeNode *pParent = pNode->pParent;
135081   if( pParent ){
135082     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
135083   }
135084   *piIndex = -1;
135085   return SQLITE_OK;
135086 }
135087
135088 /* 
135089 ** Rtree virtual table module xNext method.
135090 */
135091 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
135092   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
135093   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
135094   int rc = SQLITE_OK;
135095
135096   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
135097   ** already at EOF. It is against the rules to call the xNext() method of
135098   ** a cursor that has already reached EOF.
135099   */
135100   assert( pCsr->pNode );
135101
135102   if( pCsr->iStrategy==1 ){
135103     /* This "scan" is a direct lookup by rowid. There is no next entry. */
135104     nodeRelease(pRtree, pCsr->pNode);
135105     pCsr->pNode = 0;
135106   }else{
135107     /* Move to the next entry that matches the configured constraints. */
135108     int iHeight = 0;
135109     while( pCsr->pNode ){
135110       RtreeNode *pNode = pCsr->pNode;
135111       int nCell = NCELL(pNode);
135112       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
135113         int isEof;
135114         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
135115         if( rc!=SQLITE_OK || !isEof ){
135116           return rc;
135117         }
135118       }
135119       pCsr->pNode = pNode->pParent;
135120       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
135121       if( rc!=SQLITE_OK ){
135122         return rc;
135123       }
135124       nodeReference(pCsr->pNode);
135125       nodeRelease(pRtree, pNode);
135126       iHeight++;
135127     }
135128   }
135129
135130   return rc;
135131 }
135132
135133 /* 
135134 ** Rtree virtual table module xRowid method.
135135 */
135136 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
135137   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
135138   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
135139
135140   assert(pCsr->pNode);
135141   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
135142
135143   return SQLITE_OK;
135144 }
135145
135146 /* 
135147 ** Rtree virtual table module xColumn method.
135148 */
135149 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
135150   Rtree *pRtree = (Rtree *)cur->pVtab;
135151   RtreeCursor *pCsr = (RtreeCursor *)cur;
135152
135153   if( i==0 ){
135154     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
135155     sqlite3_result_int64(ctx, iRowid);
135156   }else{
135157     RtreeCoord c;
135158     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
135159 #ifndef SQLITE_RTREE_INT_ONLY
135160     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
135161       sqlite3_result_double(ctx, c.f);
135162     }else
135163 #endif
135164     {
135165       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
135166       sqlite3_result_int(ctx, c.i);
135167     }
135168   }
135169
135170   return SQLITE_OK;
135171 }
135172
135173 /* 
135174 ** Use nodeAcquire() to obtain the leaf node containing the record with 
135175 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
135176 ** return SQLITE_OK. If there is no such record in the table, set
135177 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
135178 ** to zero and return an SQLite error code.
135179 */
135180 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
135181   int rc;
135182   *ppLeaf = 0;
135183   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
135184   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
135185     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
135186     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
135187     sqlite3_reset(pRtree->pReadRowid);
135188   }else{
135189     rc = sqlite3_reset(pRtree->pReadRowid);
135190   }
135191   return rc;
135192 }
135193
135194 /*
135195 ** This function is called to configure the RtreeConstraint object passed
135196 ** as the second argument for a MATCH constraint. The value passed as the
135197 ** first argument to this function is the right-hand operand to the MATCH
135198 ** operator.
135199 */
135200 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
135201   RtreeMatchArg *p;
135202   sqlite3_rtree_geometry *pGeom;
135203   int nBlob;
135204
135205   /* Check that value is actually a blob. */
135206   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
135207
135208   /* Check that the blob is roughly the right size. */
135209   nBlob = sqlite3_value_bytes(pValue);
135210   if( nBlob<(int)sizeof(RtreeMatchArg) 
135211    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
135212   ){
135213     return SQLITE_ERROR;
135214   }
135215
135216   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
135217       sizeof(sqlite3_rtree_geometry) + nBlob
135218   );
135219   if( !pGeom ) return SQLITE_NOMEM;
135220   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
135221   p = (RtreeMatchArg *)&pGeom[1];
135222
135223   memcpy(p, sqlite3_value_blob(pValue), nBlob);
135224   if( p->magic!=RTREE_GEOMETRY_MAGIC 
135225    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
135226   ){
135227     sqlite3_free(pGeom);
135228     return SQLITE_ERROR;
135229   }
135230
135231   pGeom->pContext = p->pContext;
135232   pGeom->nParam = p->nParam;
135233   pGeom->aParam = p->aParam;
135234
135235   pCons->xGeom = p->xGeom;
135236   pCons->pGeom = pGeom;
135237   return SQLITE_OK;
135238 }
135239
135240 /* 
135241 ** Rtree virtual table module xFilter method.
135242 */
135243 static int rtreeFilter(
135244   sqlite3_vtab_cursor *pVtabCursor, 
135245   int idxNum, const char *idxStr,
135246   int argc, sqlite3_value **argv
135247 ){
135248   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
135249   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
135250
135251   RtreeNode *pRoot = 0;
135252   int ii;
135253   int rc = SQLITE_OK;
135254
135255   rtreeReference(pRtree);
135256
135257   freeCursorConstraints(pCsr);
135258   pCsr->iStrategy = idxNum;
135259
135260   if( idxNum==1 ){
135261     /* Special case - lookup by rowid. */
135262     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
135263     i64 iRowid = sqlite3_value_int64(argv[0]);
135264     rc = findLeafNode(pRtree, iRowid, &pLeaf);
135265     pCsr->pNode = pLeaf; 
135266     if( pLeaf ){
135267       assert( rc==SQLITE_OK );
135268       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
135269     }
135270   }else{
135271     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
135272     ** with the configured constraints. 
135273     */
135274     if( argc>0 ){
135275       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
135276       pCsr->nConstraint = argc;
135277       if( !pCsr->aConstraint ){
135278         rc = SQLITE_NOMEM;
135279       }else{
135280         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
135281         assert( (idxStr==0 && argc==0)
135282                 || (idxStr && (int)strlen(idxStr)==argc*2) );
135283         for(ii=0; ii<argc; ii++){
135284           RtreeConstraint *p = &pCsr->aConstraint[ii];
135285           p->op = idxStr[ii*2];
135286           p->iCoord = idxStr[ii*2+1]-'a';
135287           if( p->op==RTREE_MATCH ){
135288             /* A MATCH operator. The right-hand-side must be a blob that
135289             ** can be cast into an RtreeMatchArg object. One created using
135290             ** an sqlite3_rtree_geometry_callback() SQL user function.
135291             */
135292             rc = deserializeGeometry(argv[ii], p);
135293             if( rc!=SQLITE_OK ){
135294               break;
135295             }
135296           }else{
135297 #ifdef SQLITE_RTREE_INT_ONLY
135298             p->rValue = sqlite3_value_int64(argv[ii]);
135299 #else
135300             p->rValue = sqlite3_value_double(argv[ii]);
135301 #endif
135302           }
135303         }
135304       }
135305     }
135306   
135307     if( rc==SQLITE_OK ){
135308       pCsr->pNode = 0;
135309       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
135310     }
135311     if( rc==SQLITE_OK ){
135312       int isEof = 1;
135313       int nCell = NCELL(pRoot);
135314       pCsr->pNode = pRoot;
135315       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
135316         assert( pCsr->pNode==pRoot );
135317         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
135318         if( !isEof ){
135319           break;
135320         }
135321       }
135322       if( rc==SQLITE_OK && isEof ){
135323         assert( pCsr->pNode==pRoot );
135324         nodeRelease(pRtree, pRoot);
135325         pCsr->pNode = 0;
135326       }
135327       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
135328     }
135329   }
135330
135331   rtreeRelease(pRtree);
135332   return rc;
135333 }
135334
135335 /*
135336 ** Rtree virtual table module xBestIndex method. There are three
135337 ** table scan strategies to choose from (in order from most to 
135338 ** least desirable):
135339 **
135340 **   idxNum     idxStr        Strategy
135341 **   ------------------------------------------------
135342 **     1        Unused        Direct lookup by rowid.
135343 **     2        See below     R-tree query or full-table scan.
135344 **   ------------------------------------------------
135345 **
135346 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
135347 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
135348 ** constraint used. The first two bytes of idxStr correspond to 
135349 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
135350 ** (argvIndex==1) etc.
135351 **
135352 ** The first of each pair of bytes in idxStr identifies the constraint
135353 ** operator as follows:
135354 **
135355 **   Operator    Byte Value
135356 **   ----------------------
135357 **      =        0x41 ('A')
135358 **     <=        0x42 ('B')
135359 **      <        0x43 ('C')
135360 **     >=        0x44 ('D')
135361 **      >        0x45 ('E')
135362 **   MATCH       0x46 ('F')
135363 **   ----------------------
135364 **
135365 ** The second of each pair of bytes identifies the coordinate column
135366 ** to which the constraint applies. The leftmost coordinate column
135367 ** is 'a', the second from the left 'b' etc.
135368 */
135369 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
135370   int rc = SQLITE_OK;
135371   int ii;
135372
135373   int iIdx = 0;
135374   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
135375   memset(zIdxStr, 0, sizeof(zIdxStr));
135376   UNUSED_PARAMETER(tab);
135377
135378   assert( pIdxInfo->idxStr==0 );
135379   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
135380     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
135381
135382     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
135383       /* We have an equality constraint on the rowid. Use strategy 1. */
135384       int jj;
135385       for(jj=0; jj<ii; jj++){
135386         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
135387         pIdxInfo->aConstraintUsage[jj].omit = 0;
135388       }
135389       pIdxInfo->idxNum = 1;
135390       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
135391       pIdxInfo->aConstraintUsage[jj].omit = 1;
135392
135393       /* This strategy involves a two rowid lookups on an B-Tree structures
135394       ** and then a linear search of an R-Tree node. This should be 
135395       ** considered almost as quick as a direct rowid lookup (for which 
135396       ** sqlite uses an internal cost of 0.0).
135397       */ 
135398       pIdxInfo->estimatedCost = 10.0;
135399       return SQLITE_OK;
135400     }
135401
135402     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
135403       u8 op;
135404       switch( p->op ){
135405         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
135406         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
135407         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
135408         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
135409         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
135410         default:
135411           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
135412           op = RTREE_MATCH; 
135413           break;
135414       }
135415       zIdxStr[iIdx++] = op;
135416       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
135417       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
135418       pIdxInfo->aConstraintUsage[ii].omit = 1;
135419     }
135420   }
135421
135422   pIdxInfo->idxNum = 2;
135423   pIdxInfo->needToFreeIdxStr = 1;
135424   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
135425     return SQLITE_NOMEM;
135426   }
135427   assert( iIdx>=0 );
135428   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
135429   return rc;
135430 }
135431
135432 /*
135433 ** Return the N-dimensional volumn of the cell stored in *p.
135434 */
135435 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
135436   RtreeDValue area = (RtreeDValue)1;
135437   int ii;
135438   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135439     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
135440   }
135441   return area;
135442 }
135443
135444 /*
135445 ** Return the margin length of cell p. The margin length is the sum
135446 ** of the objects size in each dimension.
135447 */
135448 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
135449   RtreeDValue margin = (RtreeDValue)0;
135450   int ii;
135451   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135452     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
135453   }
135454   return margin;
135455 }
135456
135457 /*
135458 ** Store the union of cells p1 and p2 in p1.
135459 */
135460 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
135461   int ii;
135462   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
135463     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135464       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
135465       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
135466     }
135467   }else{
135468     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135469       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
135470       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
135471     }
135472   }
135473 }
135474
135475 /*
135476 ** Return true if the area covered by p2 is a subset of the area covered
135477 ** by p1. False otherwise.
135478 */
135479 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
135480   int ii;
135481   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
135482   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135483     RtreeCoord *a1 = &p1->aCoord[ii];
135484     RtreeCoord *a2 = &p2->aCoord[ii];
135485     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
135486      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
135487     ){
135488       return 0;
135489     }
135490   }
135491   return 1;
135492 }
135493
135494 /*
135495 ** Return the amount cell p would grow by if it were unioned with pCell.
135496 */
135497 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
135498   RtreeDValue area;
135499   RtreeCell cell;
135500   memcpy(&cell, p, sizeof(RtreeCell));
135501   area = cellArea(pRtree, &cell);
135502   cellUnion(pRtree, &cell, pCell);
135503   return (cellArea(pRtree, &cell)-area);
135504 }
135505
135506 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
135507 static RtreeDValue cellOverlap(
135508   Rtree *pRtree, 
135509   RtreeCell *p, 
135510   RtreeCell *aCell, 
135511   int nCell, 
135512   int iExclude
135513 ){
135514   int ii;
135515   RtreeDValue overlap = 0.0;
135516   for(ii=0; ii<nCell; ii++){
135517 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135518     if( ii!=iExclude )
135519 #else
135520     assert( iExclude==-1 );
135521     UNUSED_PARAMETER(iExclude);
135522 #endif
135523     {
135524       int jj;
135525       RtreeDValue o = (RtreeDValue)1;
135526       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
135527         RtreeDValue x1, x2;
135528
135529         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
135530         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
135531
135532         if( x2<x1 ){
135533           o = 0.0;
135534           break;
135535         }else{
135536           o = o * (x2-x1);
135537         }
135538       }
135539       overlap += o;
135540     }
135541   }
135542   return overlap;
135543 }
135544 #endif
135545
135546 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135547 static RtreeDValue cellOverlapEnlargement(
135548   Rtree *pRtree, 
135549   RtreeCell *p, 
135550   RtreeCell *pInsert, 
135551   RtreeCell *aCell, 
135552   int nCell, 
135553   int iExclude
135554 ){
135555   RtreeDValue before, after;
135556   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
135557   cellUnion(pRtree, p, pInsert);
135558   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
135559   return (after-before);
135560 }
135561 #endif
135562
135563
135564 /*
135565 ** This function implements the ChooseLeaf algorithm from Gutman[84].
135566 ** ChooseSubTree in r*tree terminology.
135567 */
135568 static int ChooseLeaf(
135569   Rtree *pRtree,               /* Rtree table */
135570   RtreeCell *pCell,            /* Cell to insert into rtree */
135571   int iHeight,                 /* Height of sub-tree rooted at pCell */
135572   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
135573 ){
135574   int rc;
135575   int ii;
135576   RtreeNode *pNode;
135577   rc = nodeAcquire(pRtree, 1, 0, &pNode);
135578
135579   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
135580     int iCell;
135581     sqlite3_int64 iBest = 0;
135582
135583     RtreeDValue fMinGrowth = 0.0;
135584     RtreeDValue fMinArea = 0.0;
135585 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135586     RtreeDValue fMinOverlap = 0.0;
135587     RtreeDValue overlap;
135588 #endif
135589
135590     int nCell = NCELL(pNode);
135591     RtreeCell cell;
135592     RtreeNode *pChild;
135593
135594     RtreeCell *aCell = 0;
135595
135596 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135597     if( ii==(pRtree->iDepth-1) ){
135598       int jj;
135599       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
135600       if( !aCell ){
135601         rc = SQLITE_NOMEM;
135602         nodeRelease(pRtree, pNode);
135603         pNode = 0;
135604         continue;
135605       }
135606       for(jj=0; jj<nCell; jj++){
135607         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
135608       }
135609     }
135610 #endif
135611
135612     /* Select the child node which will be enlarged the least if pCell
135613     ** is inserted into it. Resolve ties by choosing the entry with
135614     ** the smallest area.
135615     */
135616     for(iCell=0; iCell<nCell; iCell++){
135617       int bBest = 0;
135618       RtreeDValue growth;
135619       RtreeDValue area;
135620       nodeGetCell(pRtree, pNode, iCell, &cell);
135621       growth = cellGrowth(pRtree, &cell, pCell);
135622       area = cellArea(pRtree, &cell);
135623
135624 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135625       if( ii==(pRtree->iDepth-1) ){
135626         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
135627       }else{
135628         overlap = 0.0;
135629       }
135630       if( (iCell==0) 
135631        || (overlap<fMinOverlap) 
135632        || (overlap==fMinOverlap && growth<fMinGrowth)
135633        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
135634       ){
135635         bBest = 1;
135636         fMinOverlap = overlap;
135637       }
135638 #else
135639       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
135640         bBest = 1;
135641       }
135642 #endif
135643       if( bBest ){
135644         fMinGrowth = growth;
135645         fMinArea = area;
135646         iBest = cell.iRowid;
135647       }
135648     }
135649
135650     sqlite3_free(aCell);
135651     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
135652     nodeRelease(pRtree, pNode);
135653     pNode = pChild;
135654   }
135655
135656   *ppLeaf = pNode;
135657   return rc;
135658 }
135659
135660 /*
135661 ** A cell with the same content as pCell has just been inserted into
135662 ** the node pNode. This function updates the bounding box cells in
135663 ** all ancestor elements.
135664 */
135665 static int AdjustTree(
135666   Rtree *pRtree,                    /* Rtree table */
135667   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
135668   RtreeCell *pCell                  /* This cell was just inserted */
135669 ){
135670   RtreeNode *p = pNode;
135671   while( p->pParent ){
135672     RtreeNode *pParent = p->pParent;
135673     RtreeCell cell;
135674     int iCell;
135675
135676     if( nodeParentIndex(pRtree, p, &iCell) ){
135677       return SQLITE_CORRUPT_VTAB;
135678     }
135679
135680     nodeGetCell(pRtree, pParent, iCell, &cell);
135681     if( !cellContains(pRtree, &cell, pCell) ){
135682       cellUnion(pRtree, &cell, pCell);
135683       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
135684     }
135685  
135686     p = pParent;
135687   }
135688   return SQLITE_OK;
135689 }
135690
135691 /*
135692 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
135693 */
135694 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
135695   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
135696   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
135697   sqlite3_step(pRtree->pWriteRowid);
135698   return sqlite3_reset(pRtree->pWriteRowid);
135699 }
135700
135701 /*
135702 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
135703 */
135704 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
135705   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
135706   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
135707   sqlite3_step(pRtree->pWriteParent);
135708   return sqlite3_reset(pRtree->pWriteParent);
135709 }
135710
135711 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
135712
135713 #if VARIANT_GUTTMAN_LINEAR_SPLIT
135714 /*
135715 ** Implementation of the linear variant of the PickNext() function from
135716 ** Guttman[84].
135717 */
135718 static RtreeCell *LinearPickNext(
135719   Rtree *pRtree,
135720   RtreeCell *aCell, 
135721   int nCell, 
135722   RtreeCell *pLeftBox, 
135723   RtreeCell *pRightBox,
135724   int *aiUsed
135725 ){
135726   int ii;
135727   for(ii=0; aiUsed[ii]; ii++);
135728   aiUsed[ii] = 1;
135729   return &aCell[ii];
135730 }
135731
135732 /*
135733 ** Implementation of the linear variant of the PickSeeds() function from
135734 ** Guttman[84].
135735 */
135736 static void LinearPickSeeds(
135737   Rtree *pRtree,
135738   RtreeCell *aCell, 
135739   int nCell, 
135740   int *piLeftSeed, 
135741   int *piRightSeed
135742 ){
135743   int i;
135744   int iLeftSeed = 0;
135745   int iRightSeed = 1;
135746   RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
135747
135748   /* Pick two "seed" cells from the array of cells. The algorithm used
135749   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
135750   ** indices of the two seed cells in the array are stored in local
135751   ** variables iLeftSeek and iRightSeed.
135752   */
135753   for(i=0; i<pRtree->nDim; i++){
135754     RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
135755     RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
135756     RtreeDValue x3 = x1;
135757     RtreeDValue x4 = x2;
135758     int jj;
135759
135760     int iCellLeft = 0;
135761     int iCellRight = 0;
135762
135763     for(jj=1; jj<nCell; jj++){
135764       RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
135765       RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
135766
135767       if( left<x1 ) x1 = left;
135768       if( right>x4 ) x4 = right;
135769       if( left>x3 ){
135770         x3 = left;
135771         iCellRight = jj;
135772       }
135773       if( right<x2 ){
135774         x2 = right;
135775         iCellLeft = jj;
135776       }
135777     }
135778
135779     if( x4!=x1 ){
135780       RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
135781       if( normalwidth>maxNormalInnerWidth ){
135782         iLeftSeed = iCellLeft;
135783         iRightSeed = iCellRight;
135784       }
135785     }
135786   }
135787
135788   *piLeftSeed = iLeftSeed;
135789   *piRightSeed = iRightSeed;
135790 }
135791 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
135792
135793 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
135794 /*
135795 ** Implementation of the quadratic variant of the PickNext() function from
135796 ** Guttman[84].
135797 */
135798 static RtreeCell *QuadraticPickNext(
135799   Rtree *pRtree,
135800   RtreeCell *aCell, 
135801   int nCell, 
135802   RtreeCell *pLeftBox, 
135803   RtreeCell *pRightBox,
135804   int *aiUsed
135805 ){
135806   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
135807
135808   int iSelect = -1;
135809   RtreeDValue fDiff;
135810   int ii;
135811   for(ii=0; ii<nCell; ii++){
135812     if( aiUsed[ii]==0 ){
135813       RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
135814       RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
135815       RtreeDValue diff = FABS(right-left);
135816       if( iSelect<0 || diff>fDiff ){
135817         fDiff = diff;
135818         iSelect = ii;
135819       }
135820     }
135821   }
135822   aiUsed[iSelect] = 1;
135823   return &aCell[iSelect];
135824 }
135825
135826 /*
135827 ** Implementation of the quadratic variant of the PickSeeds() function from
135828 ** Guttman[84].
135829 */
135830 static void QuadraticPickSeeds(
135831   Rtree *pRtree,
135832   RtreeCell *aCell, 
135833   int nCell, 
135834   int *piLeftSeed, 
135835   int *piRightSeed
135836 ){
135837   int ii;
135838   int jj;
135839
135840   int iLeftSeed = 0;
135841   int iRightSeed = 1;
135842   RtreeDValue fWaste = 0.0;
135843
135844   for(ii=0; ii<nCell; ii++){
135845     for(jj=ii+1; jj<nCell; jj++){
135846       RtreeDValue right = cellArea(pRtree, &aCell[jj]);
135847       RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
135848       RtreeDValue waste = growth - right;
135849
135850       if( waste>fWaste ){
135851         iLeftSeed = ii;
135852         iRightSeed = jj;
135853         fWaste = waste;
135854       }
135855     }
135856   }
135857
135858   *piLeftSeed = iLeftSeed;
135859   *piRightSeed = iRightSeed;
135860 }
135861 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
135862
135863 /*
135864 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
135865 ** nIdx. The aIdx array contains the set of integers from 0 to 
135866 ** (nIdx-1) in no particular order. This function sorts the values
135867 ** in aIdx according to the indexed values in aDistance. For
135868 ** example, assuming the inputs:
135869 **
135870 **   aIdx      = { 0,   1,   2,   3 }
135871 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
135872 **
135873 ** this function sets the aIdx array to contain:
135874 **
135875 **   aIdx      = { 0,   1,   2,   3 }
135876 **
135877 ** The aSpare array is used as temporary working space by the
135878 ** sorting algorithm.
135879 */
135880 static void SortByDistance(
135881   int *aIdx, 
135882   int nIdx, 
135883   RtreeDValue *aDistance, 
135884   int *aSpare
135885 ){
135886   if( nIdx>1 ){
135887     int iLeft = 0;
135888     int iRight = 0;
135889
135890     int nLeft = nIdx/2;
135891     int nRight = nIdx-nLeft;
135892     int *aLeft = aIdx;
135893     int *aRight = &aIdx[nLeft];
135894
135895     SortByDistance(aLeft, nLeft, aDistance, aSpare);
135896     SortByDistance(aRight, nRight, aDistance, aSpare);
135897
135898     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
135899     aLeft = aSpare;
135900
135901     while( iLeft<nLeft || iRight<nRight ){
135902       if( iLeft==nLeft ){
135903         aIdx[iLeft+iRight] = aRight[iRight];
135904         iRight++;
135905       }else if( iRight==nRight ){
135906         aIdx[iLeft+iRight] = aLeft[iLeft];
135907         iLeft++;
135908       }else{
135909         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
135910         RtreeDValue fRight = aDistance[aRight[iRight]];
135911         if( fLeft<fRight ){
135912           aIdx[iLeft+iRight] = aLeft[iLeft];
135913           iLeft++;
135914         }else{
135915           aIdx[iLeft+iRight] = aRight[iRight];
135916           iRight++;
135917         }
135918       }
135919     }
135920
135921 #if 0
135922     /* Check that the sort worked */
135923     {
135924       int jj;
135925       for(jj=1; jj<nIdx; jj++){
135926         RtreeDValue left = aDistance[aIdx[jj-1]];
135927         RtreeDValue right = aDistance[aIdx[jj]];
135928         assert( left<=right );
135929       }
135930     }
135931 #endif
135932   }
135933 }
135934
135935 /*
135936 ** Arguments aIdx, aCell and aSpare all point to arrays of size
135937 ** nIdx. The aIdx array contains the set of integers from 0 to 
135938 ** (nIdx-1) in no particular order. This function sorts the values
135939 ** in aIdx according to dimension iDim of the cells in aCell. The
135940 ** minimum value of dimension iDim is considered first, the
135941 ** maximum used to break ties.
135942 **
135943 ** The aSpare array is used as temporary working space by the
135944 ** sorting algorithm.
135945 */
135946 static void SortByDimension(
135947   Rtree *pRtree,
135948   int *aIdx, 
135949   int nIdx, 
135950   int iDim, 
135951   RtreeCell *aCell, 
135952   int *aSpare
135953 ){
135954   if( nIdx>1 ){
135955
135956     int iLeft = 0;
135957     int iRight = 0;
135958
135959     int nLeft = nIdx/2;
135960     int nRight = nIdx-nLeft;
135961     int *aLeft = aIdx;
135962     int *aRight = &aIdx[nLeft];
135963
135964     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
135965     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
135966
135967     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
135968     aLeft = aSpare;
135969     while( iLeft<nLeft || iRight<nRight ){
135970       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
135971       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
135972       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
135973       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
135974       if( (iLeft!=nLeft) && ((iRight==nRight)
135975        || (xleft1<xright1)
135976        || (xleft1==xright1 && xleft2<xright2)
135977       )){
135978         aIdx[iLeft+iRight] = aLeft[iLeft];
135979         iLeft++;
135980       }else{
135981         aIdx[iLeft+iRight] = aRight[iRight];
135982         iRight++;
135983       }
135984     }
135985
135986 #if 0
135987     /* Check that the sort worked */
135988     {
135989       int jj;
135990       for(jj=1; jj<nIdx; jj++){
135991         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
135992         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
135993         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
135994         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
135995         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
135996       }
135997     }
135998 #endif
135999   }
136000 }
136001
136002 #if VARIANT_RSTARTREE_SPLIT
136003 /*
136004 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
136005 */
136006 static int splitNodeStartree(
136007   Rtree *pRtree,
136008   RtreeCell *aCell,
136009   int nCell,
136010   RtreeNode *pLeft,
136011   RtreeNode *pRight,
136012   RtreeCell *pBboxLeft,
136013   RtreeCell *pBboxRight
136014 ){
136015   int **aaSorted;
136016   int *aSpare;
136017   int ii;
136018
136019   int iBestDim = 0;
136020   int iBestSplit = 0;
136021   RtreeDValue fBestMargin = 0.0;
136022
136023   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
136024
136025   aaSorted = (int **)sqlite3_malloc(nByte);
136026   if( !aaSorted ){
136027     return SQLITE_NOMEM;
136028   }
136029
136030   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
136031   memset(aaSorted, 0, nByte);
136032   for(ii=0; ii<pRtree->nDim; ii++){
136033     int jj;
136034     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
136035     for(jj=0; jj<nCell; jj++){
136036       aaSorted[ii][jj] = jj;
136037     }
136038     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
136039   }
136040
136041   for(ii=0; ii<pRtree->nDim; ii++){
136042     RtreeDValue margin = 0.0;
136043     RtreeDValue fBestOverlap = 0.0;
136044     RtreeDValue fBestArea = 0.0;
136045     int iBestLeft = 0;
136046     int nLeft;
136047
136048     for(
136049       nLeft=RTREE_MINCELLS(pRtree); 
136050       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
136051       nLeft++
136052     ){
136053       RtreeCell left;
136054       RtreeCell right;
136055       int kk;
136056       RtreeDValue overlap;
136057       RtreeDValue area;
136058
136059       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
136060       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
136061       for(kk=1; kk<(nCell-1); kk++){
136062         if( kk<nLeft ){
136063           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
136064         }else{
136065           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
136066         }
136067       }
136068       margin += cellMargin(pRtree, &left);
136069       margin += cellMargin(pRtree, &right);
136070       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
136071       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
136072       if( (nLeft==RTREE_MINCELLS(pRtree))
136073        || (overlap<fBestOverlap)
136074        || (overlap==fBestOverlap && area<fBestArea)
136075       ){
136076         iBestLeft = nLeft;
136077         fBestOverlap = overlap;
136078         fBestArea = area;
136079       }
136080     }
136081
136082     if( ii==0 || margin<fBestMargin ){
136083       iBestDim = ii;
136084       fBestMargin = margin;
136085       iBestSplit = iBestLeft;
136086     }
136087   }
136088
136089   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
136090   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
136091   for(ii=0; ii<nCell; ii++){
136092     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
136093     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
136094     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
136095     nodeInsertCell(pRtree, pTarget, pCell);
136096     cellUnion(pRtree, pBbox, pCell);
136097   }
136098
136099   sqlite3_free(aaSorted);
136100   return SQLITE_OK;
136101 }
136102 #endif
136103
136104 #if VARIANT_GUTTMAN_SPLIT
136105 /*
136106 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
136107 */
136108 static int splitNodeGuttman(
136109   Rtree *pRtree,
136110   RtreeCell *aCell,
136111   int nCell,
136112   RtreeNode *pLeft,
136113   RtreeNode *pRight,
136114   RtreeCell *pBboxLeft,
136115   RtreeCell *pBboxRight
136116 ){
136117   int iLeftSeed = 0;
136118   int iRightSeed = 1;
136119   int *aiUsed;
136120   int i;
136121
136122   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
136123   if( !aiUsed ){
136124     return SQLITE_NOMEM;
136125   }
136126   memset(aiUsed, 0, sizeof(int)*nCell);
136127
136128   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
136129
136130   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
136131   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
136132   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
136133   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
136134   aiUsed[iLeftSeed] = 1;
136135   aiUsed[iRightSeed] = 1;
136136
136137   for(i=nCell-2; i>0; i--){
136138     RtreeCell *pNext;
136139     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
136140     RtreeDValue diff =  
136141       cellGrowth(pRtree, pBboxLeft, pNext) - 
136142       cellGrowth(pRtree, pBboxRight, pNext)
136143     ;
136144     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
136145      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
136146     ){
136147       nodeInsertCell(pRtree, pRight, pNext);
136148       cellUnion(pRtree, pBboxRight, pNext);
136149     }else{
136150       nodeInsertCell(pRtree, pLeft, pNext);
136151       cellUnion(pRtree, pBboxLeft, pNext);
136152     }
136153   }
136154
136155   sqlite3_free(aiUsed);
136156   return SQLITE_OK;
136157 }
136158 #endif
136159
136160 static int updateMapping(
136161   Rtree *pRtree, 
136162   i64 iRowid, 
136163   RtreeNode *pNode, 
136164   int iHeight
136165 ){
136166   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
136167   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
136168   if( iHeight>0 ){
136169     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
136170     if( pChild ){
136171       nodeRelease(pRtree, pChild->pParent);
136172       nodeReference(pNode);
136173       pChild->pParent = pNode;
136174     }
136175   }
136176   return xSetMapping(pRtree, iRowid, pNode->iNode);
136177 }
136178
136179 static int SplitNode(
136180   Rtree *pRtree,
136181   RtreeNode *pNode,
136182   RtreeCell *pCell,
136183   int iHeight
136184 ){
136185   int i;
136186   int newCellIsRight = 0;
136187
136188   int rc = SQLITE_OK;
136189   int nCell = NCELL(pNode);
136190   RtreeCell *aCell;
136191   int *aiUsed;
136192
136193   RtreeNode *pLeft = 0;
136194   RtreeNode *pRight = 0;
136195
136196   RtreeCell leftbbox;
136197   RtreeCell rightbbox;
136198
136199   /* Allocate an array and populate it with a copy of pCell and 
136200   ** all cells from node pLeft. Then zero the original node.
136201   */
136202   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
136203   if( !aCell ){
136204     rc = SQLITE_NOMEM;
136205     goto splitnode_out;
136206   }
136207   aiUsed = (int *)&aCell[nCell+1];
136208   memset(aiUsed, 0, sizeof(int)*(nCell+1));
136209   for(i=0; i<nCell; i++){
136210     nodeGetCell(pRtree, pNode, i, &aCell[i]);
136211   }
136212   nodeZero(pRtree, pNode);
136213   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
136214   nCell++;
136215
136216   if( pNode->iNode==1 ){
136217     pRight = nodeNew(pRtree, pNode);
136218     pLeft = nodeNew(pRtree, pNode);
136219     pRtree->iDepth++;
136220     pNode->isDirty = 1;
136221     writeInt16(pNode->zData, pRtree->iDepth);
136222   }else{
136223     pLeft = pNode;
136224     pRight = nodeNew(pRtree, pLeft->pParent);
136225     nodeReference(pLeft);
136226   }
136227
136228   if( !pLeft || !pRight ){
136229     rc = SQLITE_NOMEM;
136230     goto splitnode_out;
136231   }
136232
136233   memset(pLeft->zData, 0, pRtree->iNodeSize);
136234   memset(pRight->zData, 0, pRtree->iNodeSize);
136235
136236   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
136237   if( rc!=SQLITE_OK ){
136238     goto splitnode_out;
136239   }
136240
136241   /* Ensure both child nodes have node numbers assigned to them by calling
136242   ** nodeWrite(). Node pRight always needs a node number, as it was created
136243   ** by nodeNew() above. But node pLeft sometimes already has a node number.
136244   ** In this case avoid the all to nodeWrite().
136245   */
136246   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
136247    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
136248   ){
136249     goto splitnode_out;
136250   }
136251
136252   rightbbox.iRowid = pRight->iNode;
136253   leftbbox.iRowid = pLeft->iNode;
136254
136255   if( pNode->iNode==1 ){
136256     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
136257     if( rc!=SQLITE_OK ){
136258       goto splitnode_out;
136259     }
136260   }else{
136261     RtreeNode *pParent = pLeft->pParent;
136262     int iCell;
136263     rc = nodeParentIndex(pRtree, pLeft, &iCell);
136264     if( rc==SQLITE_OK ){
136265       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
136266       rc = AdjustTree(pRtree, pParent, &leftbbox);
136267     }
136268     if( rc!=SQLITE_OK ){
136269       goto splitnode_out;
136270     }
136271   }
136272   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
136273     goto splitnode_out;
136274   }
136275
136276   for(i=0; i<NCELL(pRight); i++){
136277     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
136278     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
136279     if( iRowid==pCell->iRowid ){
136280       newCellIsRight = 1;
136281     }
136282     if( rc!=SQLITE_OK ){
136283       goto splitnode_out;
136284     }
136285   }
136286   if( pNode->iNode==1 ){
136287     for(i=0; i<NCELL(pLeft); i++){
136288       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
136289       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
136290       if( rc!=SQLITE_OK ){
136291         goto splitnode_out;
136292       }
136293     }
136294   }else if( newCellIsRight==0 ){
136295     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
136296   }
136297
136298   if( rc==SQLITE_OK ){
136299     rc = nodeRelease(pRtree, pRight);
136300     pRight = 0;
136301   }
136302   if( rc==SQLITE_OK ){
136303     rc = nodeRelease(pRtree, pLeft);
136304     pLeft = 0;
136305   }
136306
136307 splitnode_out:
136308   nodeRelease(pRtree, pRight);
136309   nodeRelease(pRtree, pLeft);
136310   sqlite3_free(aCell);
136311   return rc;
136312 }
136313
136314 /*
136315 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
136316 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
136317 ** the pLeaf->pParent chain all the way up to the root node.
136318 **
136319 ** This operation is required when a row is deleted (or updated - an update
136320 ** is implemented as a delete followed by an insert). SQLite provides the
136321 ** rowid of the row to delete, which can be used to find the leaf on which
136322 ** the entry resides (argument pLeaf). Once the leaf is located, this 
136323 ** function is called to determine its ancestry.
136324 */
136325 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
136326   int rc = SQLITE_OK;
136327   RtreeNode *pChild = pLeaf;
136328   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
136329     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
136330     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
136331     rc = sqlite3_step(pRtree->pReadParent);
136332     if( rc==SQLITE_ROW ){
136333       RtreeNode *pTest;           /* Used to test for reference loops */
136334       i64 iNode;                  /* Node number of parent node */
136335
136336       /* Before setting pChild->pParent, test that we are not creating a
136337       ** loop of references (as we would if, say, pChild==pParent). We don't
136338       ** want to do this as it leads to a memory leak when trying to delete
136339       ** the referenced counted node structures.
136340       */
136341       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
136342       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
136343       if( !pTest ){
136344         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
136345       }
136346     }
136347     rc = sqlite3_reset(pRtree->pReadParent);
136348     if( rc==SQLITE_OK ) rc = rc2;
136349     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
136350     pChild = pChild->pParent;
136351   }
136352   return rc;
136353 }
136354
136355 static int deleteCell(Rtree *, RtreeNode *, int, int);
136356
136357 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
136358   int rc;
136359   int rc2;
136360   RtreeNode *pParent = 0;
136361   int iCell;
136362
136363   assert( pNode->nRef==1 );
136364
136365   /* Remove the entry in the parent cell. */
136366   rc = nodeParentIndex(pRtree, pNode, &iCell);
136367   if( rc==SQLITE_OK ){
136368     pParent = pNode->pParent;
136369     pNode->pParent = 0;
136370     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
136371   }
136372   rc2 = nodeRelease(pRtree, pParent);
136373   if( rc==SQLITE_OK ){
136374     rc = rc2;
136375   }
136376   if( rc!=SQLITE_OK ){
136377     return rc;
136378   }
136379
136380   /* Remove the xxx_node entry. */
136381   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
136382   sqlite3_step(pRtree->pDeleteNode);
136383   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
136384     return rc;
136385   }
136386
136387   /* Remove the xxx_parent entry. */
136388   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
136389   sqlite3_step(pRtree->pDeleteParent);
136390   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
136391     return rc;
136392   }
136393   
136394   /* Remove the node from the in-memory hash table and link it into
136395   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
136396   */
136397   nodeHashDelete(pRtree, pNode);
136398   pNode->iNode = iHeight;
136399   pNode->pNext = pRtree->pDeleted;
136400   pNode->nRef++;
136401   pRtree->pDeleted = pNode;
136402
136403   return SQLITE_OK;
136404 }
136405
136406 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
136407   RtreeNode *pParent = pNode->pParent;
136408   int rc = SQLITE_OK; 
136409   if( pParent ){
136410     int ii; 
136411     int nCell = NCELL(pNode);
136412     RtreeCell box;                            /* Bounding box for pNode */
136413     nodeGetCell(pRtree, pNode, 0, &box);
136414     for(ii=1; ii<nCell; ii++){
136415       RtreeCell cell;
136416       nodeGetCell(pRtree, pNode, ii, &cell);
136417       cellUnion(pRtree, &box, &cell);
136418     }
136419     box.iRowid = pNode->iNode;
136420     rc = nodeParentIndex(pRtree, pNode, &ii);
136421     if( rc==SQLITE_OK ){
136422       nodeOverwriteCell(pRtree, pParent, &box, ii);
136423       rc = fixBoundingBox(pRtree, pParent);
136424     }
136425   }
136426   return rc;
136427 }
136428
136429 /*
136430 ** Delete the cell at index iCell of node pNode. After removing the
136431 ** cell, adjust the r-tree data structure if required.
136432 */
136433 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
136434   RtreeNode *pParent;
136435   int rc;
136436
136437   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
136438     return rc;
136439   }
136440
136441   /* Remove the cell from the node. This call just moves bytes around
136442   ** the in-memory node image, so it cannot fail.
136443   */
136444   nodeDeleteCell(pRtree, pNode, iCell);
136445
136446   /* If the node is not the tree root and now has less than the minimum
136447   ** number of cells, remove it from the tree. Otherwise, update the
136448   ** cell in the parent node so that it tightly contains the updated
136449   ** node.
136450   */
136451   pParent = pNode->pParent;
136452   assert( pParent || pNode->iNode==1 );
136453   if( pParent ){
136454     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
136455       rc = removeNode(pRtree, pNode, iHeight);
136456     }else{
136457       rc = fixBoundingBox(pRtree, pNode);
136458     }
136459   }
136460
136461   return rc;
136462 }
136463
136464 static int Reinsert(
136465   Rtree *pRtree, 
136466   RtreeNode *pNode, 
136467   RtreeCell *pCell, 
136468   int iHeight
136469 ){
136470   int *aOrder;
136471   int *aSpare;
136472   RtreeCell *aCell;
136473   RtreeDValue *aDistance;
136474   int nCell;
136475   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
136476   int iDim;
136477   int ii;
136478   int rc = SQLITE_OK;
136479   int n;
136480
136481   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
136482
136483   nCell = NCELL(pNode)+1;
136484   n = (nCell+1)&(~1);
136485
136486   /* Allocate the buffers used by this operation. The allocation is
136487   ** relinquished before this function returns.
136488   */
136489   aCell = (RtreeCell *)sqlite3_malloc(n * (
136490     sizeof(RtreeCell)     +         /* aCell array */
136491     sizeof(int)           +         /* aOrder array */
136492     sizeof(int)           +         /* aSpare array */
136493     sizeof(RtreeDValue)             /* aDistance array */
136494   ));
136495   if( !aCell ){
136496     return SQLITE_NOMEM;
136497   }
136498   aOrder    = (int *)&aCell[n];
136499   aSpare    = (int *)&aOrder[n];
136500   aDistance = (RtreeDValue *)&aSpare[n];
136501
136502   for(ii=0; ii<nCell; ii++){
136503     if( ii==(nCell-1) ){
136504       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
136505     }else{
136506       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
136507     }
136508     aOrder[ii] = ii;
136509     for(iDim=0; iDim<pRtree->nDim; iDim++){
136510       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
136511       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
136512     }
136513   }
136514   for(iDim=0; iDim<pRtree->nDim; iDim++){
136515     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
136516   }
136517
136518   for(ii=0; ii<nCell; ii++){
136519     aDistance[ii] = 0.0;
136520     for(iDim=0; iDim<pRtree->nDim; iDim++){
136521       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
136522                                DCOORD(aCell[ii].aCoord[iDim*2]));
136523       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
136524     }
136525   }
136526
136527   SortByDistance(aOrder, nCell, aDistance, aSpare);
136528   nodeZero(pRtree, pNode);
136529
136530   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
136531     RtreeCell *p = &aCell[aOrder[ii]];
136532     nodeInsertCell(pRtree, pNode, p);
136533     if( p->iRowid==pCell->iRowid ){
136534       if( iHeight==0 ){
136535         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
136536       }else{
136537         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
136538       }
136539     }
136540   }
136541   if( rc==SQLITE_OK ){
136542     rc = fixBoundingBox(pRtree, pNode);
136543   }
136544   for(; rc==SQLITE_OK && ii<nCell; ii++){
136545     /* Find a node to store this cell in. pNode->iNode currently contains
136546     ** the height of the sub-tree headed by the cell.
136547     */
136548     RtreeNode *pInsert;
136549     RtreeCell *p = &aCell[aOrder[ii]];
136550     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
136551     if( rc==SQLITE_OK ){
136552       int rc2;
136553       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
136554       rc2 = nodeRelease(pRtree, pInsert);
136555       if( rc==SQLITE_OK ){
136556         rc = rc2;
136557       }
136558     }
136559   }
136560
136561   sqlite3_free(aCell);
136562   return rc;
136563 }
136564
136565 /*
136566 ** Insert cell pCell into node pNode. Node pNode is the head of a 
136567 ** subtree iHeight high (leaf nodes have iHeight==0).
136568 */
136569 static int rtreeInsertCell(
136570   Rtree *pRtree,
136571   RtreeNode *pNode,
136572   RtreeCell *pCell,
136573   int iHeight
136574 ){
136575   int rc = SQLITE_OK;
136576   if( iHeight>0 ){
136577     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
136578     if( pChild ){
136579       nodeRelease(pRtree, pChild->pParent);
136580       nodeReference(pNode);
136581       pChild->pParent = pNode;
136582     }
136583   }
136584   if( nodeInsertCell(pRtree, pNode, pCell) ){
136585 #if VARIANT_RSTARTREE_REINSERT
136586     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
136587       rc = SplitNode(pRtree, pNode, pCell, iHeight);
136588     }else{
136589       pRtree->iReinsertHeight = iHeight;
136590       rc = Reinsert(pRtree, pNode, pCell, iHeight);
136591     }
136592 #else
136593     rc = SplitNode(pRtree, pNode, pCell, iHeight);
136594 #endif
136595   }else{
136596     rc = AdjustTree(pRtree, pNode, pCell);
136597     if( rc==SQLITE_OK ){
136598       if( iHeight==0 ){
136599         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
136600       }else{
136601         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
136602       }
136603     }
136604   }
136605   return rc;
136606 }
136607
136608 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
136609   int ii;
136610   int rc = SQLITE_OK;
136611   int nCell = NCELL(pNode);
136612
136613   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
136614     RtreeNode *pInsert;
136615     RtreeCell cell;
136616     nodeGetCell(pRtree, pNode, ii, &cell);
136617
136618     /* Find a node to store this cell in. pNode->iNode currently contains
136619     ** the height of the sub-tree headed by the cell.
136620     */
136621     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
136622     if( rc==SQLITE_OK ){
136623       int rc2;
136624       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
136625       rc2 = nodeRelease(pRtree, pInsert);
136626       if( rc==SQLITE_OK ){
136627         rc = rc2;
136628       }
136629     }
136630   }
136631   return rc;
136632 }
136633
136634 /*
136635 ** Select a currently unused rowid for a new r-tree record.
136636 */
136637 static int newRowid(Rtree *pRtree, i64 *piRowid){
136638   int rc;
136639   sqlite3_bind_null(pRtree->pWriteRowid, 1);
136640   sqlite3_bind_null(pRtree->pWriteRowid, 2);
136641   sqlite3_step(pRtree->pWriteRowid);
136642   rc = sqlite3_reset(pRtree->pWriteRowid);
136643   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
136644   return rc;
136645 }
136646
136647 /*
136648 ** Remove the entry with rowid=iDelete from the r-tree structure.
136649 */
136650 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
136651   int rc;                         /* Return code */
136652   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
136653   int iCell;                      /* Index of iDelete cell in pLeaf */
136654   RtreeNode *pRoot;               /* Root node of rtree structure */
136655
136656
136657   /* Obtain a reference to the root node to initialize Rtree.iDepth */
136658   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
136659
136660   /* Obtain a reference to the leaf node that contains the entry 
136661   ** about to be deleted. 
136662   */
136663   if( rc==SQLITE_OK ){
136664     rc = findLeafNode(pRtree, iDelete, &pLeaf);
136665   }
136666
136667   /* Delete the cell in question from the leaf node. */
136668   if( rc==SQLITE_OK ){
136669     int rc2;
136670     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
136671     if( rc==SQLITE_OK ){
136672       rc = deleteCell(pRtree, pLeaf, iCell, 0);
136673     }
136674     rc2 = nodeRelease(pRtree, pLeaf);
136675     if( rc==SQLITE_OK ){
136676       rc = rc2;
136677     }
136678   }
136679
136680   /* Delete the corresponding entry in the <rtree>_rowid table. */
136681   if( rc==SQLITE_OK ){
136682     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
136683     sqlite3_step(pRtree->pDeleteRowid);
136684     rc = sqlite3_reset(pRtree->pDeleteRowid);
136685   }
136686
136687   /* Check if the root node now has exactly one child. If so, remove
136688   ** it, schedule the contents of the child for reinsertion and 
136689   ** reduce the tree height by one.
136690   **
136691   ** This is equivalent to copying the contents of the child into
136692   ** the root node (the operation that Gutman's paper says to perform 
136693   ** in this scenario).
136694   */
136695   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
136696     int rc2;
136697     RtreeNode *pChild;
136698     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
136699     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
136700     if( rc==SQLITE_OK ){
136701       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
136702     }
136703     rc2 = nodeRelease(pRtree, pChild);
136704     if( rc==SQLITE_OK ) rc = rc2;
136705     if( rc==SQLITE_OK ){
136706       pRtree->iDepth--;
136707       writeInt16(pRoot->zData, pRtree->iDepth);
136708       pRoot->isDirty = 1;
136709     }
136710   }
136711
136712   /* Re-insert the contents of any underfull nodes removed from the tree. */
136713   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
136714     if( rc==SQLITE_OK ){
136715       rc = reinsertNodeContent(pRtree, pLeaf);
136716     }
136717     pRtree->pDeleted = pLeaf->pNext;
136718     sqlite3_free(pLeaf);
136719   }
136720
136721   /* Release the reference to the root node. */
136722   if( rc==SQLITE_OK ){
136723     rc = nodeRelease(pRtree, pRoot);
136724   }else{
136725     nodeRelease(pRtree, pRoot);
136726   }
136727
136728   return rc;
136729 }
136730
136731 /*
136732 ** Rounding constants for float->double conversion.
136733 */
136734 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
136735 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
136736
136737 #if !defined(SQLITE_RTREE_INT_ONLY)
136738 /*
136739 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
136740 ** while taking care to round toward negative or positive, respectively.
136741 */
136742 static RtreeValue rtreeValueDown(sqlite3_value *v){
136743   double d = sqlite3_value_double(v);
136744   float f = (float)d;
136745   if( f>d ){
136746     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
136747   }
136748   return f;
136749 }
136750 static RtreeValue rtreeValueUp(sqlite3_value *v){
136751   double d = sqlite3_value_double(v);
136752   float f = (float)d;
136753   if( f<d ){
136754     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
136755   }
136756   return f;
136757 }
136758 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
136759
136760
136761 /*
136762 ** The xUpdate method for rtree module virtual tables.
136763 */
136764 static int rtreeUpdate(
136765   sqlite3_vtab *pVtab, 
136766   int nData, 
136767   sqlite3_value **azData, 
136768   sqlite_int64 *pRowid
136769 ){
136770   Rtree *pRtree = (Rtree *)pVtab;
136771   int rc = SQLITE_OK;
136772   RtreeCell cell;                 /* New cell to insert if nData>1 */
136773   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
136774
136775   rtreeReference(pRtree);
136776   assert(nData>=1);
136777
136778   /* Constraint handling. A write operation on an r-tree table may return
136779   ** SQLITE_CONSTRAINT for two reasons:
136780   **
136781   **   1. A duplicate rowid value, or
136782   **   2. The supplied data violates the "x2>=x1" constraint.
136783   **
136784   ** In the first case, if the conflict-handling mode is REPLACE, then
136785   ** the conflicting row can be removed before proceeding. In the second
136786   ** case, SQLITE_CONSTRAINT must be returned regardless of the
136787   ** conflict-handling mode specified by the user.
136788   */
136789   if( nData>1 ){
136790     int ii;
136791
136792     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
136793     assert( nData==(pRtree->nDim*2 + 3) );
136794 #ifndef SQLITE_RTREE_INT_ONLY
136795     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
136796       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136797         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
136798         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
136799         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
136800           rc = SQLITE_CONSTRAINT;
136801           goto constraint;
136802         }
136803       }
136804     }else
136805 #endif
136806     {
136807       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136808         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
136809         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
136810         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
136811           rc = SQLITE_CONSTRAINT;
136812           goto constraint;
136813         }
136814       }
136815     }
136816
136817     /* If a rowid value was supplied, check if it is already present in 
136818     ** the table. If so, the constraint has failed. */
136819     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
136820       cell.iRowid = sqlite3_value_int64(azData[2]);
136821       if( sqlite3_value_type(azData[0])==SQLITE_NULL
136822        || sqlite3_value_int64(azData[0])!=cell.iRowid
136823       ){
136824         int steprc;
136825         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
136826         steprc = sqlite3_step(pRtree->pReadRowid);
136827         rc = sqlite3_reset(pRtree->pReadRowid);
136828         if( SQLITE_ROW==steprc ){
136829           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
136830             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
136831           }else{
136832             rc = SQLITE_CONSTRAINT;
136833             goto constraint;
136834           }
136835         }
136836       }
136837       bHaveRowid = 1;
136838     }
136839   }
136840
136841   /* If azData[0] is not an SQL NULL value, it is the rowid of a
136842   ** record to delete from the r-tree table. The following block does
136843   ** just that.
136844   */
136845   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
136846     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
136847   }
136848
136849   /* If the azData[] array contains more than one element, elements
136850   ** (azData[2]..azData[argc-1]) contain a new record to insert into
136851   ** the r-tree structure.
136852   */
136853   if( rc==SQLITE_OK && nData>1 ){
136854     /* Insert the new record into the r-tree */
136855     RtreeNode *pLeaf = 0;
136856
136857     /* Figure out the rowid of the new row. */
136858     if( bHaveRowid==0 ){
136859       rc = newRowid(pRtree, &cell.iRowid);
136860     }
136861     *pRowid = cell.iRowid;
136862
136863     if( rc==SQLITE_OK ){
136864       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
136865     }
136866     if( rc==SQLITE_OK ){
136867       int rc2;
136868       pRtree->iReinsertHeight = -1;
136869       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
136870       rc2 = nodeRelease(pRtree, pLeaf);
136871       if( rc==SQLITE_OK ){
136872         rc = rc2;
136873       }
136874     }
136875   }
136876
136877 constraint:
136878   rtreeRelease(pRtree);
136879   return rc;
136880 }
136881
136882 /*
136883 ** The xRename method for rtree module virtual tables.
136884 */
136885 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
136886   Rtree *pRtree = (Rtree *)pVtab;
136887   int rc = SQLITE_NOMEM;
136888   char *zSql = sqlite3_mprintf(
136889     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
136890     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
136891     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
136892     , pRtree->zDb, pRtree->zName, zNewName 
136893     , pRtree->zDb, pRtree->zName, zNewName 
136894     , pRtree->zDb, pRtree->zName, zNewName
136895   );
136896   if( zSql ){
136897     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
136898     sqlite3_free(zSql);
136899   }
136900   return rc;
136901 }
136902
136903 static sqlite3_module rtreeModule = {
136904   0,                          /* iVersion */
136905   rtreeCreate,                /* xCreate - create a table */
136906   rtreeConnect,               /* xConnect - connect to an existing table */
136907   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
136908   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
136909   rtreeDestroy,               /* xDestroy - Drop a table */
136910   rtreeOpen,                  /* xOpen - open a cursor */
136911   rtreeClose,                 /* xClose - close a cursor */
136912   rtreeFilter,                /* xFilter - configure scan constraints */
136913   rtreeNext,                  /* xNext - advance a cursor */
136914   rtreeEof,                   /* xEof */
136915   rtreeColumn,                /* xColumn - read data */
136916   rtreeRowid,                 /* xRowid - read data */
136917   rtreeUpdate,                /* xUpdate - write data */
136918   0,                          /* xBegin - begin transaction */
136919   0,                          /* xSync - sync transaction */
136920   0,                          /* xCommit - commit transaction */
136921   0,                          /* xRollback - rollback transaction */
136922   0,                          /* xFindFunction - function overloading */
136923   rtreeRename,                /* xRename - rename the table */
136924   0,                          /* xSavepoint */
136925   0,                          /* xRelease */
136926   0                           /* xRollbackTo */
136927 };
136928
136929 static int rtreeSqlInit(
136930   Rtree *pRtree, 
136931   sqlite3 *db, 
136932   const char *zDb, 
136933   const char *zPrefix, 
136934   int isCreate
136935 ){
136936   int rc = SQLITE_OK;
136937
136938   #define N_STATEMENT 9
136939   static const char *azSql[N_STATEMENT] = {
136940     /* Read and write the xxx_node table */
136941     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
136942     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
136943     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
136944
136945     /* Read and write the xxx_rowid table */
136946     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
136947     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
136948     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
136949
136950     /* Read and write the xxx_parent table */
136951     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
136952     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
136953     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
136954   };
136955   sqlite3_stmt **appStmt[N_STATEMENT];
136956   int i;
136957
136958   pRtree->db = db;
136959
136960   if( isCreate ){
136961     char *zCreate = sqlite3_mprintf(
136962 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
136963 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
136964 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
136965 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
136966       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
136967     );
136968     if( !zCreate ){
136969       return SQLITE_NOMEM;
136970     }
136971     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
136972     sqlite3_free(zCreate);
136973     if( rc!=SQLITE_OK ){
136974       return rc;
136975     }
136976   }
136977
136978   appStmt[0] = &pRtree->pReadNode;
136979   appStmt[1] = &pRtree->pWriteNode;
136980   appStmt[2] = &pRtree->pDeleteNode;
136981   appStmt[3] = &pRtree->pReadRowid;
136982   appStmt[4] = &pRtree->pWriteRowid;
136983   appStmt[5] = &pRtree->pDeleteRowid;
136984   appStmt[6] = &pRtree->pReadParent;
136985   appStmt[7] = &pRtree->pWriteParent;
136986   appStmt[8] = &pRtree->pDeleteParent;
136987
136988   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
136989     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
136990     if( zSql ){
136991       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
136992     }else{
136993       rc = SQLITE_NOMEM;
136994     }
136995     sqlite3_free(zSql);
136996   }
136997
136998   return rc;
136999 }
137000
137001 /*
137002 ** The second argument to this function contains the text of an SQL statement
137003 ** that returns a single integer value. The statement is compiled and executed
137004 ** using database connection db. If successful, the integer value returned
137005 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
137006 ** code is returned and the value of *piVal after returning is not defined.
137007 */
137008 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
137009   int rc = SQLITE_NOMEM;
137010   if( zSql ){
137011     sqlite3_stmt *pStmt = 0;
137012     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
137013     if( rc==SQLITE_OK ){
137014       if( SQLITE_ROW==sqlite3_step(pStmt) ){
137015         *piVal = sqlite3_column_int(pStmt, 0);
137016       }
137017       rc = sqlite3_finalize(pStmt);
137018     }
137019   }
137020   return rc;
137021 }
137022
137023 /*
137024 ** This function is called from within the xConnect() or xCreate() method to
137025 ** determine the node-size used by the rtree table being created or connected
137026 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
137027 ** Otherwise, an SQLite error code is returned.
137028 **
137029 ** If this function is being called as part of an xConnect(), then the rtree
137030 ** table already exists. In this case the node-size is determined by inspecting
137031 ** the root node of the tree.
137032 **
137033 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
137034 ** This ensures that each node is stored on a single database page. If the 
137035 ** database page-size is so large that more than RTREE_MAXCELLS entries 
137036 ** would fit in a single node, use a smaller node-size.
137037 */
137038 static int getNodeSize(
137039   sqlite3 *db,                    /* Database handle */
137040   Rtree *pRtree,                  /* Rtree handle */
137041   int isCreate,                   /* True for xCreate, false for xConnect */
137042   char **pzErr                    /* OUT: Error message, if any */
137043 ){
137044   int rc;
137045   char *zSql;
137046   if( isCreate ){
137047     int iPageSize = 0;
137048     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
137049     rc = getIntFromStmt(db, zSql, &iPageSize);
137050     if( rc==SQLITE_OK ){
137051       pRtree->iNodeSize = iPageSize-64;
137052       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
137053         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
137054       }
137055     }else{
137056       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
137057     }
137058   }else{
137059     zSql = sqlite3_mprintf(
137060         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
137061         pRtree->zDb, pRtree->zName
137062     );
137063     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
137064     if( rc!=SQLITE_OK ){
137065       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
137066     }
137067   }
137068
137069   sqlite3_free(zSql);
137070   return rc;
137071 }
137072
137073 /* 
137074 ** This function is the implementation of both the xConnect and xCreate
137075 ** methods of the r-tree virtual table.
137076 **
137077 **   argv[0]   -> module name
137078 **   argv[1]   -> database name
137079 **   argv[2]   -> table name
137080 **   argv[...] -> column names...
137081 */
137082 static int rtreeInit(
137083   sqlite3 *db,                        /* Database connection */
137084   void *pAux,                         /* One of the RTREE_COORD_* constants */
137085   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
137086   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
137087   char **pzErr,                       /* OUT: Error message, if any */
137088   int isCreate                        /* True for xCreate, false for xConnect */
137089 ){
137090   int rc = SQLITE_OK;
137091   Rtree *pRtree;
137092   int nDb;              /* Length of string argv[1] */
137093   int nName;            /* Length of string argv[2] */
137094   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
137095
137096   const char *aErrMsg[] = {
137097     0,                                                    /* 0 */
137098     "Wrong number of columns for an rtree table",         /* 1 */
137099     "Too few columns for an rtree table",                 /* 2 */
137100     "Too many columns for an rtree table"                 /* 3 */
137101   };
137102
137103   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
137104   if( aErrMsg[iErr] ){
137105     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
137106     return SQLITE_ERROR;
137107   }
137108
137109   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
137110
137111   /* Allocate the sqlite3_vtab structure */
137112   nDb = (int)strlen(argv[1]);
137113   nName = (int)strlen(argv[2]);
137114   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
137115   if( !pRtree ){
137116     return SQLITE_NOMEM;
137117   }
137118   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
137119   pRtree->nBusy = 1;
137120   pRtree->base.pModule = &rtreeModule;
137121   pRtree->zDb = (char *)&pRtree[1];
137122   pRtree->zName = &pRtree->zDb[nDb+1];
137123   pRtree->nDim = (argc-4)/2;
137124   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
137125   pRtree->eCoordType = eCoordType;
137126   memcpy(pRtree->zDb, argv[1], nDb);
137127   memcpy(pRtree->zName, argv[2], nName);
137128
137129   /* Figure out the node size to use. */
137130   rc = getNodeSize(db, pRtree, isCreate, pzErr);
137131
137132   /* Create/Connect to the underlying relational database schema. If
137133   ** that is successful, call sqlite3_declare_vtab() to configure
137134   ** the r-tree table schema.
137135   */
137136   if( rc==SQLITE_OK ){
137137     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
137138       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
137139     }else{
137140       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
137141       char *zTmp;
137142       int ii;
137143       for(ii=4; zSql && ii<argc; ii++){
137144         zTmp = zSql;
137145         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
137146         sqlite3_free(zTmp);
137147       }
137148       if( zSql ){
137149         zTmp = zSql;
137150         zSql = sqlite3_mprintf("%s);", zTmp);
137151         sqlite3_free(zTmp);
137152       }
137153       if( !zSql ){
137154         rc = SQLITE_NOMEM;
137155       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
137156         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
137157       }
137158       sqlite3_free(zSql);
137159     }
137160   }
137161
137162   if( rc==SQLITE_OK ){
137163     *ppVtab = (sqlite3_vtab *)pRtree;
137164   }else{
137165     rtreeRelease(pRtree);
137166   }
137167   return rc;
137168 }
137169
137170
137171 /*
137172 ** Implementation of a scalar function that decodes r-tree nodes to
137173 ** human readable strings. This can be used for debugging and analysis.
137174 **
137175 ** The scalar function takes two arguments, a blob of data containing
137176 ** an r-tree node, and the number of dimensions the r-tree indexes.
137177 ** For a two-dimensional r-tree structure called "rt", to deserialize
137178 ** all nodes, a statement like:
137179 **
137180 **   SELECT rtreenode(2, data) FROM rt_node;
137181 **
137182 ** The human readable string takes the form of a Tcl list with one
137183 ** entry for each cell in the r-tree node. Each entry is itself a
137184 ** list, containing the 8-byte rowid/pageno followed by the 
137185 ** <num-dimension>*2 coordinates.
137186 */
137187 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
137188   char *zText = 0;
137189   RtreeNode node;
137190   Rtree tree;
137191   int ii;
137192
137193   UNUSED_PARAMETER(nArg);
137194   memset(&node, 0, sizeof(RtreeNode));
137195   memset(&tree, 0, sizeof(Rtree));
137196   tree.nDim = sqlite3_value_int(apArg[0]);
137197   tree.nBytesPerCell = 8 + 8 * tree.nDim;
137198   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
137199
137200   for(ii=0; ii<NCELL(&node); ii++){
137201     char zCell[512];
137202     int nCell = 0;
137203     RtreeCell cell;
137204     int jj;
137205
137206     nodeGetCell(&tree, &node, ii, &cell);
137207     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
137208     nCell = (int)strlen(zCell);
137209     for(jj=0; jj<tree.nDim*2; jj++){
137210 #ifndef SQLITE_RTREE_INT_ONLY
137211       sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
137212                        (double)cell.aCoord[jj].f);
137213 #else
137214       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
137215                        cell.aCoord[jj].i);
137216 #endif
137217       nCell = (int)strlen(zCell);
137218     }
137219
137220     if( zText ){
137221       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
137222       sqlite3_free(zText);
137223       zText = zTextNew;
137224     }else{
137225       zText = sqlite3_mprintf("{%s}", zCell);
137226     }
137227   }
137228   
137229   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
137230 }
137231
137232 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
137233   UNUSED_PARAMETER(nArg);
137234   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
137235    || sqlite3_value_bytes(apArg[0])<2
137236   ){
137237     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
137238   }else{
137239     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
137240     sqlite3_result_int(ctx, readInt16(zBlob));
137241   }
137242 }
137243
137244 /*
137245 ** Register the r-tree module with database handle db. This creates the
137246 ** virtual table module "rtree" and the debugging/analysis scalar 
137247 ** function "rtreenode".
137248 */
137249 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
137250   const int utf8 = SQLITE_UTF8;
137251   int rc;
137252
137253   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
137254   if( rc==SQLITE_OK ){
137255     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
137256   }
137257   if( rc==SQLITE_OK ){
137258 #ifdef SQLITE_RTREE_INT_ONLY
137259     void *c = (void *)RTREE_COORD_INT32;
137260 #else
137261     void *c = (void *)RTREE_COORD_REAL32;
137262 #endif
137263     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
137264   }
137265   if( rc==SQLITE_OK ){
137266     void *c = (void *)RTREE_COORD_INT32;
137267     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
137268   }
137269
137270   return rc;
137271 }
137272
137273 /*
137274 ** A version of sqlite3_free() that can be used as a callback. This is used
137275 ** in two places - as the destructor for the blob value returned by the
137276 ** invocation of a geometry function, and as the destructor for the geometry
137277 ** functions themselves.
137278 */
137279 static void doSqlite3Free(void *p){
137280   sqlite3_free(p);
137281 }
137282
137283 /*
137284 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
137285 ** scalar user function. This C function is the callback used for all such
137286 ** registered SQL functions.
137287 **
137288 ** The scalar user functions return a blob that is interpreted by r-tree
137289 ** table MATCH operators.
137290 */
137291 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
137292   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
137293   RtreeMatchArg *pBlob;
137294   int nBlob;
137295
137296   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
137297   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
137298   if( !pBlob ){
137299     sqlite3_result_error_nomem(ctx);
137300   }else{
137301     int i;
137302     pBlob->magic = RTREE_GEOMETRY_MAGIC;
137303     pBlob->xGeom = pGeomCtx->xGeom;
137304     pBlob->pContext = pGeomCtx->pContext;
137305     pBlob->nParam = nArg;
137306     for(i=0; i<nArg; i++){
137307 #ifdef SQLITE_RTREE_INT_ONLY
137308       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
137309 #else
137310       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
137311 #endif
137312     }
137313     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
137314   }
137315 }
137316
137317 /*
137318 ** Register a new geometry function for use with the r-tree MATCH operator.
137319 */
137320 SQLITE_API int sqlite3_rtree_geometry_callback(
137321   sqlite3 *db,
137322   const char *zGeom,
137323   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
137324   void *pContext
137325 ){
137326   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
137327
137328   /* Allocate and populate the context object. */
137329   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
137330   if( !pGeomCtx ) return SQLITE_NOMEM;
137331   pGeomCtx->xGeom = xGeom;
137332   pGeomCtx->pContext = pContext;
137333
137334   /* Create the new user-function. Register a destructor function to delete
137335   ** the context object when it is no longer required.  */
137336   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
137337       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
137338   );
137339 }
137340
137341 #if !SQLITE_CORE
137342 SQLITE_API int sqlite3_extension_init(
137343   sqlite3 *db,
137344   char **pzErrMsg,
137345   const sqlite3_api_routines *pApi
137346 ){
137347   SQLITE_EXTENSION_INIT2(pApi)
137348   return sqlite3RtreeInit(db);
137349 }
137350 #endif
137351
137352 #endif
137353
137354 /************** End of rtree.c ***********************************************/
137355 /************** Begin file icu.c *********************************************/
137356 /*
137357 ** 2007 May 6
137358 **
137359 ** The author disclaims copyright to this source code.  In place of
137360 ** a legal notice, here is a blessing:
137361 **
137362 **    May you do good and not evil.
137363 **    May you find forgiveness for yourself and forgive others.
137364 **    May you share freely, never taking more than you give.
137365 **
137366 *************************************************************************
137367 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
137368 **
137369 ** This file implements an integration between the ICU library 
137370 ** ("International Components for Unicode", an open-source library 
137371 ** for handling unicode data) and SQLite. The integration uses 
137372 ** ICU to provide the following to SQLite:
137373 **
137374 **   * An implementation of the SQL regexp() function (and hence REGEXP
137375 **     operator) using the ICU uregex_XX() APIs.
137376 **
137377 **   * Implementations of the SQL scalar upper() and lower() functions
137378 **     for case mapping.
137379 **
137380 **   * Integration of ICU and SQLite collation seqences.
137381 **
137382 **   * An implementation of the LIKE operator that uses ICU to 
137383 **     provide case-independent matching.
137384 */
137385
137386 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
137387
137388 /* Include ICU headers */
137389 #include <unicode/utypes.h>
137390 #include <unicode/uregex.h>
137391 #include <unicode/ustring.h>
137392 #include <unicode/ucol.h>
137393
137394 /* #include <assert.h> */
137395
137396 #ifndef SQLITE_CORE
137397   SQLITE_EXTENSION_INIT1
137398 #else
137399 #endif
137400
137401 /*
137402 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
137403 ** operator.
137404 */
137405 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
137406 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
137407 #endif
137408
137409 /*
137410 ** Version of sqlite3_free() that is always a function, never a macro.
137411 */
137412 static void xFree(void *p){
137413   sqlite3_free(p);
137414 }
137415
137416 /*
137417 ** Compare two UTF-8 strings for equality where the first string is
137418 ** a "LIKE" expression. Return true (1) if they are the same and 
137419 ** false (0) if they are different.
137420 */
137421 static int icuLikeCompare(
137422   const uint8_t *zPattern,   /* LIKE pattern */
137423   const uint8_t *zString,    /* The UTF-8 string to compare against */
137424   const UChar32 uEsc         /* The escape character */
137425 ){
137426   static const int MATCH_ONE = (UChar32)'_';
137427   static const int MATCH_ALL = (UChar32)'%';
137428
137429   int iPattern = 0;       /* Current byte index in zPattern */
137430   int iString = 0;        /* Current byte index in zString */
137431
137432   int prevEscape = 0;     /* True if the previous character was uEsc */
137433
137434   while( zPattern[iPattern]!=0 ){
137435
137436     /* Read (and consume) the next character from the input pattern. */
137437     UChar32 uPattern;
137438     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
137439     assert(uPattern!=0);
137440
137441     /* There are now 4 possibilities:
137442     **
137443     **     1. uPattern is an unescaped match-all character "%",
137444     **     2. uPattern is an unescaped match-one character "_",
137445     **     3. uPattern is an unescaped escape character, or
137446     **     4. uPattern is to be handled as an ordinary character
137447     */
137448     if( !prevEscape && uPattern==MATCH_ALL ){
137449       /* Case 1. */
137450       uint8_t c;
137451
137452       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
137453       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
137454       ** test string.
137455       */
137456       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
137457         if( c==MATCH_ONE ){
137458           if( zString[iString]==0 ) return 0;
137459           U8_FWD_1_UNSAFE(zString, iString);
137460         }
137461         iPattern++;
137462       }
137463
137464       if( zPattern[iPattern]==0 ) return 1;
137465
137466       while( zString[iString] ){
137467         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
137468           return 1;
137469         }
137470         U8_FWD_1_UNSAFE(zString, iString);
137471       }
137472       return 0;
137473
137474     }else if( !prevEscape && uPattern==MATCH_ONE ){
137475       /* Case 2. */
137476       if( zString[iString]==0 ) return 0;
137477       U8_FWD_1_UNSAFE(zString, iString);
137478
137479     }else if( !prevEscape && uPattern==uEsc){
137480       /* Case 3. */
137481       prevEscape = 1;
137482
137483     }else{
137484       /* Case 4. */
137485       UChar32 uString;
137486       U8_NEXT_UNSAFE(zString, iString, uString);
137487       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
137488       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
137489       if( uString!=uPattern ){
137490         return 0;
137491       }
137492       prevEscape = 0;
137493     }
137494   }
137495
137496   return zString[iString]==0;
137497 }
137498
137499 /*
137500 ** Implementation of the like() SQL function.  This function implements
137501 ** the build-in LIKE operator.  The first argument to the function is the
137502 ** pattern and the second argument is the string.  So, the SQL statements:
137503 **
137504 **       A LIKE B
137505 **
137506 ** is implemented as like(B, A). If there is an escape character E, 
137507 **
137508 **       A LIKE B ESCAPE E
137509 **
137510 ** is mapped to like(B, A, E).
137511 */
137512 static void icuLikeFunc(
137513   sqlite3_context *context, 
137514   int argc, 
137515   sqlite3_value **argv
137516 ){
137517   const unsigned char *zA = sqlite3_value_text(argv[0]);
137518   const unsigned char *zB = sqlite3_value_text(argv[1]);
137519   UChar32 uEsc = 0;
137520
137521   /* Limit the length of the LIKE or GLOB pattern to avoid problems
137522   ** of deep recursion and N*N behavior in patternCompare().
137523   */
137524   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
137525     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
137526     return;
137527   }
137528
137529
137530   if( argc==3 ){
137531     /* The escape character string must consist of a single UTF-8 character.
137532     ** Otherwise, return an error.
137533     */
137534     int nE= sqlite3_value_bytes(argv[2]);
137535     const unsigned char *zE = sqlite3_value_text(argv[2]);
137536     int i = 0;
137537     if( zE==0 ) return;
137538     U8_NEXT(zE, i, nE, uEsc);
137539     if( i!=nE){
137540       sqlite3_result_error(context, 
137541           "ESCAPE expression must be a single character", -1);
137542       return;
137543     }
137544   }
137545
137546   if( zA && zB ){
137547     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
137548   }
137549 }
137550
137551 /*
137552 ** This function is called when an ICU function called from within
137553 ** the implementation of an SQL scalar function returns an error.
137554 **
137555 ** The scalar function context passed as the first argument is 
137556 ** loaded with an error message based on the following two args.
137557 */
137558 static void icuFunctionError(
137559   sqlite3_context *pCtx,       /* SQLite scalar function context */
137560   const char *zName,           /* Name of ICU function that failed */
137561   UErrorCode e                 /* Error code returned by ICU function */
137562 ){
137563   char zBuf[128];
137564   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
137565   zBuf[127] = '\0';
137566   sqlite3_result_error(pCtx, zBuf, -1);
137567 }
137568
137569 /*
137570 ** Function to delete compiled regexp objects. Registered as
137571 ** a destructor function with sqlite3_set_auxdata().
137572 */
137573 static void icuRegexpDelete(void *p){
137574   URegularExpression *pExpr = (URegularExpression *)p;
137575   uregex_close(pExpr);
137576 }
137577
137578 /*
137579 ** Implementation of SQLite REGEXP operator. This scalar function takes
137580 ** two arguments. The first is a regular expression pattern to compile
137581 ** the second is a string to match against that pattern. If either 
137582 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
137583 ** is 1 if the string matches the pattern, or 0 otherwise.
137584 **
137585 ** SQLite maps the regexp() function to the regexp() operator such
137586 ** that the following two are equivalent:
137587 **
137588 **     zString REGEXP zPattern
137589 **     regexp(zPattern, zString)
137590 **
137591 ** Uses the following ICU regexp APIs:
137592 **
137593 **     uregex_open()
137594 **     uregex_matches()
137595 **     uregex_close()
137596 */
137597 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
137598   UErrorCode status = U_ZERO_ERROR;
137599   URegularExpression *pExpr;
137600   UBool res;
137601   const UChar *zString = sqlite3_value_text16(apArg[1]);
137602
137603   (void)nArg;  /* Unused parameter */
137604
137605   /* If the left hand side of the regexp operator is NULL, 
137606   ** then the result is also NULL. 
137607   */
137608   if( !zString ){
137609     return;
137610   }
137611
137612   pExpr = sqlite3_get_auxdata(p, 0);
137613   if( !pExpr ){
137614     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
137615     if( !zPattern ){
137616       return;
137617     }
137618     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
137619
137620     if( U_SUCCESS(status) ){
137621       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
137622     }else{
137623       assert(!pExpr);
137624       icuFunctionError(p, "uregex_open", status);
137625       return;
137626     }
137627   }
137628
137629   /* Configure the text that the regular expression operates on. */
137630   uregex_setText(pExpr, zString, -1, &status);
137631   if( !U_SUCCESS(status) ){
137632     icuFunctionError(p, "uregex_setText", status);
137633     return;
137634   }
137635
137636   /* Attempt the match */
137637   res = uregex_matches(pExpr, 0, &status);
137638   if( !U_SUCCESS(status) ){
137639     icuFunctionError(p, "uregex_matches", status);
137640     return;
137641   }
137642
137643   /* Set the text that the regular expression operates on to a NULL
137644   ** pointer. This is not really necessary, but it is tidier than 
137645   ** leaving the regular expression object configured with an invalid
137646   ** pointer after this function returns.
137647   */
137648   uregex_setText(pExpr, 0, 0, &status);
137649
137650   /* Return 1 or 0. */
137651   sqlite3_result_int(p, res ? 1 : 0);
137652 }
137653
137654 /*
137655 ** Implementations of scalar functions for case mapping - upper() and 
137656 ** lower(). Function upper() converts its input to upper-case (ABC).
137657 ** Function lower() converts to lower-case (abc).
137658 **
137659 ** ICU provides two types of case mapping, "general" case mapping and
137660 ** "language specific". Refer to ICU documentation for the differences
137661 ** between the two.
137662 **
137663 ** To utilise "general" case mapping, the upper() or lower() scalar 
137664 ** functions are invoked with one argument:
137665 **
137666 **     upper('ABC') -> 'abc'
137667 **     lower('abc') -> 'ABC'
137668 **
137669 ** To access ICU "language specific" case mapping, upper() or lower()
137670 ** should be invoked with two arguments. The second argument is the name
137671 ** of the locale to use. Passing an empty string ("") or SQL NULL value
137672 ** as the second argument is the same as invoking the 1 argument version
137673 ** of upper() or lower().
137674 **
137675 **     lower('I', 'en_us') -> 'i'
137676 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
137677 **
137678 ** http://www.icu-project.org/userguide/posix.html#case_mappings
137679 */
137680 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
137681   const UChar *zInput;
137682   UChar *zOutput;
137683   int nInput;
137684   int nOutput;
137685
137686   UErrorCode status = U_ZERO_ERROR;
137687   const char *zLocale = 0;
137688
137689   assert(nArg==1 || nArg==2);
137690   if( nArg==2 ){
137691     zLocale = (const char *)sqlite3_value_text(apArg[1]);
137692   }
137693
137694   zInput = sqlite3_value_text16(apArg[0]);
137695   if( !zInput ){
137696     return;
137697   }
137698   nInput = sqlite3_value_bytes16(apArg[0]);
137699
137700   nOutput = nInput * 2 + 2;
137701   zOutput = sqlite3_malloc(nOutput);
137702   if( !zOutput ){
137703     return;
137704   }
137705
137706   if( sqlite3_user_data(p) ){
137707     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
137708   }else{
137709     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
137710   }
137711
137712   if( !U_SUCCESS(status) ){
137713     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
137714     return;
137715   }
137716
137717   sqlite3_result_text16(p, zOutput, -1, xFree);
137718 }
137719
137720 /*
137721 ** Collation sequence destructor function. The pCtx argument points to
137722 ** a UCollator structure previously allocated using ucol_open().
137723 */
137724 static void icuCollationDel(void *pCtx){
137725   UCollator *p = (UCollator *)pCtx;
137726   ucol_close(p);
137727 }
137728
137729 /*
137730 ** Collation sequence comparison function. The pCtx argument points to
137731 ** a UCollator structure previously allocated using ucol_open().
137732 */
137733 static int icuCollationColl(
137734   void *pCtx,
137735   int nLeft,
137736   const void *zLeft,
137737   int nRight,
137738   const void *zRight
137739 ){
137740   UCollationResult res;
137741   UCollator *p = (UCollator *)pCtx;
137742   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
137743   switch( res ){
137744     case UCOL_LESS:    return -1;
137745     case UCOL_GREATER: return +1;
137746     case UCOL_EQUAL:   return 0;
137747   }
137748   assert(!"Unexpected return value from ucol_strcoll()");
137749   return 0;
137750 }
137751
137752 /*
137753 ** Implementation of the scalar function icu_load_collation().
137754 **
137755 ** This scalar function is used to add ICU collation based collation 
137756 ** types to an SQLite database connection. It is intended to be called
137757 ** as follows:
137758 **
137759 **     SELECT icu_load_collation(<locale>, <collation-name>);
137760 **
137761 ** Where <locale> is a string containing an ICU locale identifier (i.e.
137762 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
137763 ** collation sequence to create.
137764 */
137765 static void icuLoadCollation(
137766   sqlite3_context *p, 
137767   int nArg, 
137768   sqlite3_value **apArg
137769 ){
137770   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
137771   UErrorCode status = U_ZERO_ERROR;
137772   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
137773   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
137774   UCollator *pUCollator;    /* ICU library collation object */
137775   int rc;                   /* Return code from sqlite3_create_collation_x() */
137776
137777   assert(nArg==2);
137778   zLocale = (const char *)sqlite3_value_text(apArg[0]);
137779   zName = (const char *)sqlite3_value_text(apArg[1]);
137780
137781   if( !zLocale || !zName ){
137782     return;
137783   }
137784
137785   pUCollator = ucol_open(zLocale, &status);
137786   if( !U_SUCCESS(status) ){
137787     icuFunctionError(p, "ucol_open", status);
137788     return;
137789   }
137790   assert(p);
137791
137792   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
137793       icuCollationColl, icuCollationDel
137794   );
137795   if( rc!=SQLITE_OK ){
137796     ucol_close(pUCollator);
137797     sqlite3_result_error(p, "Error registering collation function", -1);
137798   }
137799 }
137800
137801 /*
137802 ** Register the ICU extension functions with database db.
137803 */
137804 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
137805   struct IcuScalar {
137806     const char *zName;                        /* Function name */
137807     int nArg;                                 /* Number of arguments */
137808     int enc;                                  /* Optimal text encoding */
137809     void *pContext;                           /* sqlite3_user_data() context */
137810     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
137811   } scalars[] = {
137812     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
137813
137814     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
137815     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
137816     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
137817     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
137818
137819     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
137820     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
137821     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
137822     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
137823
137824     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
137825     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
137826
137827     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
137828   };
137829
137830   int rc = SQLITE_OK;
137831   int i;
137832
137833   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
137834     struct IcuScalar *p = &scalars[i];
137835     rc = sqlite3_create_function(
137836         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
137837     );
137838   }
137839
137840   return rc;
137841 }
137842
137843 #if !SQLITE_CORE
137844 SQLITE_API int sqlite3_extension_init(
137845   sqlite3 *db, 
137846   char **pzErrMsg,
137847   const sqlite3_api_routines *pApi
137848 ){
137849   SQLITE_EXTENSION_INIT2(pApi)
137850   return sqlite3IcuInit(db);
137851 }
137852 #endif
137853
137854 #endif
137855
137856 /************** End of icu.c *************************************************/
137857 /************** Begin file fts3_icu.c ****************************************/
137858 /*
137859 ** 2007 June 22
137860 **
137861 ** The author disclaims copyright to this source code.  In place of
137862 ** a legal notice, here is a blessing:
137863 **
137864 **    May you do good and not evil.
137865 **    May you find forgiveness for yourself and forgive others.
137866 **    May you share freely, never taking more than you give.
137867 **
137868 *************************************************************************
137869 ** This file implements a tokenizer for fts3 based on the ICU library.
137870 */
137871 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
137872 #ifdef SQLITE_ENABLE_ICU
137873
137874 /* #include <assert.h> */
137875 /* #include <string.h> */
137876
137877 #include <unicode/ubrk.h>
137878 /* #include <unicode/ucol.h> */
137879 /* #include <unicode/ustring.h> */
137880 #include <unicode/utf16.h>
137881
137882 typedef struct IcuTokenizer IcuTokenizer;
137883 typedef struct IcuCursor IcuCursor;
137884
137885 struct IcuTokenizer {
137886   sqlite3_tokenizer base;
137887   char *zLocale;
137888 };
137889
137890 struct IcuCursor {
137891   sqlite3_tokenizer_cursor base;
137892
137893   UBreakIterator *pIter;      /* ICU break-iterator object */
137894   int nChar;                  /* Number of UChar elements in pInput */
137895   UChar *aChar;               /* Copy of input using utf-16 encoding */
137896   int *aOffset;               /* Offsets of each character in utf-8 input */
137897
137898   int nBuffer;
137899   char *zBuffer;
137900
137901   int iToken;
137902 };
137903
137904 /*
137905 ** Create a new tokenizer instance.
137906 */
137907 static int icuCreate(
137908   int argc,                            /* Number of entries in argv[] */
137909   const char * const *argv,            /* Tokenizer creation arguments */
137910   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
137911 ){
137912   IcuTokenizer *p;
137913   int n = 0;
137914
137915   if( argc>0 ){
137916     n = strlen(argv[0])+1;
137917   }
137918   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
137919   if( !p ){
137920     return SQLITE_NOMEM;
137921   }
137922   memset(p, 0, sizeof(IcuTokenizer));
137923
137924   if( n ){
137925     p->zLocale = (char *)&p[1];
137926     memcpy(p->zLocale, argv[0], n);
137927   }
137928
137929   *ppTokenizer = (sqlite3_tokenizer *)p;
137930
137931   return SQLITE_OK;
137932 }
137933
137934 /*
137935 ** Destroy a tokenizer
137936 */
137937 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
137938   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
137939   sqlite3_free(p);
137940   return SQLITE_OK;
137941 }
137942
137943 /*
137944 ** Prepare to begin tokenizing a particular string.  The input
137945 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
137946 ** used to incrementally tokenize this string is returned in 
137947 ** *ppCursor.
137948 */
137949 static int icuOpen(
137950   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
137951   const char *zInput,                    /* Input string */
137952   int nInput,                            /* Length of zInput in bytes */
137953   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
137954 ){
137955   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
137956   IcuCursor *pCsr;
137957
137958   const int32_t opt = U_FOLD_CASE_DEFAULT;
137959   UErrorCode status = U_ZERO_ERROR;
137960   int nChar;
137961
137962   UChar32 c;
137963   int iInput = 0;
137964   int iOut = 0;
137965
137966   *ppCursor = 0;
137967
137968   if( zInput==0 ){
137969     nInput = 0;
137970     zInput = "";
137971   }else if( nInput<0 ){
137972     nInput = strlen(zInput);
137973   }
137974   nChar = nInput+1;
137975   pCsr = (IcuCursor *)sqlite3_malloc(
137976       sizeof(IcuCursor) +                /* IcuCursor */
137977       ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
137978       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
137979   );
137980   if( !pCsr ){
137981     return SQLITE_NOMEM;
137982   }
137983   memset(pCsr, 0, sizeof(IcuCursor));
137984   pCsr->aChar = (UChar *)&pCsr[1];
137985   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
137986
137987   pCsr->aOffset[iOut] = iInput;
137988   U8_NEXT(zInput, iInput, nInput, c); 
137989   while( c>0 ){
137990     int isError = 0;
137991     c = u_foldCase(c, opt);
137992     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
137993     if( isError ){
137994       sqlite3_free(pCsr);
137995       return SQLITE_ERROR;
137996     }
137997     pCsr->aOffset[iOut] = iInput;
137998
137999     if( iInput<nInput ){
138000       U8_NEXT(zInput, iInput, nInput, c);
138001     }else{
138002       c = 0;
138003     }
138004   }
138005
138006   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
138007   if( !U_SUCCESS(status) ){
138008     sqlite3_free(pCsr);
138009     return SQLITE_ERROR;
138010   }
138011   pCsr->nChar = iOut;
138012
138013   ubrk_first(pCsr->pIter);
138014   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
138015   return SQLITE_OK;
138016 }
138017
138018 /*
138019 ** Close a tokenization cursor previously opened by a call to icuOpen().
138020 */
138021 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
138022   IcuCursor *pCsr = (IcuCursor *)pCursor;
138023   ubrk_close(pCsr->pIter);
138024   sqlite3_free(pCsr->zBuffer);
138025   sqlite3_free(pCsr);
138026   return SQLITE_OK;
138027 }
138028
138029 /*
138030 ** Extract the next token from a tokenization cursor.
138031 */
138032 static int icuNext(
138033   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
138034   const char **ppToken,               /* OUT: *ppToken is the token text */
138035   int *pnBytes,                       /* OUT: Number of bytes in token */
138036   int *piStartOffset,                 /* OUT: Starting offset of token */
138037   int *piEndOffset,                   /* OUT: Ending offset of token */
138038   int *piPosition                     /* OUT: Position integer of token */
138039 ){
138040   IcuCursor *pCsr = (IcuCursor *)pCursor;
138041
138042   int iStart = 0;
138043   int iEnd = 0;
138044   int nByte = 0;
138045
138046   while( iStart==iEnd ){
138047     UChar32 c;
138048
138049     iStart = ubrk_current(pCsr->pIter);
138050     iEnd = ubrk_next(pCsr->pIter);
138051     if( iEnd==UBRK_DONE ){
138052       return SQLITE_DONE;
138053     }
138054
138055     while( iStart<iEnd ){
138056       int iWhite = iStart;
138057       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
138058       if( u_isspace(c) ){
138059         iStart = iWhite;
138060       }else{
138061         break;
138062       }
138063     }
138064     assert(iStart<=iEnd);
138065   }
138066
138067   do {
138068     UErrorCode status = U_ZERO_ERROR;
138069     if( nByte ){
138070       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
138071       if( !zNew ){
138072         return SQLITE_NOMEM;
138073       }
138074       pCsr->zBuffer = zNew;
138075       pCsr->nBuffer = nByte;
138076     }
138077
138078     u_strToUTF8(
138079         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
138080         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
138081         &status                                  /* Output success/failure */
138082     );
138083   } while( nByte>pCsr->nBuffer );
138084
138085   *ppToken = pCsr->zBuffer;
138086   *pnBytes = nByte;
138087   *piStartOffset = pCsr->aOffset[iStart];
138088   *piEndOffset = pCsr->aOffset[iEnd];
138089   *piPosition = pCsr->iToken++;
138090
138091   return SQLITE_OK;
138092 }
138093
138094 /*
138095 ** The set of routines that implement the simple tokenizer
138096 */
138097 static const sqlite3_tokenizer_module icuTokenizerModule = {
138098   0,                           /* iVersion */
138099   icuCreate,                   /* xCreate  */
138100   icuDestroy,                  /* xCreate  */
138101   icuOpen,                     /* xOpen    */
138102   icuClose,                    /* xClose   */
138103   icuNext,                     /* xNext    */
138104 };
138105
138106 /*
138107 ** Set *ppModule to point at the implementation of the ICU tokenizer.
138108 */
138109 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
138110   sqlite3_tokenizer_module const**ppModule
138111 ){
138112   *ppModule = &icuTokenizerModule;
138113 }
138114
138115 #endif /* defined(SQLITE_ENABLE_ICU) */
138116 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
138117
138118 /************** End of fts3_icu.c ********************************************/